1 //===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
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 //===----------------------------------------------------------------------===//
8 // This file implements semantic analysis for C++ templates.
9 //===----------------------------------------------------------------------===//
11 #include "TreeTransform.h"
12 #include "clang/AST/ASTConsumer.h"
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/Decl.h"
15 #include "clang/AST/DeclFriend.h"
16 #include "clang/AST/DeclTemplate.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/RecursiveASTVisitor.h"
20 #include "clang/AST/TemplateName.h"
21 #include "clang/AST/TypeVisitor.h"
22 #include "clang/Basic/Builtins.h"
23 #include "clang/Basic/DiagnosticSema.h"
24 #include "clang/Basic/LangOptions.h"
25 #include "clang/Basic/PartialDiagnostic.h"
26 #include "clang/Basic/SourceLocation.h"
27 #include "clang/Basic/Stack.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Sema/DeclSpec.h"
30 #include "clang/Sema/EnterExpressionEvaluationContext.h"
31 #include "clang/Sema/Initialization.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/Overload.h"
34 #include "clang/Sema/ParsedTemplate.h"
35 #include "clang/Sema/Scope.h"
36 #include "clang/Sema/SemaInternal.h"
37 #include "clang/Sema/Template.h"
38 #include "clang/Sema/TemplateDeduction.h"
39 #include "llvm/ADT/SmallBitVector.h"
40 #include "llvm/ADT/SmallString.h"
41 #include "llvm/ADT/StringExtras.h"
45 using namespace clang
;
48 // Exported for use by Parser.
50 clang::getTemplateParamsRange(TemplateParameterList
const * const *Ps
,
52 if (!N
) return SourceRange();
53 return SourceRange(Ps
[0]->getTemplateLoc(), Ps
[N
-1]->getRAngleLoc());
56 unsigned Sema::getTemplateDepth(Scope
*S
) const {
59 // Each template parameter scope represents one level of template parameter
61 for (Scope
*TempParamScope
= S
->getTemplateParamParent(); TempParamScope
;
62 TempParamScope
= TempParamScope
->getParent()->getTemplateParamParent()) {
66 // Note that there are template parameters with the given depth.
67 auto ParamsAtDepth
= [&](unsigned D
) { Depth
= std::max(Depth
, D
+ 1); };
69 // Look for parameters of an enclosing generic lambda. We don't create a
70 // template parameter scope for these.
71 for (FunctionScopeInfo
*FSI
: getFunctionScopes()) {
72 if (auto *LSI
= dyn_cast
<LambdaScopeInfo
>(FSI
)) {
73 if (!LSI
->TemplateParams
.empty()) {
74 ParamsAtDepth(LSI
->AutoTemplateParameterDepth
);
77 if (LSI
->GLTemplateParameterList
) {
78 ParamsAtDepth(LSI
->GLTemplateParameterList
->getDepth());
84 // Look for parameters of an enclosing terse function template. We don't
85 // create a template parameter scope for these either.
86 for (const InventedTemplateParameterInfo
&Info
:
87 getInventedParameterInfos()) {
88 if (!Info
.TemplateParams
.empty()) {
89 ParamsAtDepth(Info
.AutoTemplateParameterDepth
);
97 /// \brief Determine whether the declaration found is acceptable as the name
98 /// of a template and, if so, return that template declaration. Otherwise,
101 /// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
102 /// is true. In all other cases it will return a TemplateDecl (or null).
103 NamedDecl
*Sema::getAsTemplateNameDecl(NamedDecl
*D
,
104 bool AllowFunctionTemplates
,
105 bool AllowDependent
) {
106 D
= D
->getUnderlyingDecl();
108 if (isa
<TemplateDecl
>(D
)) {
109 if (!AllowFunctionTemplates
&& isa
<FunctionTemplateDecl
>(D
))
115 if (const auto *Record
= dyn_cast
<CXXRecordDecl
>(D
)) {
116 // C++ [temp.local]p1:
117 // Like normal (non-template) classes, class templates have an
118 // injected-class-name (Clause 9). The injected-class-name
119 // can be used with or without a template-argument-list. When
120 // it is used without a template-argument-list, it is
121 // equivalent to the injected-class-name followed by the
122 // template-parameters of the class template enclosed in
123 // <>. When it is used with a template-argument-list, it
124 // refers to the specified class template specialization,
125 // which could be the current specialization or another
127 if (Record
->isInjectedClassName()) {
128 Record
= cast
<CXXRecordDecl
>(Record
->getDeclContext());
129 if (Record
->getDescribedClassTemplate())
130 return Record
->getDescribedClassTemplate();
132 if (const auto *Spec
= dyn_cast
<ClassTemplateSpecializationDecl
>(Record
))
133 return Spec
->getSpecializedTemplate();
139 // 'using Dependent::foo;' can resolve to a template name.
140 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
141 // injected-class-name).
142 if (AllowDependent
&& isa
<UnresolvedUsingValueDecl
>(D
))
148 void Sema::FilterAcceptableTemplateNames(LookupResult
&R
,
149 bool AllowFunctionTemplates
,
150 bool AllowDependent
) {
151 LookupResult::Filter filter
= R
.makeFilter();
152 while (filter
.hasNext()) {
153 NamedDecl
*Orig
= filter
.next();
154 if (!getAsTemplateNameDecl(Orig
, AllowFunctionTemplates
, AllowDependent
))
160 bool Sema::hasAnyAcceptableTemplateNames(LookupResult
&R
,
161 bool AllowFunctionTemplates
,
163 bool AllowNonTemplateFunctions
) {
164 for (LookupResult::iterator I
= R
.begin(), IEnd
= R
.end(); I
!= IEnd
; ++I
) {
165 if (getAsTemplateNameDecl(*I
, AllowFunctionTemplates
, AllowDependent
))
167 if (AllowNonTemplateFunctions
&&
168 isa
<FunctionDecl
>((*I
)->getUnderlyingDecl()))
175 TemplateNameKind
Sema::isTemplateName(Scope
*S
,
177 bool hasTemplateKeyword
,
178 const UnqualifiedId
&Name
,
179 ParsedType ObjectTypePtr
,
180 bool EnteringContext
,
181 TemplateTy
&TemplateResult
,
182 bool &MemberOfUnknownSpecialization
,
183 bool Disambiguation
) {
184 assert(getLangOpts().CPlusPlus
&& "No template names in C!");
186 DeclarationName TName
;
187 MemberOfUnknownSpecialization
= false;
189 switch (Name
.getKind()) {
190 case UnqualifiedIdKind::IK_Identifier
:
191 TName
= DeclarationName(Name
.Identifier
);
194 case UnqualifiedIdKind::IK_OperatorFunctionId
:
195 TName
= Context
.DeclarationNames
.getCXXOperatorName(
196 Name
.OperatorFunctionId
.Operator
);
199 case UnqualifiedIdKind::IK_LiteralOperatorId
:
200 TName
= Context
.DeclarationNames
.getCXXLiteralOperatorName(Name
.Identifier
);
204 return TNK_Non_template
;
207 QualType ObjectType
= ObjectTypePtr
.get();
209 AssumedTemplateKind AssumedTemplate
;
210 LookupResult
R(*this, TName
, Name
.getBeginLoc(), LookupOrdinaryName
);
211 if (LookupTemplateName(R
, S
, SS
, ObjectType
, EnteringContext
,
212 MemberOfUnknownSpecialization
, SourceLocation(),
214 /*AllowTypoCorrection=*/!Disambiguation
))
215 return TNK_Non_template
;
217 if (AssumedTemplate
!= AssumedTemplateKind::None
) {
218 TemplateResult
= TemplateTy::make(Context
.getAssumedTemplateName(TName
));
219 // Let the parser know whether we found nothing or found functions; if we
220 // found nothing, we want to more carefully check whether this is actually
221 // a function template name versus some other kind of undeclared identifier.
222 return AssumedTemplate
== AssumedTemplateKind::FoundNothing
223 ? TNK_Undeclared_template
224 : TNK_Function_template
;
228 return TNK_Non_template
;
230 NamedDecl
*D
= nullptr;
231 UsingShadowDecl
*FoundUsingShadow
= dyn_cast
<UsingShadowDecl
>(*R
.begin());
232 if (R
.isAmbiguous()) {
233 // If we got an ambiguity involving a non-function template, treat this
234 // as a template name, and pick an arbitrary template for error recovery.
235 bool AnyFunctionTemplates
= false;
236 for (NamedDecl
*FoundD
: R
) {
237 if (NamedDecl
*FoundTemplate
= getAsTemplateNameDecl(FoundD
)) {
238 if (isa
<FunctionTemplateDecl
>(FoundTemplate
))
239 AnyFunctionTemplates
= true;
242 FoundUsingShadow
= dyn_cast
<UsingShadowDecl
>(FoundD
);
248 // If we didn't find any templates at all, this isn't a template name.
249 // Leave the ambiguity for a later lookup to diagnose.
250 if (!D
&& !AnyFunctionTemplates
) {
251 R
.suppressDiagnostics();
252 return TNK_Non_template
;
255 // If the only templates were function templates, filter out the rest.
256 // We'll diagnose the ambiguity later.
258 FilterAcceptableTemplateNames(R
);
261 // At this point, we have either picked a single template name declaration D
262 // or we have a non-empty set of results R containing either one template name
263 // declaration or a set of function templates.
265 TemplateName Template
;
266 TemplateNameKind TemplateKind
;
268 unsigned ResultCount
= R
.end() - R
.begin();
269 if (!D
&& ResultCount
> 1) {
270 // We assume that we'll preserve the qualifier from a function
271 // template name in other ways.
272 Template
= Context
.getOverloadedTemplateName(R
.begin(), R
.end());
273 TemplateKind
= TNK_Function_template
;
275 // We'll do this lookup again later.
276 R
.suppressDiagnostics();
279 D
= getAsTemplateNameDecl(*R
.begin());
280 assert(D
&& "unambiguous result is not a template name");
283 if (isa
<UnresolvedUsingValueDecl
>(D
)) {
284 // We don't yet know whether this is a template-name or not.
285 MemberOfUnknownSpecialization
= true;
286 return TNK_Non_template
;
289 TemplateDecl
*TD
= cast
<TemplateDecl
>(D
);
291 FoundUsingShadow
? TemplateName(FoundUsingShadow
) : TemplateName(TD
);
292 assert(!FoundUsingShadow
|| FoundUsingShadow
->getTargetDecl() == TD
);
293 if (SS
.isSet() && !SS
.isInvalid()) {
294 NestedNameSpecifier
*Qualifier
= SS
.getScopeRep();
295 Template
= Context
.getQualifiedTemplateName(Qualifier
, hasTemplateKeyword
,
299 if (isa
<FunctionTemplateDecl
>(TD
)) {
300 TemplateKind
= TNK_Function_template
;
302 // We'll do this lookup again later.
303 R
.suppressDiagnostics();
305 assert(isa
<ClassTemplateDecl
>(TD
) || isa
<TemplateTemplateParmDecl
>(TD
) ||
306 isa
<TypeAliasTemplateDecl
>(TD
) || isa
<VarTemplateDecl
>(TD
) ||
307 isa
<BuiltinTemplateDecl
>(TD
) || isa
<ConceptDecl
>(TD
));
309 isa
<VarTemplateDecl
>(TD
) ? TNK_Var_template
:
310 isa
<ConceptDecl
>(TD
) ? TNK_Concept_template
:
315 TemplateResult
= TemplateTy::make(Template
);
319 bool Sema::isDeductionGuideName(Scope
*S
, const IdentifierInfo
&Name
,
320 SourceLocation NameLoc
, CXXScopeSpec
&SS
,
321 ParsedTemplateTy
*Template
/*=nullptr*/) {
322 bool MemberOfUnknownSpecialization
= false;
324 // We could use redeclaration lookup here, but we don't need to: the
325 // syntactic form of a deduction guide is enough to identify it even
326 // if we can't look up the template name at all.
327 LookupResult
R(*this, DeclarationName(&Name
), NameLoc
, LookupOrdinaryName
);
328 if (LookupTemplateName(R
, S
, SS
, /*ObjectType*/ QualType(),
329 /*EnteringContext*/ false,
330 MemberOfUnknownSpecialization
))
333 if (R
.empty()) return false;
334 if (R
.isAmbiguous()) {
335 // FIXME: Diagnose an ambiguity if we find at least one template.
336 R
.suppressDiagnostics();
340 // We only treat template-names that name type templates as valid deduction
342 TemplateDecl
*TD
= R
.getAsSingle
<TemplateDecl
>();
343 if (!TD
|| !getAsTypeTemplateDecl(TD
))
347 *Template
= TemplateTy::make(TemplateName(TD
));
351 bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo
&II
,
352 SourceLocation IILoc
,
354 const CXXScopeSpec
*SS
,
355 TemplateTy
&SuggestedTemplate
,
356 TemplateNameKind
&SuggestedKind
) {
357 // We can't recover unless there's a dependent scope specifier preceding the
359 // FIXME: Typo correction?
360 if (!SS
|| !SS
->isSet() || !isDependentScopeSpecifier(*SS
) ||
361 computeDeclContext(*SS
))
364 // The code is missing a 'template' keyword prior to the dependent template
366 NestedNameSpecifier
*Qualifier
= (NestedNameSpecifier
*)SS
->getScopeRep();
367 Diag(IILoc
, diag::err_template_kw_missing
)
368 << Qualifier
<< II
.getName()
369 << FixItHint::CreateInsertion(IILoc
, "template ");
371 = TemplateTy::make(Context
.getDependentTemplateName(Qualifier
, &II
));
372 SuggestedKind
= TNK_Dependent_template_name
;
376 bool Sema::LookupTemplateName(LookupResult
&Found
,
377 Scope
*S
, CXXScopeSpec
&SS
,
379 bool EnteringContext
,
380 bool &MemberOfUnknownSpecialization
,
381 RequiredTemplateKind RequiredTemplate
,
382 AssumedTemplateKind
*ATK
,
383 bool AllowTypoCorrection
) {
385 *ATK
= AssumedTemplateKind::None
;
390 Found
.setTemplateNameLookup(true);
392 // Determine where to perform name lookup
393 MemberOfUnknownSpecialization
= false;
394 DeclContext
*LookupCtx
= nullptr;
395 bool IsDependent
= false;
396 if (!ObjectType
.isNull()) {
397 // This nested-name-specifier occurs in a member access expression, e.g.,
398 // x->B::f, and we are looking into the type of the object.
399 assert(SS
.isEmpty() && "ObjectType and scope specifier cannot coexist");
400 LookupCtx
= computeDeclContext(ObjectType
);
401 IsDependent
= !LookupCtx
&& ObjectType
->isDependentType();
402 assert((IsDependent
|| !ObjectType
->isIncompleteType() ||
403 !ObjectType
->getAs
<TagType
>() ||
404 ObjectType
->castAs
<TagType
>()->isBeingDefined()) &&
405 "Caller should have completed object type");
407 // Template names cannot appear inside an Objective-C class or object type
410 // FIXME: This is wrong. For example:
412 // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
414 // vi.Vec<int>::~Vec<int>();
416 // ... should be accepted but we will not treat 'Vec' as a template name
417 // here. The right thing to do would be to check if the name is a valid
418 // vector component name, and look up a template name if not. And similarly
419 // for lookups into Objective-C class and object types, where the same
420 // problem can arise.
421 if (ObjectType
->isObjCObjectOrInterfaceType() ||
422 ObjectType
->isVectorType()) {
426 } else if (SS
.isNotEmpty()) {
427 // This nested-name-specifier occurs after another nested-name-specifier,
428 // so long into the context associated with the prior nested-name-specifier.
429 LookupCtx
= computeDeclContext(SS
, EnteringContext
);
430 IsDependent
= !LookupCtx
&& isDependentScopeSpecifier(SS
);
432 // The declaration context must be complete.
433 if (LookupCtx
&& RequireCompleteDeclContext(SS
, LookupCtx
))
437 bool ObjectTypeSearchedInScope
= false;
438 bool AllowFunctionTemplatesInLookup
= true;
440 // Perform "qualified" name lookup into the declaration context we
441 // computed, which is either the type of the base of a member access
442 // expression or the declaration context associated with a prior
443 // nested-name-specifier.
444 LookupQualifiedName(Found
, LookupCtx
);
446 // FIXME: The C++ standard does not clearly specify what happens in the
447 // case where the object type is dependent, and implementations vary. In
448 // Clang, we treat a name after a . or -> as a template-name if lookup
449 // finds a non-dependent member or member of the current instantiation that
450 // is a type template, or finds no such members and lookup in the context
451 // of the postfix-expression finds a type template. In the latter case, the
452 // name is nonetheless dependent, and we may resolve it to a member of an
453 // unknown specialization when we come to instantiate the template.
454 IsDependent
|= Found
.wasNotFoundInCurrentInstantiation();
457 if (SS
.isEmpty() && (ObjectType
.isNull() || Found
.empty())) {
458 // C++ [basic.lookup.classref]p1:
459 // In a class member access expression (5.2.5), if the . or -> token is
460 // immediately followed by an identifier followed by a <, the
461 // identifier must be looked up to determine whether the < is the
462 // beginning of a template argument list (14.2) or a less-than operator.
463 // The identifier is first looked up in the class of the object
464 // expression. If the identifier is not found, it is then looked up in
465 // the context of the entire postfix-expression and shall name a class
468 LookupName(Found
, S
);
470 if (!ObjectType
.isNull()) {
471 // FIXME: We should filter out all non-type templates here, particularly
472 // variable templates and concepts. But the exclusion of alias templates
473 // and template template parameters is a wording defect.
474 AllowFunctionTemplatesInLookup
= false;
475 ObjectTypeSearchedInScope
= true;
478 IsDependent
|= Found
.wasNotFoundInCurrentInstantiation();
481 if (Found
.isAmbiguous())
484 if (ATK
&& SS
.isEmpty() && ObjectType
.isNull() &&
485 !RequiredTemplate
.hasTemplateKeyword()) {
486 // C++2a [temp.names]p2:
487 // A name is also considered to refer to a template if it is an
488 // unqualified-id followed by a < and name lookup finds either one or more
489 // functions or finds nothing.
491 // To keep our behavior consistent, we apply the "finds nothing" part in
492 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
493 // successfully form a call to an undeclared template-id.
495 getLangOpts().CPlusPlus20
&& llvm::all_of(Found
, [](NamedDecl
*ND
) {
496 return isa
<FunctionDecl
>(ND
->getUnderlyingDecl());
498 if (AllFunctions
|| (Found
.empty() && !IsDependent
)) {
499 // If lookup found any functions, or if this is a name that can only be
500 // used for a function, then strongly assume this is a function
502 *ATK
= (Found
.empty() && Found
.getLookupName().isIdentifier())
503 ? AssumedTemplateKind::FoundNothing
504 : AssumedTemplateKind::FoundFunctions
;
510 if (Found
.empty() && !IsDependent
&& AllowTypoCorrection
) {
511 // If we did not find any names, and this is not a disambiguation, attempt
512 // to correct any typos.
513 DeclarationName Name
= Found
.getLookupName();
515 // Simple filter callback that, for keywords, only accepts the C++ *_cast
516 DefaultFilterCCC FilterCCC
{};
517 FilterCCC
.WantTypeSpecifiers
= false;
518 FilterCCC
.WantExpressionKeywords
= false;
519 FilterCCC
.WantRemainingKeywords
= false;
520 FilterCCC
.WantCXXNamedCasts
= true;
521 if (TypoCorrection Corrected
=
522 CorrectTypo(Found
.getLookupNameInfo(), Found
.getLookupKind(), S
,
523 &SS
, FilterCCC
, CTK_ErrorRecovery
, LookupCtx
)) {
524 if (auto *ND
= Corrected
.getFoundDecl())
526 FilterAcceptableTemplateNames(Found
);
527 if (Found
.isAmbiguous()) {
529 } else if (!Found
.empty()) {
530 Found
.setLookupName(Corrected
.getCorrection());
532 std::string
CorrectedStr(Corrected
.getAsString(getLangOpts()));
533 bool DroppedSpecifier
= Corrected
.WillReplaceSpecifier() &&
534 Name
.getAsString() == CorrectedStr
;
535 diagnoseTypo(Corrected
, PDiag(diag::err_no_member_template_suggest
)
536 << Name
<< LookupCtx
<< DroppedSpecifier
539 diagnoseTypo(Corrected
, PDiag(diag::err_no_template_suggest
) << Name
);
545 NamedDecl
*ExampleLookupResult
=
546 Found
.empty() ? nullptr : Found
.getRepresentativeDecl();
547 FilterAcceptableTemplateNames(Found
, AllowFunctionTemplatesInLookup
);
550 MemberOfUnknownSpecialization
= true;
554 // If a 'template' keyword was used, a lookup that finds only non-template
555 // names is an error.
556 if (ExampleLookupResult
&& RequiredTemplate
) {
557 Diag(Found
.getNameLoc(), diag::err_template_kw_refers_to_non_template
)
558 << Found
.getLookupName() << SS
.getRange()
559 << RequiredTemplate
.hasTemplateKeyword()
560 << RequiredTemplate
.getTemplateKeywordLoc();
561 Diag(ExampleLookupResult
->getUnderlyingDecl()->getLocation(),
562 diag::note_template_kw_refers_to_non_template
)
563 << Found
.getLookupName();
570 if (S
&& !ObjectType
.isNull() && !ObjectTypeSearchedInScope
&&
571 !getLangOpts().CPlusPlus11
) {
572 // C++03 [basic.lookup.classref]p1:
573 // [...] If the lookup in the class of the object expression finds a
574 // template, the name is also looked up in the context of the entire
575 // postfix-expression and [...]
577 // Note: C++11 does not perform this second lookup.
578 LookupResult
FoundOuter(*this, Found
.getLookupName(), Found
.getNameLoc(),
580 FoundOuter
.setTemplateNameLookup(true);
581 LookupName(FoundOuter
, S
);
582 // FIXME: We silently accept an ambiguous lookup here, in violation of
584 FilterAcceptableTemplateNames(FoundOuter
, /*AllowFunctionTemplates=*/false);
586 NamedDecl
*OuterTemplate
;
587 if (FoundOuter
.empty()) {
588 // - if the name is not found, the name found in the class of the
589 // object expression is used, otherwise
590 } else if (FoundOuter
.isAmbiguous() || !FoundOuter
.isSingleResult() ||
592 getAsTemplateNameDecl(FoundOuter
.getFoundDecl()))) {
593 // - if the name is found in the context of the entire
594 // postfix-expression and does not name a class template, the name
595 // found in the class of the object expression is used, otherwise
597 } else if (!Found
.isSuppressingAmbiguousDiagnostics()) {
598 // - if the name found is a class template, it must refer to the same
599 // entity as the one found in the class of the object expression,
600 // otherwise the program is ill-formed.
601 if (!Found
.isSingleResult() ||
602 getAsTemplateNameDecl(Found
.getFoundDecl())->getCanonicalDecl() !=
603 OuterTemplate
->getCanonicalDecl()) {
604 Diag(Found
.getNameLoc(),
605 diag::ext_nested_name_member_ref_lookup_ambiguous
)
606 << Found
.getLookupName()
608 Diag(Found
.getRepresentativeDecl()->getLocation(),
609 diag::note_ambig_member_ref_object_type
)
611 Diag(FoundOuter
.getFoundDecl()->getLocation(),
612 diag::note_ambig_member_ref_scope
);
614 // Recover by taking the template that we found in the object
615 // expression's type.
623 void Sema::diagnoseExprIntendedAsTemplateName(Scope
*S
, ExprResult TemplateName
,
625 SourceLocation Greater
) {
626 if (TemplateName
.isInvalid())
629 DeclarationNameInfo NameInfo
;
631 LookupNameKind LookupKind
;
633 DeclContext
*LookupCtx
= nullptr;
634 NamedDecl
*Found
= nullptr;
635 bool MissingTemplateKeyword
= false;
637 // Figure out what name we looked up.
638 if (auto *DRE
= dyn_cast
<DeclRefExpr
>(TemplateName
.get())) {
639 NameInfo
= DRE
->getNameInfo();
640 SS
.Adopt(DRE
->getQualifierLoc());
641 LookupKind
= LookupOrdinaryName
;
642 Found
= DRE
->getFoundDecl();
643 } else if (auto *ME
= dyn_cast
<MemberExpr
>(TemplateName
.get())) {
644 NameInfo
= ME
->getMemberNameInfo();
645 SS
.Adopt(ME
->getQualifierLoc());
646 LookupKind
= LookupMemberName
;
647 LookupCtx
= ME
->getBase()->getType()->getAsCXXRecordDecl();
648 Found
= ME
->getMemberDecl();
649 } else if (auto *DSDRE
=
650 dyn_cast
<DependentScopeDeclRefExpr
>(TemplateName
.get())) {
651 NameInfo
= DSDRE
->getNameInfo();
652 SS
.Adopt(DSDRE
->getQualifierLoc());
653 MissingTemplateKeyword
= true;
654 } else if (auto *DSME
=
655 dyn_cast
<CXXDependentScopeMemberExpr
>(TemplateName
.get())) {
656 NameInfo
= DSME
->getMemberNameInfo();
657 SS
.Adopt(DSME
->getQualifierLoc());
658 MissingTemplateKeyword
= true;
660 llvm_unreachable("unexpected kind of potential template name");
663 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
665 if (MissingTemplateKeyword
) {
666 Diag(NameInfo
.getBeginLoc(), diag::err_template_kw_missing
)
667 << "" << NameInfo
.getName().getAsString() << SourceRange(Less
, Greater
);
671 // Try to correct the name by looking for templates and C++ named casts.
672 struct TemplateCandidateFilter
: CorrectionCandidateCallback
{
674 TemplateCandidateFilter(Sema
&S
) : S(S
) {
675 WantTypeSpecifiers
= false;
676 WantExpressionKeywords
= false;
677 WantRemainingKeywords
= false;
678 WantCXXNamedCasts
= true;
680 bool ValidateCandidate(const TypoCorrection
&Candidate
) override
{
681 if (auto *ND
= Candidate
.getCorrectionDecl())
682 return S
.getAsTemplateNameDecl(ND
);
683 return Candidate
.isKeyword();
686 std::unique_ptr
<CorrectionCandidateCallback
> clone() override
{
687 return std::make_unique
<TemplateCandidateFilter
>(*this);
691 DeclarationName Name
= NameInfo
.getName();
692 TemplateCandidateFilter
CCC(*this);
693 if (TypoCorrection Corrected
= CorrectTypo(NameInfo
, LookupKind
, S
, &SS
, CCC
,
694 CTK_ErrorRecovery
, LookupCtx
)) {
695 auto *ND
= Corrected
.getFoundDecl();
697 ND
= getAsTemplateNameDecl(ND
);
698 if (ND
|| Corrected
.isKeyword()) {
700 std::string
CorrectedStr(Corrected
.getAsString(getLangOpts()));
701 bool DroppedSpecifier
= Corrected
.WillReplaceSpecifier() &&
702 Name
.getAsString() == CorrectedStr
;
703 diagnoseTypo(Corrected
,
704 PDiag(diag::err_non_template_in_member_template_id_suggest
)
705 << Name
<< LookupCtx
<< DroppedSpecifier
706 << SS
.getRange(), false);
708 diagnoseTypo(Corrected
,
709 PDiag(diag::err_non_template_in_template_id_suggest
)
713 Diag(Found
->getLocation(),
714 diag::note_non_template_in_template_id_found
);
719 Diag(NameInfo
.getLoc(), diag::err_non_template_in_template_id
)
720 << Name
<< SourceRange(Less
, Greater
);
722 Diag(Found
->getLocation(), diag::note_non_template_in_template_id_found
);
725 /// ActOnDependentIdExpression - Handle a dependent id-expression that
726 /// was just parsed. This is only possible with an explicit scope
727 /// specifier naming a dependent type.
729 Sema::ActOnDependentIdExpression(const CXXScopeSpec
&SS
,
730 SourceLocation TemplateKWLoc
,
731 const DeclarationNameInfo
&NameInfo
,
732 bool isAddressOfOperand
,
733 const TemplateArgumentListInfo
*TemplateArgs
) {
734 DeclContext
*DC
= getFunctionLevelDeclContext();
736 // C++11 [expr.prim.general]p12:
737 // An id-expression that denotes a non-static data member or non-static
738 // member function of a class can only be used:
740 // - if that id-expression denotes a non-static data member and it
741 // appears in an unevaluated operand.
743 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
744 // CXXDependentScopeMemberExpr. The former can instantiate to either
745 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
746 // always a MemberExpr.
747 bool MightBeCxx11UnevalField
=
748 getLangOpts().CPlusPlus11
&& isUnevaluatedContext();
750 // Check if the nested name specifier is an enum type.
752 if (NestedNameSpecifier
*NNS
= SS
.getScopeRep())
753 IsEnum
= isa_and_nonnull
<EnumType
>(NNS
->getAsType());
755 if (!MightBeCxx11UnevalField
&& !isAddressOfOperand
&& !IsEnum
&&
756 isa
<CXXMethodDecl
>(DC
) &&
757 cast
<CXXMethodDecl
>(DC
)->isImplicitObjectMemberFunction()) {
758 QualType ThisType
= cast
<CXXMethodDecl
>(DC
)->getThisType().getNonReferenceType();
760 // Since the 'this' expression is synthesized, we don't need to
761 // perform the double-lookup check.
762 NamedDecl
*FirstQualifierInScope
= nullptr;
764 return CXXDependentScopeMemberExpr::Create(
765 Context
, /*This=*/nullptr, ThisType
,
766 /*IsArrow=*/!Context
.getLangOpts().HLSL
,
767 /*Op=*/SourceLocation(), SS
.getWithLocInContext(Context
), TemplateKWLoc
,
768 FirstQualifierInScope
, NameInfo
, TemplateArgs
);
771 return BuildDependentDeclRefExpr(SS
, TemplateKWLoc
, NameInfo
, TemplateArgs
);
775 Sema::BuildDependentDeclRefExpr(const CXXScopeSpec
&SS
,
776 SourceLocation TemplateKWLoc
,
777 const DeclarationNameInfo
&NameInfo
,
778 const TemplateArgumentListInfo
*TemplateArgs
) {
779 // DependentScopeDeclRefExpr::Create requires a valid QualifierLoc
780 NestedNameSpecifierLoc QualifierLoc
= SS
.getWithLocInContext(Context
);
784 return DependentScopeDeclRefExpr::Create(
785 Context
, QualifierLoc
, TemplateKWLoc
, NameInfo
, TemplateArgs
);
789 /// Determine whether we would be unable to instantiate this template (because
790 /// it either has no definition, or is in the process of being instantiated).
791 bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation
,
792 NamedDecl
*Instantiation
,
793 bool InstantiatedFromMember
,
794 const NamedDecl
*Pattern
,
795 const NamedDecl
*PatternDef
,
796 TemplateSpecializationKind TSK
,
797 bool Complain
/*= true*/) {
798 assert(isa
<TagDecl
>(Instantiation
) || isa
<FunctionDecl
>(Instantiation
) ||
799 isa
<VarDecl
>(Instantiation
));
801 bool IsEntityBeingDefined
= false;
802 if (const TagDecl
*TD
= dyn_cast_or_null
<TagDecl
>(PatternDef
))
803 IsEntityBeingDefined
= TD
->isBeingDefined();
805 if (PatternDef
&& !IsEntityBeingDefined
) {
806 NamedDecl
*SuggestedDef
= nullptr;
807 if (!hasReachableDefinition(const_cast<NamedDecl
*>(PatternDef
),
809 /*OnlyNeedComplete*/ false)) {
810 // If we're allowed to diagnose this and recover, do so.
811 bool Recover
= Complain
&& !isSFINAEContext();
813 diagnoseMissingImport(PointOfInstantiation
, SuggestedDef
,
814 Sema::MissingImportKind::Definition
, Recover
);
820 if (!Complain
|| (PatternDef
&& PatternDef
->isInvalidDecl()))
823 std::optional
<unsigned> Note
;
824 QualType InstantiationTy
;
825 if (TagDecl
*TD
= dyn_cast
<TagDecl
>(Instantiation
))
826 InstantiationTy
= Context
.getTypeDeclType(TD
);
828 Diag(PointOfInstantiation
,
829 diag::err_template_instantiate_within_definition
)
830 << /*implicit|explicit*/(TSK
!= TSK_ImplicitInstantiation
)
832 // Not much point in noting the template declaration here, since
833 // we're lexically inside it.
834 Instantiation
->setInvalidDecl();
835 } else if (InstantiatedFromMember
) {
836 if (isa
<FunctionDecl
>(Instantiation
)) {
837 Diag(PointOfInstantiation
,
838 diag::err_explicit_instantiation_undefined_member
)
839 << /*member function*/ 1 << Instantiation
->getDeclName()
840 << Instantiation
->getDeclContext();
841 Note
= diag::note_explicit_instantiation_here
;
843 assert(isa
<TagDecl
>(Instantiation
) && "Must be a TagDecl!");
844 Diag(PointOfInstantiation
,
845 diag::err_implicit_instantiate_member_undefined
)
847 Note
= diag::note_member_declared_at
;
850 if (isa
<FunctionDecl
>(Instantiation
)) {
851 Diag(PointOfInstantiation
,
852 diag::err_explicit_instantiation_undefined_func_template
)
854 Note
= diag::note_explicit_instantiation_here
;
855 } else if (isa
<TagDecl
>(Instantiation
)) {
856 Diag(PointOfInstantiation
, diag::err_template_instantiate_undefined
)
857 << (TSK
!= TSK_ImplicitInstantiation
)
859 Note
= diag::note_template_decl_here
;
861 assert(isa
<VarDecl
>(Instantiation
) && "Must be a VarDecl!");
862 if (isa
<VarTemplateSpecializationDecl
>(Instantiation
)) {
863 Diag(PointOfInstantiation
,
864 diag::err_explicit_instantiation_undefined_var_template
)
866 Instantiation
->setInvalidDecl();
868 Diag(PointOfInstantiation
,
869 diag::err_explicit_instantiation_undefined_member
)
870 << /*static data member*/ 2 << Instantiation
->getDeclName()
871 << Instantiation
->getDeclContext();
872 Note
= diag::note_explicit_instantiation_here
;
875 if (Note
) // Diagnostics were emitted.
876 Diag(Pattern
->getLocation(), *Note
);
878 // In general, Instantiation isn't marked invalid to get more than one
879 // error for multiple undefined instantiations. But the code that does
880 // explicit declaration -> explicit definition conversion can't handle
881 // invalid declarations, so mark as invalid in that case.
882 if (TSK
== TSK_ExplicitInstantiationDeclaration
)
883 Instantiation
->setInvalidDecl();
887 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
888 /// that the template parameter 'PrevDecl' is being shadowed by a new
889 /// declaration at location Loc. Returns true to indicate that this is
890 /// an error, and false otherwise.
891 void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc
, Decl
*PrevDecl
) {
892 assert(PrevDecl
->isTemplateParameter() && "Not a template parameter");
894 // C++ [temp.local]p4:
895 // A template-parameter shall not be redeclared within its
896 // scope (including nested scopes).
898 // Make this a warning when MSVC compatibility is requested.
899 unsigned DiagId
= getLangOpts().MSVCCompat
? diag::ext_template_param_shadow
900 : diag::err_template_param_shadow
;
901 Diag(Loc
, DiagId
) << cast
<NamedDecl
>(PrevDecl
)->getDeclName();
902 Diag(PrevDecl
->getLocation(), diag::note_template_param_here
);
905 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
906 /// the parameter D to reference the templated declaration and return a pointer
907 /// to the template declaration. Otherwise, do nothing to D and return null.
908 TemplateDecl
*Sema::AdjustDeclIfTemplate(Decl
*&D
) {
909 if (TemplateDecl
*Temp
= dyn_cast_or_null
<TemplateDecl
>(D
)) {
910 D
= Temp
->getTemplatedDecl();
916 ParsedTemplateArgument
ParsedTemplateArgument::getTemplatePackExpansion(
917 SourceLocation EllipsisLoc
) const {
918 assert(Kind
== Template
&&
919 "Only template template arguments can be pack expansions here");
920 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
921 "Template template argument pack expansion without packs");
922 ParsedTemplateArgument
Result(*this);
923 Result
.EllipsisLoc
= EllipsisLoc
;
927 static TemplateArgumentLoc
translateTemplateArgument(Sema
&SemaRef
,
928 const ParsedTemplateArgument
&Arg
) {
930 switch (Arg
.getKind()) {
931 case ParsedTemplateArgument::Type
: {
933 QualType T
= SemaRef
.GetTypeFromParser(Arg
.getAsType(), &DI
);
935 DI
= SemaRef
.Context
.getTrivialTypeSourceInfo(T
, Arg
.getLocation());
936 return TemplateArgumentLoc(TemplateArgument(T
), DI
);
939 case ParsedTemplateArgument::NonType
: {
940 Expr
*E
= static_cast<Expr
*>(Arg
.getAsExpr());
941 return TemplateArgumentLoc(TemplateArgument(E
), E
);
944 case ParsedTemplateArgument::Template
: {
945 TemplateName Template
= Arg
.getAsTemplate().get();
946 TemplateArgument TArg
;
947 if (Arg
.getEllipsisLoc().isValid())
948 TArg
= TemplateArgument(Template
, std::optional
<unsigned int>());
951 return TemplateArgumentLoc(
952 SemaRef
.Context
, TArg
,
953 Arg
.getScopeSpec().getWithLocInContext(SemaRef
.Context
),
954 Arg
.getLocation(), Arg
.getEllipsisLoc());
958 llvm_unreachable("Unhandled parsed template argument");
961 /// Translates template arguments as provided by the parser
962 /// into template arguments used by semantic analysis.
963 void Sema::translateTemplateArguments(const ASTTemplateArgsPtr
&TemplateArgsIn
,
964 TemplateArgumentListInfo
&TemplateArgs
) {
965 for (unsigned I
= 0, Last
= TemplateArgsIn
.size(); I
!= Last
; ++I
)
966 TemplateArgs
.addArgument(translateTemplateArgument(*this,
970 static void maybeDiagnoseTemplateParameterShadow(Sema
&SemaRef
, Scope
*S
,
972 IdentifierInfo
*Name
) {
973 NamedDecl
*PrevDecl
= SemaRef
.LookupSingleName(
974 S
, Name
, Loc
, Sema::LookupOrdinaryName
, Sema::ForVisibleRedeclaration
);
975 if (PrevDecl
&& PrevDecl
->isTemplateParameter())
976 SemaRef
.DiagnoseTemplateParameterShadow(Loc
, PrevDecl
);
979 /// Convert a parsed type into a parsed template argument. This is mostly
980 /// trivial, except that we may have parsed a C++17 deduced class template
981 /// specialization type, in which case we should form a template template
982 /// argument instead of a type template argument.
983 ParsedTemplateArgument
Sema::ActOnTemplateTypeArgument(TypeResult ParsedType
) {
984 TypeSourceInfo
*TInfo
;
985 QualType T
= GetTypeFromParser(ParsedType
.get(), &TInfo
);
987 return ParsedTemplateArgument();
988 assert(TInfo
&& "template argument with no location");
990 // If we might have formed a deduced template specialization type, convert
991 // it to a template template argument.
992 if (getLangOpts().CPlusPlus17
) {
993 TypeLoc TL
= TInfo
->getTypeLoc();
994 SourceLocation EllipsisLoc
;
995 if (auto PET
= TL
.getAs
<PackExpansionTypeLoc
>()) {
996 EllipsisLoc
= PET
.getEllipsisLoc();
997 TL
= PET
.getPatternLoc();
1001 if (auto ET
= TL
.getAs
<ElaboratedTypeLoc
>()) {
1002 SS
.Adopt(ET
.getQualifierLoc());
1003 TL
= ET
.getNamedTypeLoc();
1006 if (auto DTST
= TL
.getAs
<DeducedTemplateSpecializationTypeLoc
>()) {
1007 TemplateName Name
= DTST
.getTypePtr()->getTemplateName();
1009 Name
= Context
.getQualifiedTemplateName(SS
.getScopeRep(),
1010 /*HasTemplateKeyword=*/false,
1012 ParsedTemplateArgument
Result(SS
, TemplateTy::make(Name
),
1013 DTST
.getTemplateNameLoc());
1014 if (EllipsisLoc
.isValid())
1015 Result
= Result
.getTemplatePackExpansion(EllipsisLoc
);
1020 // This is a normal type template argument. Note, if the type template
1021 // argument is an injected-class-name for a template, it has a dual nature
1022 // and can be used as either a type or a template. We handle that in
1023 // convertTypeTemplateArgumentToTemplate.
1024 return ParsedTemplateArgument(ParsedTemplateArgument::Type
,
1025 ParsedType
.get().getAsOpaquePtr(),
1026 TInfo
->getTypeLoc().getBeginLoc());
1029 /// ActOnTypeParameter - Called when a C++ template type parameter
1030 /// (e.g., "typename T") has been parsed. Typename specifies whether
1031 /// the keyword "typename" was used to declare the type parameter
1032 /// (otherwise, "class" was used), and KeyLoc is the location of the
1033 /// "class" or "typename" keyword. ParamName is the name of the
1034 /// parameter (NULL indicates an unnamed template parameter) and
1035 /// ParamNameLoc is the location of the parameter name (if any).
1036 /// If the type parameter has a default argument, it will be added
1037 /// later via ActOnTypeParameterDefault.
1038 NamedDecl
*Sema::ActOnTypeParameter(Scope
*S
, bool Typename
,
1039 SourceLocation EllipsisLoc
,
1040 SourceLocation KeyLoc
,
1041 IdentifierInfo
*ParamName
,
1042 SourceLocation ParamNameLoc
,
1043 unsigned Depth
, unsigned Position
,
1044 SourceLocation EqualLoc
,
1045 ParsedType DefaultArg
,
1046 bool HasTypeConstraint
) {
1047 assert(S
->isTemplateParamScope() &&
1048 "Template type parameter not in template parameter scope!");
1050 bool IsParameterPack
= EllipsisLoc
.isValid();
1051 TemplateTypeParmDecl
*Param
1052 = TemplateTypeParmDecl::Create(Context
, Context
.getTranslationUnitDecl(),
1053 KeyLoc
, ParamNameLoc
, Depth
, Position
,
1054 ParamName
, Typename
, IsParameterPack
,
1056 Param
->setAccess(AS_public
);
1058 if (Param
->isParameterPack())
1059 if (auto *LSI
= getEnclosingLambda())
1060 LSI
->LocalPacks
.push_back(Param
);
1063 maybeDiagnoseTemplateParameterShadow(*this, S
, ParamNameLoc
, ParamName
);
1065 // Add the template parameter into the current scope.
1067 IdResolver
.AddDecl(Param
);
1070 // C++0x [temp.param]p9:
1071 // A default template-argument may be specified for any kind of
1072 // template-parameter that is not a template parameter pack.
1073 if (DefaultArg
&& IsParameterPack
) {
1074 Diag(EqualLoc
, diag::err_template_param_pack_default_arg
);
1075 DefaultArg
= nullptr;
1078 // Handle the default argument, if provided.
1080 TypeSourceInfo
*DefaultTInfo
;
1081 GetTypeFromParser(DefaultArg
, &DefaultTInfo
);
1083 assert(DefaultTInfo
&& "expected source information for type");
1085 // Check for unexpanded parameter packs.
1086 if (DiagnoseUnexpandedParameterPack(ParamNameLoc
, DefaultTInfo
,
1087 UPPC_DefaultArgument
))
1090 // Check the template argument itself.
1091 if (CheckTemplateArgument(DefaultTInfo
)) {
1092 Param
->setInvalidDecl();
1096 Param
->setDefaultArgument(DefaultTInfo
);
1102 /// Convert the parser's template argument list representation into our form.
1103 static TemplateArgumentListInfo
1104 makeTemplateArgumentListInfo(Sema
&S
, TemplateIdAnnotation
&TemplateId
) {
1105 TemplateArgumentListInfo
TemplateArgs(TemplateId
.LAngleLoc
,
1106 TemplateId
.RAngleLoc
);
1107 ASTTemplateArgsPtr
TemplateArgsPtr(TemplateId
.getTemplateArgs(),
1108 TemplateId
.NumArgs
);
1109 S
.translateTemplateArguments(TemplateArgsPtr
, TemplateArgs
);
1110 return TemplateArgs
;
1113 bool Sema::CheckTypeConstraint(TemplateIdAnnotation
*TypeConstr
) {
1115 TemplateName TN
= TypeConstr
->Template
.get();
1116 ConceptDecl
*CD
= cast
<ConceptDecl
>(TN
.getAsTemplateDecl());
1118 // C++2a [temp.param]p4:
1119 // [...] The concept designated by a type-constraint shall be a type
1120 // concept ([temp.concept]).
1121 if (!CD
->isTypeConcept()) {
1122 Diag(TypeConstr
->TemplateNameLoc
,
1123 diag::err_type_constraint_non_type_concept
);
1127 bool WereArgsSpecified
= TypeConstr
->LAngleLoc
.isValid();
1129 if (!WereArgsSpecified
&&
1130 CD
->getTemplateParameters()->getMinRequiredArguments() > 1) {
1131 Diag(TypeConstr
->TemplateNameLoc
,
1132 diag::err_type_constraint_missing_arguments
)
1139 bool Sema::ActOnTypeConstraint(const CXXScopeSpec
&SS
,
1140 TemplateIdAnnotation
*TypeConstr
,
1141 TemplateTypeParmDecl
*ConstrainedParameter
,
1142 SourceLocation EllipsisLoc
) {
1143 return BuildTypeConstraint(SS
, TypeConstr
, ConstrainedParameter
, EllipsisLoc
,
1147 bool Sema::BuildTypeConstraint(const CXXScopeSpec
&SS
,
1148 TemplateIdAnnotation
*TypeConstr
,
1149 TemplateTypeParmDecl
*ConstrainedParameter
,
1150 SourceLocation EllipsisLoc
,
1151 bool AllowUnexpandedPack
) {
1153 if (CheckTypeConstraint(TypeConstr
))
1156 TemplateName TN
= TypeConstr
->Template
.get();
1157 ConceptDecl
*CD
= cast
<ConceptDecl
>(TN
.getAsTemplateDecl());
1159 DeclarationNameInfo
ConceptName(DeclarationName(TypeConstr
->Name
),
1160 TypeConstr
->TemplateNameLoc
);
1162 TemplateArgumentListInfo TemplateArgs
;
1163 if (TypeConstr
->LAngleLoc
.isValid()) {
1165 makeTemplateArgumentListInfo(*this, *TypeConstr
);
1167 if (EllipsisLoc
.isInvalid() && !AllowUnexpandedPack
) {
1168 for (TemplateArgumentLoc Arg
: TemplateArgs
.arguments()) {
1169 if (DiagnoseUnexpandedParameterPack(Arg
, UPPC_TypeConstraint
))
1174 return AttachTypeConstraint(
1175 SS
.isSet() ? SS
.getWithLocInContext(Context
) : NestedNameSpecifierLoc(),
1177 TypeConstr
->LAngleLoc
.isValid() ? &TemplateArgs
: nullptr,
1178 ConstrainedParameter
, EllipsisLoc
);
1181 template<typename ArgumentLocAppender
>
1182 static ExprResult
formImmediatelyDeclaredConstraint(
1183 Sema
&S
, NestedNameSpecifierLoc NS
, DeclarationNameInfo NameInfo
,
1184 ConceptDecl
*NamedConcept
, SourceLocation LAngleLoc
,
1185 SourceLocation RAngleLoc
, QualType ConstrainedType
,
1186 SourceLocation ParamNameLoc
, ArgumentLocAppender Appender
,
1187 SourceLocation EllipsisLoc
) {
1189 TemplateArgumentListInfo ConstraintArgs
;
1190 ConstraintArgs
.addArgument(
1191 S
.getTrivialTemplateArgumentLoc(TemplateArgument(ConstrainedType
),
1192 /*NTTPType=*/QualType(), ParamNameLoc
));
1194 ConstraintArgs
.setRAngleLoc(RAngleLoc
);
1195 ConstraintArgs
.setLAngleLoc(LAngleLoc
);
1196 Appender(ConstraintArgs
);
1198 // C++2a [temp.param]p4:
1199 // [...] This constraint-expression E is called the immediately-declared
1200 // constraint of T. [...]
1203 ExprResult ImmediatelyDeclaredConstraint
= S
.CheckConceptTemplateId(
1204 SS
, /*TemplateKWLoc=*/SourceLocation(), NameInfo
,
1205 /*FoundDecl=*/NamedConcept
, NamedConcept
, &ConstraintArgs
);
1206 if (ImmediatelyDeclaredConstraint
.isInvalid() || !EllipsisLoc
.isValid())
1207 return ImmediatelyDeclaredConstraint
;
1209 // C++2a [temp.param]p4:
1210 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1212 // We have the following case:
1214 // template<typename T> concept C1 = true;
1215 // template<C1... T> struct s1;
1217 // The constraint: (C1<T> && ...)
1219 // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1220 // any unqualified lookups for 'operator&&' here.
1221 return S
.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
1222 /*LParenLoc=*/SourceLocation(),
1223 ImmediatelyDeclaredConstraint
.get(), BO_LAnd
,
1224 EllipsisLoc
, /*RHS=*/nullptr,
1225 /*RParenLoc=*/SourceLocation(),
1226 /*NumExpansions=*/std::nullopt
);
1229 /// Attach a type-constraint to a template parameter.
1230 /// \returns true if an error occurred. This can happen if the
1231 /// immediately-declared constraint could not be formed (e.g. incorrect number
1232 /// of arguments for the named concept).
1233 bool Sema::AttachTypeConstraint(NestedNameSpecifierLoc NS
,
1234 DeclarationNameInfo NameInfo
,
1235 ConceptDecl
*NamedConcept
,
1236 const TemplateArgumentListInfo
*TemplateArgs
,
1237 TemplateTypeParmDecl
*ConstrainedParameter
,
1238 SourceLocation EllipsisLoc
) {
1239 // C++2a [temp.param]p4:
1240 // [...] If Q is of the form C<A1, ..., An>, then let E' be
1241 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1242 const ASTTemplateArgumentListInfo
*ArgsAsWritten
=
1243 TemplateArgs
? ASTTemplateArgumentListInfo::Create(Context
,
1244 *TemplateArgs
) : nullptr;
1246 QualType
ParamAsArgument(ConstrainedParameter
->getTypeForDecl(), 0);
1248 ExprResult ImmediatelyDeclaredConstraint
=
1249 formImmediatelyDeclaredConstraint(
1250 *this, NS
, NameInfo
, NamedConcept
,
1251 TemplateArgs
? TemplateArgs
->getLAngleLoc() : SourceLocation(),
1252 TemplateArgs
? TemplateArgs
->getRAngleLoc() : SourceLocation(),
1253 ParamAsArgument
, ConstrainedParameter
->getLocation(),
1254 [&] (TemplateArgumentListInfo
&ConstraintArgs
) {
1256 for (const auto &ArgLoc
: TemplateArgs
->arguments())
1257 ConstraintArgs
.addArgument(ArgLoc
);
1259 if (ImmediatelyDeclaredConstraint
.isInvalid())
1262 auto *CL
= ConceptReference::Create(Context
, /*NNS=*/NS
,
1263 /*TemplateKWLoc=*/SourceLocation
{},
1264 /*ConceptNameInfo=*/NameInfo
,
1265 /*FoundDecl=*/NamedConcept
,
1266 /*NamedConcept=*/NamedConcept
,
1267 /*ArgsWritten=*/ArgsAsWritten
);
1268 ConstrainedParameter
->setTypeConstraint(CL
,
1269 ImmediatelyDeclaredConstraint
.get());
1273 bool Sema::AttachTypeConstraint(AutoTypeLoc TL
,
1274 NonTypeTemplateParmDecl
*NewConstrainedParm
,
1275 NonTypeTemplateParmDecl
*OrigConstrainedParm
,
1276 SourceLocation EllipsisLoc
) {
1277 if (NewConstrainedParm
->getType() != TL
.getType() ||
1278 TL
.getAutoKeyword() != AutoTypeKeyword::Auto
) {
1279 Diag(NewConstrainedParm
->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1280 diag::err_unsupported_placeholder_constraint
)
1281 << NewConstrainedParm
->getTypeSourceInfo()
1286 // FIXME: Concepts: This should be the type of the placeholder, but this is
1287 // unclear in the wording right now.
1289 BuildDeclRefExpr(OrigConstrainedParm
, OrigConstrainedParm
->getType(),
1290 VK_PRValue
, OrigConstrainedParm
->getLocation());
1293 ExprResult ImmediatelyDeclaredConstraint
= formImmediatelyDeclaredConstraint(
1294 *this, TL
.getNestedNameSpecifierLoc(), TL
.getConceptNameInfo(),
1295 TL
.getNamedConcept(), TL
.getLAngleLoc(), TL
.getRAngleLoc(),
1296 BuildDecltypeType(Ref
), OrigConstrainedParm
->getLocation(),
1297 [&](TemplateArgumentListInfo
&ConstraintArgs
) {
1298 for (unsigned I
= 0, C
= TL
.getNumArgs(); I
!= C
; ++I
)
1299 ConstraintArgs
.addArgument(TL
.getArgLoc(I
));
1302 if (ImmediatelyDeclaredConstraint
.isInvalid() ||
1303 !ImmediatelyDeclaredConstraint
.isUsable())
1306 NewConstrainedParm
->setPlaceholderTypeConstraint(
1307 ImmediatelyDeclaredConstraint
.get());
1311 /// Check that the type of a non-type template parameter is
1314 /// \returns the (possibly-promoted) parameter type if valid;
1315 /// otherwise, produces a diagnostic and returns a NULL type.
1316 QualType
Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo
*&TSI
,
1317 SourceLocation Loc
) {
1318 if (TSI
->getType()->isUndeducedType()) {
1319 // C++17 [temp.dep.expr]p3:
1320 // An id-expression is type-dependent if it contains
1321 // - an identifier associated by name lookup with a non-type
1322 // template-parameter declared with a type that contains a
1323 // placeholder type (7.1.7.4),
1324 TSI
= SubstAutoTypeSourceInfoDependent(TSI
);
1327 return CheckNonTypeTemplateParameterType(TSI
->getType(), Loc
);
1330 /// Require the given type to be a structural type, and diagnose if it is not.
1332 /// \return \c true if an error was produced.
1333 bool Sema::RequireStructuralType(QualType T
, SourceLocation Loc
) {
1334 if (T
->isDependentType())
1337 if (RequireCompleteType(Loc
, T
, diag::err_template_nontype_parm_incomplete
))
1340 if (T
->isStructuralType())
1343 // Structural types are required to be object types or lvalue references.
1344 if (T
->isRValueReferenceType()) {
1345 Diag(Loc
, diag::err_template_nontype_parm_rvalue_ref
) << T
;
1349 // Don't mention structural types in our diagnostic prior to C++20. Also,
1350 // there's not much more we can say about non-scalar non-class types --
1351 // because we can't see functions or arrays here, those can only be language
1353 if (!getLangOpts().CPlusPlus20
||
1354 (!T
->isScalarType() && !T
->isRecordType())) {
1355 Diag(Loc
, diag::err_template_nontype_parm_bad_type
) << T
;
1359 // Structural types are required to be literal types.
1360 if (RequireLiteralType(Loc
, T
, diag::err_template_nontype_parm_not_literal
))
1363 Diag(Loc
, diag::err_template_nontype_parm_not_structural
) << T
;
1365 // Drill down into the reason why the class is non-structural.
1366 while (const CXXRecordDecl
*RD
= T
->getAsCXXRecordDecl()) {
1367 // All members are required to be public and non-mutable, and can't be of
1368 // rvalue reference type. Check these conditions first to prefer a "local"
1369 // reason over a more distant one.
1370 for (const FieldDecl
*FD
: RD
->fields()) {
1371 if (FD
->getAccess() != AS_public
) {
1372 Diag(FD
->getLocation(), diag::note_not_structural_non_public
) << T
<< 0;
1375 if (FD
->isMutable()) {
1376 Diag(FD
->getLocation(), diag::note_not_structural_mutable_field
) << T
;
1379 if (FD
->getType()->isRValueReferenceType()) {
1380 Diag(FD
->getLocation(), diag::note_not_structural_rvalue_ref_field
)
1386 // All bases are required to be public.
1387 for (const auto &BaseSpec
: RD
->bases()) {
1388 if (BaseSpec
.getAccessSpecifier() != AS_public
) {
1389 Diag(BaseSpec
.getBaseTypeLoc(), diag::note_not_structural_non_public
)
1395 // All subobjects are required to be of structural types.
1396 SourceLocation SubLoc
;
1400 for (const FieldDecl
*FD
: RD
->fields()) {
1401 QualType T
= Context
.getBaseElementType(FD
->getType());
1402 if (!T
->isStructuralType()) {
1403 SubLoc
= FD
->getLocation();
1411 for (const auto &BaseSpec
: RD
->bases()) {
1412 QualType T
= BaseSpec
.getType();
1413 if (!T
->isStructuralType()) {
1414 SubLoc
= BaseSpec
.getBaseTypeLoc();
1422 assert(Kind
!= -1 && "couldn't find reason why type is not structural");
1423 Diag(SubLoc
, diag::note_not_structural_subobject
)
1424 << T
<< Kind
<< SubType
;
1426 RD
= T
->getAsCXXRecordDecl();
1432 QualType
Sema::CheckNonTypeTemplateParameterType(QualType T
,
1433 SourceLocation Loc
) {
1434 // We don't allow variably-modified types as the type of non-type template
1436 if (T
->isVariablyModifiedType()) {
1437 Diag(Loc
, diag::err_variably_modified_nontype_template_param
)
1442 // C++ [temp.param]p4:
1444 // A non-type template-parameter shall have one of the following
1445 // (optionally cv-qualified) types:
1447 // -- integral or enumeration type,
1448 if (T
->isIntegralOrEnumerationType() ||
1449 // -- pointer to object or pointer to function,
1450 T
->isPointerType() ||
1451 // -- lvalue reference to object or lvalue reference to function,
1452 T
->isLValueReferenceType() ||
1453 // -- pointer to member,
1454 T
->isMemberPointerType() ||
1455 // -- std::nullptr_t, or
1456 T
->isNullPtrType() ||
1457 // -- a type that contains a placeholder type.
1458 T
->isUndeducedType()) {
1459 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1460 // are ignored when determining its type.
1461 return T
.getUnqualifiedType();
1464 // C++ [temp.param]p8:
1466 // A non-type template-parameter of type "array of T" or
1467 // "function returning T" is adjusted to be of type "pointer to
1468 // T" or "pointer to function returning T", respectively.
1469 if (T
->isArrayType() || T
->isFunctionType())
1470 return Context
.getDecayedType(T
);
1472 // If T is a dependent type, we can't do the check now, so we
1473 // assume that it is well-formed. Note that stripping off the
1474 // qualifiers here is not really correct if T turns out to be
1475 // an array type, but we'll recompute the type everywhere it's
1476 // used during instantiation, so that should be OK. (Using the
1477 // qualified type is equally wrong.)
1478 if (T
->isDependentType())
1479 return T
.getUnqualifiedType();
1481 // C++20 [temp.param]p6:
1482 // -- a structural type
1483 if (RequireStructuralType(T
, Loc
))
1486 if (!getLangOpts().CPlusPlus20
) {
1487 // FIXME: Consider allowing structural types as an extension in C++17. (In
1488 // earlier language modes, the template argument evaluation rules are too
1490 Diag(Loc
, diag::err_template_nontype_parm_bad_structural_type
) << T
;
1494 Diag(Loc
, diag::warn_cxx17_compat_template_nontype_parm_type
) << T
;
1495 return T
.getUnqualifiedType();
1498 NamedDecl
*Sema::ActOnNonTypeTemplateParameter(Scope
*S
, Declarator
&D
,
1501 SourceLocation EqualLoc
,
1503 TypeSourceInfo
*TInfo
= GetTypeForDeclarator(D
, S
);
1505 // Check that we have valid decl-specifiers specified.
1506 auto CheckValidDeclSpecifiers
= [this, &D
] {
1509 // template-parameter:
1511 // parameter-declaration
1513 // ... A storage class shall not be specified in a template-parameter
1516 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1517 // of a parameter-declaration
1518 const DeclSpec
&DS
= D
.getDeclSpec();
1519 auto EmitDiag
= [this](SourceLocation Loc
) {
1520 Diag(Loc
, diag::err_invalid_decl_specifier_in_nontype_parm
)
1521 << FixItHint::CreateRemoval(Loc
);
1523 if (DS
.getStorageClassSpec() != DeclSpec::SCS_unspecified
)
1524 EmitDiag(DS
.getStorageClassSpecLoc());
1526 if (DS
.getThreadStorageClassSpec() != TSCS_unspecified
)
1527 EmitDiag(DS
.getThreadStorageClassSpecLoc());
1530 // The inline specifier can be applied only to the declaration or
1531 // definition of a variable or function.
1533 if (DS
.isInlineSpecified())
1534 EmitDiag(DS
.getInlineSpecLoc());
1536 // [dcl.constexpr]p1:
1537 // The constexpr specifier shall be applied only to the definition of a
1538 // variable or variable template or the declaration of a function or
1539 // function template.
1541 if (DS
.hasConstexprSpecifier())
1542 EmitDiag(DS
.getConstexprSpecLoc());
1544 // [dcl.fct.spec]p1:
1545 // Function-specifiers can be used only in function declarations.
1547 if (DS
.isVirtualSpecified())
1548 EmitDiag(DS
.getVirtualSpecLoc());
1550 if (DS
.hasExplicitSpecifier())
1551 EmitDiag(DS
.getExplicitSpecLoc());
1553 if (DS
.isNoreturnSpecified())
1554 EmitDiag(DS
.getNoreturnSpecLoc());
1557 CheckValidDeclSpecifiers();
1559 if (const auto *T
= TInfo
->getType()->getContainedDeducedType())
1560 if (isa
<AutoType
>(T
))
1561 Diag(D
.getIdentifierLoc(),
1562 diag::warn_cxx14_compat_template_nontype_parm_auto_type
)
1563 << QualType(TInfo
->getType()->getContainedAutoType(), 0);
1565 assert(S
->isTemplateParamScope() &&
1566 "Non-type template parameter not in template parameter scope!");
1567 bool Invalid
= false;
1569 QualType T
= CheckNonTypeTemplateParameterType(TInfo
, D
.getIdentifierLoc());
1571 T
= Context
.IntTy
; // Recover with an 'int' type.
1575 CheckFunctionOrTemplateParamDeclarator(S
, D
);
1577 IdentifierInfo
*ParamName
= D
.getIdentifier();
1578 bool IsParameterPack
= D
.hasEllipsis();
1579 NonTypeTemplateParmDecl
*Param
= NonTypeTemplateParmDecl::Create(
1580 Context
, Context
.getTranslationUnitDecl(), D
.getBeginLoc(),
1581 D
.getIdentifierLoc(), Depth
, Position
, ParamName
, T
, IsParameterPack
,
1583 Param
->setAccess(AS_public
);
1585 if (AutoTypeLoc TL
= TInfo
->getTypeLoc().getContainedAutoTypeLoc())
1586 if (TL
.isConstrained())
1587 if (AttachTypeConstraint(TL
, Param
, Param
, D
.getEllipsisLoc()))
1591 Param
->setInvalidDecl();
1593 if (Param
->isParameterPack())
1594 if (auto *LSI
= getEnclosingLambda())
1595 LSI
->LocalPacks
.push_back(Param
);
1598 maybeDiagnoseTemplateParameterShadow(*this, S
, D
.getIdentifierLoc(),
1601 // Add the template parameter into the current scope.
1603 IdResolver
.AddDecl(Param
);
1606 // C++0x [temp.param]p9:
1607 // A default template-argument may be specified for any kind of
1608 // template-parameter that is not a template parameter pack.
1609 if (Default
&& IsParameterPack
) {
1610 Diag(EqualLoc
, diag::err_template_param_pack_default_arg
);
1614 // Check the well-formedness of the default template argument, if provided.
1616 // Check for unexpanded parameter packs.
1617 if (DiagnoseUnexpandedParameterPack(Default
, UPPC_DefaultArgument
))
1620 Param
->setDefaultArgument(Default
);
1626 /// ActOnTemplateTemplateParameter - Called when a C++ template template
1627 /// parameter (e.g. T in template <template \<typename> class T> class array)
1628 /// has been parsed. S is the current scope.
1629 NamedDecl
*Sema::ActOnTemplateTemplateParameter(Scope
* S
,
1630 SourceLocation TmpLoc
,
1631 TemplateParameterList
*Params
,
1632 SourceLocation EllipsisLoc
,
1633 IdentifierInfo
*Name
,
1634 SourceLocation NameLoc
,
1637 SourceLocation EqualLoc
,
1638 ParsedTemplateArgument Default
) {
1639 assert(S
->isTemplateParamScope() &&
1640 "Template template parameter not in template parameter scope!");
1642 // Construct the parameter object.
1643 bool IsParameterPack
= EllipsisLoc
.isValid();
1644 TemplateTemplateParmDecl
*Param
=
1645 TemplateTemplateParmDecl::Create(Context
, Context
.getTranslationUnitDecl(),
1646 NameLoc
.isInvalid()? TmpLoc
: NameLoc
,
1647 Depth
, Position
, IsParameterPack
,
1649 Param
->setAccess(AS_public
);
1651 if (Param
->isParameterPack())
1652 if (auto *LSI
= getEnclosingLambda())
1653 LSI
->LocalPacks
.push_back(Param
);
1655 // If the template template parameter has a name, then link the identifier
1656 // into the scope and lookup mechanisms.
1658 maybeDiagnoseTemplateParameterShadow(*this, S
, NameLoc
, Name
);
1661 IdResolver
.AddDecl(Param
);
1664 if (Params
->size() == 0) {
1665 Diag(Param
->getLocation(), diag::err_template_template_parm_no_parms
)
1666 << SourceRange(Params
->getLAngleLoc(), Params
->getRAngleLoc());
1667 Param
->setInvalidDecl();
1670 // C++0x [temp.param]p9:
1671 // A default template-argument may be specified for any kind of
1672 // template-parameter that is not a template parameter pack.
1673 if (IsParameterPack
&& !Default
.isInvalid()) {
1674 Diag(EqualLoc
, diag::err_template_param_pack_default_arg
);
1675 Default
= ParsedTemplateArgument();
1678 if (!Default
.isInvalid()) {
1679 // Check only that we have a template template argument. We don't want to
1680 // try to check well-formedness now, because our template template parameter
1681 // might have dependent types in its template parameters, which we wouldn't
1682 // be able to match now.
1684 // If none of the template template parameter's template arguments mention
1685 // other template parameters, we could actually perform more checking here.
1686 // However, it isn't worth doing.
1687 TemplateArgumentLoc DefaultArg
= translateTemplateArgument(*this, Default
);
1688 if (DefaultArg
.getArgument().getAsTemplate().isNull()) {
1689 Diag(DefaultArg
.getLocation(), diag::err_template_arg_not_valid_template
)
1690 << DefaultArg
.getSourceRange();
1694 // Check for unexpanded parameter packs.
1695 if (DiagnoseUnexpandedParameterPack(DefaultArg
.getLocation(),
1696 DefaultArg
.getArgument().getAsTemplate(),
1697 UPPC_DefaultArgument
))
1700 Param
->setDefaultArgument(Context
, DefaultArg
);
1707 class ConstraintRefersToContainingTemplateChecker
1708 : public TreeTransform
<ConstraintRefersToContainingTemplateChecker
> {
1709 bool Result
= false;
1710 const FunctionDecl
*Friend
= nullptr;
1711 unsigned TemplateDepth
= 0;
1713 // Check a record-decl that we've seen to see if it is a lexical parent of the
1714 // Friend, likely because it was referred to without its template arguments.
1715 void CheckIfContainingRecord(const CXXRecordDecl
*CheckingRD
) {
1716 CheckingRD
= CheckingRD
->getMostRecentDecl();
1718 for (const DeclContext
*DC
= Friend
->getLexicalDeclContext();
1719 DC
&& !DC
->isFileContext(); DC
= DC
->getParent())
1720 if (const auto *RD
= dyn_cast
<CXXRecordDecl
>(DC
))
1721 if (CheckingRD
== RD
->getMostRecentDecl())
1725 void CheckNonTypeTemplateParmDecl(NonTypeTemplateParmDecl
*D
) {
1726 assert(D
->getDepth() <= TemplateDepth
&&
1727 "Nothing should reference a value below the actual template depth, "
1728 "depth is likely wrong");
1729 if (D
->getDepth() != TemplateDepth
)
1732 // Necessary because the type of the NTTP might be what refers to the parent
1734 TransformType(D
->getType());
1738 using inherited
= TreeTransform
<ConstraintRefersToContainingTemplateChecker
>;
1740 ConstraintRefersToContainingTemplateChecker(Sema
&SemaRef
,
1741 const FunctionDecl
*Friend
,
1742 unsigned TemplateDepth
)
1743 : inherited(SemaRef
), Friend(Friend
), TemplateDepth(TemplateDepth
) {}
1744 bool getResult() const { return Result
; }
1746 // This should be the only template parm type that we have to deal with.
1747 // SubstTempalteTypeParmPack, SubstNonTypeTemplateParmPack, and
1748 // FunctionParmPackExpr are all partially substituted, which cannot happen
1749 // with concepts at this point in translation.
1750 using inherited::TransformTemplateTypeParmType
;
1751 QualType
TransformTemplateTypeParmType(TypeLocBuilder
&TLB
,
1752 TemplateTypeParmTypeLoc TL
, bool) {
1753 assert(TL
.getDecl()->getDepth() <= TemplateDepth
&&
1754 "Nothing should reference a value below the actual template depth, "
1755 "depth is likely wrong");
1756 if (TL
.getDecl()->getDepth() != TemplateDepth
)
1758 return inherited::TransformTemplateTypeParmType(
1760 /*SuppressObjCLifetime=*/false);
1763 Decl
*TransformDecl(SourceLocation Loc
, Decl
*D
) {
1766 // FIXME : This is possibly an incomplete list, but it is unclear what other
1767 // Decl kinds could be used to refer to the template parameters. This is a
1768 // best guess so far based on examples currently available, but the
1769 // unreachable should catch future instances/cases.
1770 if (auto *TD
= dyn_cast
<TypedefNameDecl
>(D
))
1771 TransformType(TD
->getUnderlyingType());
1772 else if (auto *NTTPD
= dyn_cast
<NonTypeTemplateParmDecl
>(D
))
1773 CheckNonTypeTemplateParmDecl(NTTPD
);
1774 else if (auto *VD
= dyn_cast
<ValueDecl
>(D
))
1775 TransformType(VD
->getType());
1776 else if (auto *TD
= dyn_cast
<TemplateDecl
>(D
))
1777 TransformTemplateParameterList(TD
->getTemplateParameters());
1778 else if (auto *RD
= dyn_cast
<CXXRecordDecl
>(D
))
1779 CheckIfContainingRecord(RD
);
1780 else if (isa
<NamedDecl
>(D
)) {
1781 // No direct types to visit here I believe.
1783 llvm_unreachable("Don't know how to handle this declaration type yet");
1789 bool Sema::ConstraintExpressionDependsOnEnclosingTemplate(
1790 const FunctionDecl
*Friend
, unsigned TemplateDepth
,
1791 const Expr
*Constraint
) {
1792 assert(Friend
->getFriendObjectKind() && "Only works on a friend");
1793 ConstraintRefersToContainingTemplateChecker
Checker(*this, Friend
,
1795 Checker
.TransformExpr(const_cast<Expr
*>(Constraint
));
1796 return Checker
.getResult();
1799 /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
1800 /// constrained by RequiresClause, that contains the template parameters in
1802 TemplateParameterList
*
1803 Sema::ActOnTemplateParameterList(unsigned Depth
,
1804 SourceLocation ExportLoc
,
1805 SourceLocation TemplateLoc
,
1806 SourceLocation LAngleLoc
,
1807 ArrayRef
<NamedDecl
*> Params
,
1808 SourceLocation RAngleLoc
,
1809 Expr
*RequiresClause
) {
1810 if (ExportLoc
.isValid())
1811 Diag(ExportLoc
, diag::warn_template_export_unsupported
);
1813 for (NamedDecl
*P
: Params
)
1814 warnOnReservedIdentifier(P
);
1816 return TemplateParameterList::Create(
1817 Context
, TemplateLoc
, LAngleLoc
,
1818 llvm::ArrayRef(Params
.data(), Params
.size()), RAngleLoc
, RequiresClause
);
1821 static void SetNestedNameSpecifier(Sema
&S
, TagDecl
*T
,
1822 const CXXScopeSpec
&SS
) {
1824 T
->setQualifierInfo(SS
.getWithLocInContext(S
.Context
));
1827 DeclResult
Sema::CheckClassTemplate(
1828 Scope
*S
, unsigned TagSpec
, TagUseKind TUK
, SourceLocation KWLoc
,
1829 CXXScopeSpec
&SS
, IdentifierInfo
*Name
, SourceLocation NameLoc
,
1830 const ParsedAttributesView
&Attr
, TemplateParameterList
*TemplateParams
,
1831 AccessSpecifier AS
, SourceLocation ModulePrivateLoc
,
1832 SourceLocation FriendLoc
, unsigned NumOuterTemplateParamLists
,
1833 TemplateParameterList
**OuterTemplateParamLists
, SkipBodyInfo
*SkipBody
) {
1834 assert(TemplateParams
&& TemplateParams
->size() > 0 &&
1835 "No template parameters");
1836 assert(TUK
!= TUK_Reference
&& "Can only declare or define class templates");
1837 bool Invalid
= false;
1839 // Check that we can declare a template here.
1840 if (CheckTemplateDeclScope(S
, TemplateParams
))
1843 TagTypeKind Kind
= TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec
);
1844 assert(Kind
!= TTK_Enum
&& "can't build template of enumerated type");
1846 // There is no such thing as an unnamed class template.
1848 Diag(KWLoc
, diag::err_template_unnamed_class
);
1852 // Find any previous declaration with this name. For a friend with no
1853 // scope explicitly specified, we only look for tag declarations (per
1854 // C++11 [basic.lookup.elab]p2).
1855 DeclContext
*SemanticContext
;
1856 LookupResult
Previous(*this, Name
, NameLoc
,
1857 (SS
.isEmpty() && TUK
== TUK_Friend
)
1858 ? LookupTagName
: LookupOrdinaryName
,
1859 forRedeclarationInCurContext());
1860 if (SS
.isNotEmpty() && !SS
.isInvalid()) {
1861 SemanticContext
= computeDeclContext(SS
, true);
1862 if (!SemanticContext
) {
1863 // FIXME: Horrible, horrible hack! We can't currently represent this
1864 // in the AST, and historically we have just ignored such friend
1865 // class templates, so don't complain here.
1866 Diag(NameLoc
, TUK
== TUK_Friend
1867 ? diag::warn_template_qualified_friend_ignored
1868 : diag::err_template_qualified_declarator_no_match
)
1869 << SS
.getScopeRep() << SS
.getRange();
1870 return TUK
!= TUK_Friend
;
1873 if (RequireCompleteDeclContext(SS
, SemanticContext
))
1876 // If we're adding a template to a dependent context, we may need to
1877 // rebuilding some of the types used within the template parameter list,
1878 // now that we know what the current instantiation is.
1879 if (SemanticContext
->isDependentContext()) {
1880 ContextRAII
SavedContext(*this, SemanticContext
);
1881 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams
))
1883 } else if (TUK
!= TUK_Friend
&& TUK
!= TUK_Reference
)
1884 diagnoseQualifiedDeclaration(SS
, SemanticContext
, Name
, NameLoc
, false);
1886 LookupQualifiedName(Previous
, SemanticContext
);
1888 SemanticContext
= CurContext
;
1890 // C++14 [class.mem]p14:
1891 // If T is the name of a class, then each of the following shall have a
1892 // name different from T:
1893 // -- every member template of class T
1894 if (TUK
!= TUK_Friend
&&
1895 DiagnoseClassNameShadow(SemanticContext
,
1896 DeclarationNameInfo(Name
, NameLoc
)))
1899 LookupName(Previous
, S
);
1902 if (Previous
.isAmbiguous())
1905 NamedDecl
*PrevDecl
= nullptr;
1906 if (Previous
.begin() != Previous
.end())
1907 PrevDecl
= (*Previous
.begin())->getUnderlyingDecl();
1909 if (PrevDecl
&& PrevDecl
->isTemplateParameter()) {
1910 // Maybe we will complain about the shadowed template parameter.
1911 DiagnoseTemplateParameterShadow(NameLoc
, PrevDecl
);
1912 // Just pretend that we didn't see the previous declaration.
1916 // If there is a previous declaration with the same name, check
1917 // whether this is a valid redeclaration.
1918 ClassTemplateDecl
*PrevClassTemplate
=
1919 dyn_cast_or_null
<ClassTemplateDecl
>(PrevDecl
);
1921 // We may have found the injected-class-name of a class template,
1922 // class template partial specialization, or class template specialization.
1923 // In these cases, grab the template that is being defined or specialized.
1924 if (!PrevClassTemplate
&& PrevDecl
&& isa
<CXXRecordDecl
>(PrevDecl
) &&
1925 cast
<CXXRecordDecl
>(PrevDecl
)->isInjectedClassName()) {
1926 PrevDecl
= cast
<CXXRecordDecl
>(PrevDecl
->getDeclContext());
1928 = cast
<CXXRecordDecl
>(PrevDecl
)->getDescribedClassTemplate();
1929 if (!PrevClassTemplate
&& isa
<ClassTemplateSpecializationDecl
>(PrevDecl
)) {
1931 = cast
<ClassTemplateSpecializationDecl
>(PrevDecl
)
1932 ->getSpecializedTemplate();
1936 if (TUK
== TUK_Friend
) {
1937 // C++ [namespace.memdef]p3:
1938 // [...] When looking for a prior declaration of a class or a function
1939 // declared as a friend, and when the name of the friend class or
1940 // function is neither a qualified name nor a template-id, scopes outside
1941 // the innermost enclosing namespace scope are not considered.
1943 DeclContext
*OutermostContext
= CurContext
;
1944 while (!OutermostContext
->isFileContext())
1945 OutermostContext
= OutermostContext
->getLookupParent();
1948 (OutermostContext
->Equals(PrevDecl
->getDeclContext()) ||
1949 OutermostContext
->Encloses(PrevDecl
->getDeclContext()))) {
1950 SemanticContext
= PrevDecl
->getDeclContext();
1952 // Declarations in outer scopes don't matter. However, the outermost
1953 // context we computed is the semantic context for our new
1955 PrevDecl
= PrevClassTemplate
= nullptr;
1956 SemanticContext
= OutermostContext
;
1958 // Check that the chosen semantic context doesn't already contain a
1959 // declaration of this name as a non-tag type.
1960 Previous
.clear(LookupOrdinaryName
);
1961 DeclContext
*LookupContext
= SemanticContext
;
1962 while (LookupContext
->isTransparentContext())
1963 LookupContext
= LookupContext
->getLookupParent();
1964 LookupQualifiedName(Previous
, LookupContext
);
1966 if (Previous
.isAmbiguous())
1969 if (Previous
.begin() != Previous
.end())
1970 PrevDecl
= (*Previous
.begin())->getUnderlyingDecl();
1973 } else if (PrevDecl
&&
1974 !isDeclInScope(Previous
.getRepresentativeDecl(), SemanticContext
,
1976 PrevDecl
= PrevClassTemplate
= nullptr;
1978 if (auto *Shadow
= dyn_cast_or_null
<UsingShadowDecl
>(
1979 PrevDecl
? Previous
.getRepresentativeDecl() : nullptr)) {
1981 !(PrevClassTemplate
&&
1982 PrevClassTemplate
->getDeclContext()->getRedeclContext()->Equals(
1983 SemanticContext
->getRedeclContext()))) {
1984 Diag(KWLoc
, diag::err_using_decl_conflict_reverse
);
1985 Diag(Shadow
->getTargetDecl()->getLocation(),
1986 diag::note_using_decl_target
);
1987 Diag(Shadow
->getIntroducer()->getLocation(), diag::note_using_decl
) << 0;
1988 // Recover by ignoring the old declaration.
1989 PrevDecl
= PrevClassTemplate
= nullptr;
1993 if (PrevClassTemplate
) {
1994 // Ensure that the template parameter lists are compatible. Skip this check
1995 // for a friend in a dependent context: the template parameter list itself
1996 // could be dependent.
1997 if (!(TUK
== TUK_Friend
&& CurContext
->isDependentContext()) &&
1998 !TemplateParameterListsAreEqual(
1999 TemplateCompareNewDeclInfo(SemanticContext
? SemanticContext
2002 TemplateParams
, PrevClassTemplate
,
2003 PrevClassTemplate
->getTemplateParameters(), /*Complain=*/true,
2007 // C++ [temp.class]p4:
2008 // In a redeclaration, partial specialization, explicit
2009 // specialization or explicit instantiation of a class template,
2010 // the class-key shall agree in kind with the original class
2011 // template declaration (7.1.5.3).
2012 RecordDecl
*PrevRecordDecl
= PrevClassTemplate
->getTemplatedDecl();
2013 if (!isAcceptableTagRedeclaration(PrevRecordDecl
, Kind
,
2014 TUK
== TUK_Definition
, KWLoc
, Name
)) {
2015 Diag(KWLoc
, diag::err_use_with_wrong_tag
)
2017 << FixItHint::CreateReplacement(KWLoc
, PrevRecordDecl
->getKindName());
2018 Diag(PrevRecordDecl
->getLocation(), diag::note_previous_use
);
2019 Kind
= PrevRecordDecl
->getTagKind();
2022 // Check for redefinition of this class template.
2023 if (TUK
== TUK_Definition
) {
2024 if (TagDecl
*Def
= PrevRecordDecl
->getDefinition()) {
2025 // If we have a prior definition that is not visible, treat this as
2026 // simply making that previous definition visible.
2027 NamedDecl
*Hidden
= nullptr;
2028 if (SkipBody
&& !hasVisibleDefinition(Def
, &Hidden
)) {
2029 SkipBody
->ShouldSkip
= true;
2030 SkipBody
->Previous
= Def
;
2031 auto *Tmpl
= cast
<CXXRecordDecl
>(Hidden
)->getDescribedClassTemplate();
2032 assert(Tmpl
&& "original definition of a class template is not a "
2034 makeMergedDefinitionVisible(Hidden
);
2035 makeMergedDefinitionVisible(Tmpl
);
2037 Diag(NameLoc
, diag::err_redefinition
) << Name
;
2038 Diag(Def
->getLocation(), diag::note_previous_definition
);
2039 // FIXME: Would it make sense to try to "forget" the previous
2040 // definition, as part of error recovery?
2045 } else if (PrevDecl
) {
2047 // A class template shall not have the same name as any other
2048 // template, class, function, object, enumeration, enumerator,
2049 // namespace, or type in the same scope (3.3), except as specified
2051 Diag(NameLoc
, diag::err_redefinition_different_kind
) << Name
;
2052 Diag(PrevDecl
->getLocation(), diag::note_previous_definition
);
2056 // Check the template parameter list of this declaration, possibly
2057 // merging in the template parameter list from the previous class
2058 // template declaration. Skip this check for a friend in a dependent
2059 // context, because the template parameter list might be dependent.
2060 if (!(TUK
== TUK_Friend
&& CurContext
->isDependentContext()) &&
2061 CheckTemplateParameterList(
2064 ? PrevClassTemplate
->getMostRecentDecl()->getTemplateParameters()
2066 (SS
.isSet() && SemanticContext
&& SemanticContext
->isRecord() &&
2067 SemanticContext
->isDependentContext())
2068 ? TPC_ClassTemplateMember
2069 : TUK
== TUK_Friend
? TPC_FriendClassTemplate
: TPC_ClassTemplate
,
2074 // If the name of the template was qualified, we must be defining the
2075 // template out-of-line.
2076 if (!SS
.isInvalid() && !Invalid
&& !PrevClassTemplate
) {
2077 Diag(NameLoc
, TUK
== TUK_Friend
? diag::err_friend_decl_does_not_match
2078 : diag::err_member_decl_does_not_match
)
2079 << Name
<< SemanticContext
<< /*IsDefinition*/true << SS
.getRange();
2084 // If this is a templated friend in a dependent context we should not put it
2085 // on the redecl chain. In some cases, the templated friend can be the most
2086 // recent declaration tricking the template instantiator to make substitutions
2088 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2089 bool ShouldAddRedecl
2090 = !(TUK
== TUK_Friend
&& CurContext
->isDependentContext());
2092 CXXRecordDecl
*NewClass
=
2093 CXXRecordDecl::Create(Context
, Kind
, SemanticContext
, KWLoc
, NameLoc
, Name
,
2094 PrevClassTemplate
&& ShouldAddRedecl
?
2095 PrevClassTemplate
->getTemplatedDecl() : nullptr,
2096 /*DelayTypeCreation=*/true);
2097 SetNestedNameSpecifier(*this, NewClass
, SS
);
2098 if (NumOuterTemplateParamLists
> 0)
2099 NewClass
->setTemplateParameterListsInfo(
2101 llvm::ArrayRef(OuterTemplateParamLists
, NumOuterTemplateParamLists
));
2103 // Add alignment attributes if necessary; these attributes are checked when
2104 // the ASTContext lays out the structure.
2105 if (TUK
== TUK_Definition
&& (!SkipBody
|| !SkipBody
->ShouldSkip
)) {
2106 AddAlignmentAttributesForRecord(NewClass
);
2107 AddMsStructLayoutForRecord(NewClass
);
2110 ClassTemplateDecl
*NewTemplate
2111 = ClassTemplateDecl::Create(Context
, SemanticContext
, NameLoc
,
2112 DeclarationName(Name
), TemplateParams
,
2115 if (ShouldAddRedecl
)
2116 NewTemplate
->setPreviousDecl(PrevClassTemplate
);
2118 NewClass
->setDescribedClassTemplate(NewTemplate
);
2120 if (ModulePrivateLoc
.isValid())
2121 NewTemplate
->setModulePrivate();
2123 // Build the type for the class template declaration now.
2124 QualType T
= NewTemplate
->getInjectedClassNameSpecialization();
2125 T
= Context
.getInjectedClassNameType(NewClass
, T
);
2126 assert(T
->isDependentType() && "Class template type is not dependent?");
2129 // If we are providing an explicit specialization of a member that is a
2130 // class template, make a note of that.
2131 if (PrevClassTemplate
&&
2132 PrevClassTemplate
->getInstantiatedFromMemberTemplate())
2133 PrevClassTemplate
->setMemberSpecialization();
2135 // Set the access specifier.
2136 if (!Invalid
&& TUK
!= TUK_Friend
&& NewTemplate
->getDeclContext()->isRecord())
2137 SetMemberAccessSpecifier(NewTemplate
, PrevClassTemplate
, AS
);
2139 // Set the lexical context of these templates
2140 NewClass
->setLexicalDeclContext(CurContext
);
2141 NewTemplate
->setLexicalDeclContext(CurContext
);
2143 if (TUK
== TUK_Definition
&& (!SkipBody
|| !SkipBody
->ShouldSkip
))
2144 NewClass
->startDefinition();
2146 ProcessDeclAttributeList(S
, NewClass
, Attr
);
2148 if (PrevClassTemplate
)
2149 mergeDeclAttributes(NewClass
, PrevClassTemplate
->getTemplatedDecl());
2151 AddPushedVisibilityAttribute(NewClass
);
2152 inferGslOwnerPointerAttribute(NewClass
);
2154 if (TUK
!= TUK_Friend
) {
2155 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2157 while ((Outer
->getFlags() & Scope::TemplateParamScope
) != 0)
2158 Outer
= Outer
->getParent();
2159 PushOnScopeChains(NewTemplate
, Outer
);
2161 if (PrevClassTemplate
&& PrevClassTemplate
->getAccess() != AS_none
) {
2162 NewTemplate
->setAccess(PrevClassTemplate
->getAccess());
2163 NewClass
->setAccess(PrevClassTemplate
->getAccess());
2166 NewTemplate
->setObjectOfFriendDecl();
2168 // Friend templates are visible in fairly strange ways.
2169 if (!CurContext
->isDependentContext()) {
2170 DeclContext
*DC
= SemanticContext
->getRedeclContext();
2171 DC
->makeDeclVisibleInContext(NewTemplate
);
2172 if (Scope
*EnclosingScope
= getScopeForDeclContext(S
, DC
))
2173 PushOnScopeChains(NewTemplate
, EnclosingScope
,
2174 /* AddToContext = */ false);
2177 FriendDecl
*Friend
= FriendDecl::Create(
2178 Context
, CurContext
, NewClass
->getLocation(), NewTemplate
, FriendLoc
);
2179 Friend
->setAccess(AS_public
);
2180 CurContext
->addDecl(Friend
);
2183 if (PrevClassTemplate
)
2184 CheckRedeclarationInModule(NewTemplate
, PrevClassTemplate
);
2187 NewTemplate
->setInvalidDecl();
2188 NewClass
->setInvalidDecl();
2191 ActOnDocumentableDecl(NewTemplate
);
2193 if (SkipBody
&& SkipBody
->ShouldSkip
)
2194 return SkipBody
->Previous
;
2200 /// Tree transform to "extract" a transformed type from a class template's
2201 /// constructor to a deduction guide.
2202 class ExtractTypeForDeductionGuide
2203 : public TreeTransform
<ExtractTypeForDeductionGuide
> {
2204 llvm::SmallVectorImpl
<TypedefNameDecl
*> &MaterializedTypedefs
;
2207 typedef TreeTransform
<ExtractTypeForDeductionGuide
> Base
;
2208 ExtractTypeForDeductionGuide(
2210 llvm::SmallVectorImpl
<TypedefNameDecl
*> &MaterializedTypedefs
)
2211 : Base(SemaRef
), MaterializedTypedefs(MaterializedTypedefs
) {}
2213 TypeSourceInfo
*transform(TypeSourceInfo
*TSI
) { return TransformType(TSI
); }
2215 QualType
TransformTypedefType(TypeLocBuilder
&TLB
, TypedefTypeLoc TL
) {
2216 ASTContext
&Context
= SemaRef
.getASTContext();
2217 TypedefNameDecl
*OrigDecl
= TL
.getTypedefNameDecl();
2218 TypedefNameDecl
*Decl
= OrigDecl
;
2219 // Transform the underlying type of the typedef and clone the Decl only if
2220 // the typedef has a dependent context.
2221 if (OrigDecl
->getDeclContext()->isDependentContext()) {
2222 TypeLocBuilder InnerTLB
;
2223 QualType Transformed
=
2224 TransformType(InnerTLB
, OrigDecl
->getTypeSourceInfo()->getTypeLoc());
2225 TypeSourceInfo
*TSI
= InnerTLB
.getTypeSourceInfo(Context
, Transformed
);
2226 if (isa
<TypeAliasDecl
>(OrigDecl
))
2227 Decl
= TypeAliasDecl::Create(
2228 Context
, Context
.getTranslationUnitDecl(), OrigDecl
->getBeginLoc(),
2229 OrigDecl
->getLocation(), OrigDecl
->getIdentifier(), TSI
);
2231 assert(isa
<TypedefDecl
>(OrigDecl
) && "Not a Type alias or typedef");
2232 Decl
= TypedefDecl::Create(
2233 Context
, Context
.getTranslationUnitDecl(), OrigDecl
->getBeginLoc(),
2234 OrigDecl
->getLocation(), OrigDecl
->getIdentifier(), TSI
);
2236 MaterializedTypedefs
.push_back(Decl
);
2239 QualType TDTy
= Context
.getTypedefType(Decl
);
2240 TypedefTypeLoc TypedefTL
= TLB
.push
<TypedefTypeLoc
>(TDTy
);
2241 TypedefTL
.setNameLoc(TL
.getNameLoc());
2247 /// Transform to convert portions of a constructor declaration into the
2248 /// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
2249 struct ConvertConstructorToDeductionGuideTransform
{
2250 ConvertConstructorToDeductionGuideTransform(Sema
&S
,
2251 ClassTemplateDecl
*Template
)
2252 : SemaRef(S
), Template(Template
) {}
2255 ClassTemplateDecl
*Template
;
2256 ClassTemplateDecl
*NestedPattern
= nullptr;
2258 DeclContext
*DC
= Template
->getDeclContext();
2259 CXXRecordDecl
*Primary
= Template
->getTemplatedDecl();
2260 DeclarationName DeductionGuideName
=
2261 SemaRef
.Context
.DeclarationNames
.getCXXDeductionGuideName(Template
);
2263 QualType DeducedType
= SemaRef
.Context
.getTypeDeclType(Primary
);
2265 // Index adjustment to apply to convert depth-1 template parameters into
2266 // depth-0 template parameters.
2267 unsigned Depth1IndexAdjustment
= Template
->getTemplateParameters()->size();
2269 /// Transform a constructor declaration into a deduction guide.
2270 NamedDecl
*transformConstructor(FunctionTemplateDecl
*FTD
,
2271 CXXConstructorDecl
*CD
) {
2272 SmallVector
<TemplateArgument
, 16> SubstArgs
;
2274 LocalInstantiationScope
Scope(SemaRef
);
2276 // C++ [over.match.class.deduct]p1:
2277 // -- For each constructor of the class template designated by the
2278 // template-name, a function template with the following properties:
2280 // -- The template parameters are the template parameters of the class
2281 // template followed by the template parameters (including default
2282 // template arguments) of the constructor, if any.
2283 TemplateParameterList
*TemplateParams
= Template
->getTemplateParameters();
2285 TemplateParameterList
*InnerParams
= FTD
->getTemplateParameters();
2286 SmallVector
<NamedDecl
*, 16> AllParams
;
2287 AllParams
.reserve(TemplateParams
->size() + InnerParams
->size());
2288 AllParams
.insert(AllParams
.begin(),
2289 TemplateParams
->begin(), TemplateParams
->end());
2290 SubstArgs
.reserve(InnerParams
->size());
2292 // Later template parameters could refer to earlier ones, so build up
2293 // a list of substituted template arguments as we go.
2294 for (NamedDecl
*Param
: *InnerParams
) {
2295 MultiLevelTemplateArgumentList Args
;
2296 Args
.setKind(TemplateSubstitutionKind::Rewrite
);
2297 Args
.addOuterTemplateArguments(SubstArgs
);
2298 Args
.addOuterRetainedLevel();
2299 NamedDecl
*NewParam
= transformTemplateParameter(Param
, Args
);
2302 AllParams
.push_back(NewParam
);
2303 SubstArgs
.push_back(SemaRef
.Context
.getCanonicalTemplateArgument(
2304 SemaRef
.Context
.getInjectedTemplateArg(NewParam
)));
2307 // Substitute new template parameters into requires-clause if present.
2308 Expr
*RequiresClause
= nullptr;
2309 if (Expr
*InnerRC
= InnerParams
->getRequiresClause()) {
2310 MultiLevelTemplateArgumentList Args
;
2311 Args
.setKind(TemplateSubstitutionKind::Rewrite
);
2312 Args
.addOuterTemplateArguments(SubstArgs
);
2313 Args
.addOuterRetainedLevel();
2314 ExprResult E
= SemaRef
.SubstExpr(InnerRC
, Args
);
2317 RequiresClause
= E
.getAs
<Expr
>();
2320 TemplateParams
= TemplateParameterList::Create(
2321 SemaRef
.Context
, InnerParams
->getTemplateLoc(),
2322 InnerParams
->getLAngleLoc(), AllParams
, InnerParams
->getRAngleLoc(),
2326 // If we built a new template-parameter-list, track that we need to
2327 // substitute references to the old parameters into references to the
2329 MultiLevelTemplateArgumentList Args
;
2330 Args
.setKind(TemplateSubstitutionKind::Rewrite
);
2332 Args
.addOuterTemplateArguments(SubstArgs
);
2333 Args
.addOuterRetainedLevel();
2337 Args
.addOuterRetainedLevels(NestedPattern
->getTemplateDepth());
2339 FunctionProtoTypeLoc FPTL
= CD
->getTypeSourceInfo()->getTypeLoc()
2340 .getAsAdjusted
<FunctionProtoTypeLoc
>();
2341 assert(FPTL
&& "no prototype for constructor declaration");
2343 // Transform the type of the function, adjusting the return type and
2344 // replacing references to the old parameters with references to the
2347 SmallVector
<ParmVarDecl
*, 8> Params
;
2348 SmallVector
<TypedefNameDecl
*, 4> MaterializedTypedefs
;
2349 QualType NewType
= transformFunctionProtoType(TLB
, FPTL
, Params
, Args
,
2350 MaterializedTypedefs
);
2351 if (NewType
.isNull())
2353 TypeSourceInfo
*NewTInfo
= TLB
.getTypeSourceInfo(SemaRef
.Context
, NewType
);
2355 return buildDeductionGuide(TemplateParams
, CD
, CD
->getExplicitSpecifier(),
2356 NewTInfo
, CD
->getBeginLoc(), CD
->getLocation(),
2357 CD
->getEndLoc(), MaterializedTypedefs
);
2360 /// Build a deduction guide with the specified parameter types.
2361 NamedDecl
*buildSimpleDeductionGuide(MutableArrayRef
<QualType
> ParamTypes
) {
2362 SourceLocation Loc
= Template
->getLocation();
2364 // Build the requested type.
2365 FunctionProtoType::ExtProtoInfo EPI
;
2366 EPI
.HasTrailingReturn
= true;
2367 QualType Result
= SemaRef
.BuildFunctionType(DeducedType
, ParamTypes
, Loc
,
2368 DeductionGuideName
, EPI
);
2369 TypeSourceInfo
*TSI
= SemaRef
.Context
.getTrivialTypeSourceInfo(Result
, Loc
);
2371 FunctionProtoTypeLoc FPTL
=
2372 TSI
->getTypeLoc().castAs
<FunctionProtoTypeLoc
>();
2374 // Build the parameters, needed during deduction / substitution.
2375 SmallVector
<ParmVarDecl
*, 4> Params
;
2376 for (auto T
: ParamTypes
) {
2377 ParmVarDecl
*NewParam
= ParmVarDecl::Create(
2378 SemaRef
.Context
, DC
, Loc
, Loc
, nullptr, T
,
2379 SemaRef
.Context
.getTrivialTypeSourceInfo(T
, Loc
), SC_None
, nullptr);
2380 NewParam
->setScopeInfo(0, Params
.size());
2381 FPTL
.setParam(Params
.size(), NewParam
);
2382 Params
.push_back(NewParam
);
2385 return buildDeductionGuide(Template
->getTemplateParameters(), nullptr,
2386 ExplicitSpecifier(), TSI
, Loc
, Loc
, Loc
);
2390 /// Transform a constructor template parameter into a deduction guide template
2391 /// parameter, rebuilding any internal references to earlier parameters and
2392 /// renumbering as we go.
2393 NamedDecl
*transformTemplateParameter(NamedDecl
*TemplateParam
,
2394 MultiLevelTemplateArgumentList
&Args
) {
2395 if (auto *TTP
= dyn_cast
<TemplateTypeParmDecl
>(TemplateParam
)) {
2396 // TemplateTypeParmDecl's index cannot be changed after creation, so
2397 // substitute it directly.
2398 auto *NewTTP
= TemplateTypeParmDecl::Create(
2399 SemaRef
.Context
, DC
, TTP
->getBeginLoc(), TTP
->getLocation(),
2400 /*Depth*/ 0, Depth1IndexAdjustment
+ TTP
->getIndex(),
2401 TTP
->getIdentifier(), TTP
->wasDeclaredWithTypename(),
2402 TTP
->isParameterPack(), TTP
->hasTypeConstraint(),
2403 TTP
->isExpandedParameterPack()
2404 ? std::optional
<unsigned>(TTP
->getNumExpansionParameters())
2406 if (const auto *TC
= TTP
->getTypeConstraint())
2407 SemaRef
.SubstTypeConstraint(NewTTP
, TC
, Args
,
2408 /*EvaluateConstraint*/ true);
2409 if (TTP
->hasDefaultArgument()) {
2410 TypeSourceInfo
*InstantiatedDefaultArg
=
2411 SemaRef
.SubstType(TTP
->getDefaultArgumentInfo(), Args
,
2412 TTP
->getDefaultArgumentLoc(), TTP
->getDeclName());
2413 if (InstantiatedDefaultArg
)
2414 NewTTP
->setDefaultArgument(InstantiatedDefaultArg
);
2416 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(TemplateParam
,
2421 if (auto *TTP
= dyn_cast
<TemplateTemplateParmDecl
>(TemplateParam
))
2422 return transformTemplateParameterImpl(TTP
, Args
);
2424 return transformTemplateParameterImpl(
2425 cast
<NonTypeTemplateParmDecl
>(TemplateParam
), Args
);
2427 template<typename TemplateParmDecl
>
2429 transformTemplateParameterImpl(TemplateParmDecl
*OldParam
,
2430 MultiLevelTemplateArgumentList
&Args
) {
2431 // Ask the template instantiator to do the heavy lifting for us, then adjust
2432 // the index of the parameter once it's done.
2434 cast
<TemplateParmDecl
>(SemaRef
.SubstDecl(OldParam
, DC
, Args
));
2435 assert(NewParam
->getDepth() == 0 && "unexpected template param depth");
2436 NewParam
->setPosition(NewParam
->getPosition() + Depth1IndexAdjustment
);
2440 QualType
transformFunctionProtoType(
2441 TypeLocBuilder
&TLB
, FunctionProtoTypeLoc TL
,
2442 SmallVectorImpl
<ParmVarDecl
*> &Params
,
2443 MultiLevelTemplateArgumentList
&Args
,
2444 SmallVectorImpl
<TypedefNameDecl
*> &MaterializedTypedefs
) {
2445 SmallVector
<QualType
, 4> ParamTypes
;
2446 const FunctionProtoType
*T
= TL
.getTypePtr();
2448 MultiLevelTemplateArgumentList OuterInstantiationArgs
;
2450 OuterInstantiationArgs
= SemaRef
.getTemplateInstantiationArgs(Template
);
2452 // -- The types of the function parameters are those of the constructor.
2453 for (auto *OldParam
: TL
.getParams()) {
2454 ParmVarDecl
*NewParam
=
2455 transformFunctionTypeParam(OldParam
, Args
, MaterializedTypedefs
);
2456 if (NestedPattern
&& NewParam
)
2457 NewParam
= transformFunctionTypeParam(NewParam
, OuterInstantiationArgs
,
2458 MaterializedTypedefs
);
2461 ParamTypes
.push_back(NewParam
->getType());
2462 Params
.push_back(NewParam
);
2465 // -- The return type is the class template specialization designated by
2466 // the template-name and template arguments corresponding to the
2467 // template parameters obtained from the class template.
2469 // We use the injected-class-name type of the primary template instead.
2470 // This has the convenient property that it is different from any type that
2471 // the user can write in a deduction-guide (because they cannot enter the
2472 // context of the template), so implicit deduction guides can never collide
2473 // with explicit ones.
2474 QualType ReturnType
= DeducedType
;
2475 TLB
.pushTypeSpec(ReturnType
).setNameLoc(Primary
->getLocation());
2477 // Resolving a wording defect, we also inherit the variadicness of the
2479 FunctionProtoType::ExtProtoInfo EPI
;
2480 EPI
.Variadic
= T
->isVariadic();
2481 EPI
.HasTrailingReturn
= true;
2483 QualType Result
= SemaRef
.BuildFunctionType(
2484 ReturnType
, ParamTypes
, TL
.getBeginLoc(), DeductionGuideName
, EPI
);
2485 if (Result
.isNull())
2488 FunctionProtoTypeLoc NewTL
= TLB
.push
<FunctionProtoTypeLoc
>(Result
);
2489 NewTL
.setLocalRangeBegin(TL
.getLocalRangeBegin());
2490 NewTL
.setLParenLoc(TL
.getLParenLoc());
2491 NewTL
.setRParenLoc(TL
.getRParenLoc());
2492 NewTL
.setExceptionSpecRange(SourceRange());
2493 NewTL
.setLocalRangeEnd(TL
.getLocalRangeEnd());
2494 for (unsigned I
= 0, E
= NewTL
.getNumParams(); I
!= E
; ++I
)
2495 NewTL
.setParam(I
, Params
[I
]);
2500 ParmVarDecl
*transformFunctionTypeParam(
2501 ParmVarDecl
*OldParam
, MultiLevelTemplateArgumentList
&Args
,
2502 llvm::SmallVectorImpl
<TypedefNameDecl
*> &MaterializedTypedefs
) {
2503 TypeSourceInfo
*OldDI
= OldParam
->getTypeSourceInfo();
2504 TypeSourceInfo
*NewDI
;
2505 if (auto PackTL
= OldDI
->getTypeLoc().getAs
<PackExpansionTypeLoc
>()) {
2506 // Expand out the one and only element in each inner pack.
2507 Sema::ArgumentPackSubstitutionIndexRAII
SubstIndex(SemaRef
, 0);
2509 SemaRef
.SubstType(PackTL
.getPatternLoc(), Args
,
2510 OldParam
->getLocation(), OldParam
->getDeclName());
2511 if (!NewDI
) return nullptr;
2513 SemaRef
.CheckPackExpansion(NewDI
, PackTL
.getEllipsisLoc(),
2514 PackTL
.getTypePtr()->getNumExpansions());
2516 NewDI
= SemaRef
.SubstType(OldDI
, Args
, OldParam
->getLocation(),
2517 OldParam
->getDeclName());
2521 // Extract the type. This (for instance) replaces references to typedef
2522 // members of the current instantiations with the definitions of those
2523 // typedefs, avoiding triggering instantiation of the deduced type during
2525 NewDI
= ExtractTypeForDeductionGuide(SemaRef
, MaterializedTypedefs
)
2528 // Resolving a wording defect, we also inherit default arguments from the
2530 ExprResult NewDefArg
;
2531 if (OldParam
->hasDefaultArg()) {
2532 // We don't care what the value is (we won't use it); just create a
2533 // placeholder to indicate there is a default argument.
2534 QualType ParamTy
= NewDI
->getType();
2535 NewDefArg
= new (SemaRef
.Context
)
2536 OpaqueValueExpr(OldParam
->getDefaultArg()->getBeginLoc(),
2537 ParamTy
.getNonLValueExprType(SemaRef
.Context
),
2538 ParamTy
->isLValueReferenceType() ? VK_LValue
2539 : ParamTy
->isRValueReferenceType() ? VK_XValue
2543 ParmVarDecl
*NewParam
= ParmVarDecl::Create(SemaRef
.Context
, DC
,
2544 OldParam
->getInnerLocStart(),
2545 OldParam
->getLocation(),
2546 OldParam
->getIdentifier(),
2549 OldParam
->getStorageClass(),
2551 NewParam
->setScopeInfo(OldParam
->getFunctionScopeDepth(),
2552 OldParam
->getFunctionScopeIndex());
2553 SemaRef
.CurrentInstantiationScope
->InstantiatedLocal(OldParam
, NewParam
);
2557 FunctionTemplateDecl
*buildDeductionGuide(
2558 TemplateParameterList
*TemplateParams
, CXXConstructorDecl
*Ctor
,
2559 ExplicitSpecifier ES
, TypeSourceInfo
*TInfo
, SourceLocation LocStart
,
2560 SourceLocation Loc
, SourceLocation LocEnd
,
2561 llvm::ArrayRef
<TypedefNameDecl
*> MaterializedTypedefs
= {}) {
2562 DeclarationNameInfo
Name(DeductionGuideName
, Loc
);
2563 ArrayRef
<ParmVarDecl
*> Params
=
2564 TInfo
->getTypeLoc().castAs
<FunctionProtoTypeLoc
>().getParams();
2566 // Build the implicit deduction guide template.
2568 CXXDeductionGuideDecl::Create(SemaRef
.Context
, DC
, LocStart
, ES
, Name
,
2569 TInfo
->getType(), TInfo
, LocEnd
, Ctor
);
2570 Guide
->setImplicit();
2571 Guide
->setParams(Params
);
2573 for (auto *Param
: Params
)
2574 Param
->setDeclContext(Guide
);
2575 for (auto *TD
: MaterializedTypedefs
)
2576 TD
->setDeclContext(Guide
);
2578 auto *GuideTemplate
= FunctionTemplateDecl::Create(
2579 SemaRef
.Context
, DC
, Loc
, DeductionGuideName
, TemplateParams
, Guide
);
2580 GuideTemplate
->setImplicit();
2581 Guide
->setDescribedFunctionTemplate(GuideTemplate
);
2583 if (isa
<CXXRecordDecl
>(DC
)) {
2584 Guide
->setAccess(AS_public
);
2585 GuideTemplate
->setAccess(AS_public
);
2588 DC
->addDecl(GuideTemplate
);
2589 return GuideTemplate
;
2594 FunctionTemplateDecl
*Sema::DeclareImplicitDeductionGuideFromInitList(
2595 TemplateDecl
*Template
, MutableArrayRef
<QualType
> ParamTypes
,
2596 SourceLocation Loc
) {
2597 if (CXXRecordDecl
*DefRecord
=
2598 cast
<CXXRecordDecl
>(Template
->getTemplatedDecl())->getDefinition()) {
2599 if (TemplateDecl
*DescribedTemplate
=
2600 DefRecord
->getDescribedClassTemplate())
2601 Template
= DescribedTemplate
;
2604 DeclContext
*DC
= Template
->getDeclContext();
2605 if (DC
->isDependentContext())
2608 ConvertConstructorToDeductionGuideTransform
Transform(
2609 *this, cast
<ClassTemplateDecl
>(Template
));
2610 if (!isCompleteType(Loc
, Transform
.DeducedType
))
2613 // In case we were expanding a pack when we attempted to declare deduction
2614 // guides, turn off pack expansion for everything we're about to do.
2615 ArgumentPackSubstitutionIndexRAII
SubstIndex(*this,
2616 /*NewSubstitutionIndex=*/-1);
2617 // Create a template instantiation record to track the "instantiation" of
2618 // constructors into deduction guides.
2619 InstantiatingTemplate
BuildingDeductionGuides(
2620 *this, Loc
, Template
,
2621 Sema::InstantiatingTemplate::BuildingDeductionGuidesTag
{});
2622 if (BuildingDeductionGuides
.isInvalid())
2625 return cast
<FunctionTemplateDecl
>(
2626 Transform
.buildSimpleDeductionGuide(ParamTypes
));
2629 void Sema::DeclareImplicitDeductionGuides(TemplateDecl
*Template
,
2630 SourceLocation Loc
) {
2631 if (CXXRecordDecl
*DefRecord
=
2632 cast
<CXXRecordDecl
>(Template
->getTemplatedDecl())->getDefinition()) {
2633 if (TemplateDecl
*DescribedTemplate
= DefRecord
->getDescribedClassTemplate())
2634 Template
= DescribedTemplate
;
2637 DeclContext
*DC
= Template
->getDeclContext();
2638 if (DC
->isDependentContext())
2641 ConvertConstructorToDeductionGuideTransform
Transform(
2642 *this, cast
<ClassTemplateDecl
>(Template
));
2643 if (!isCompleteType(Loc
, Transform
.DeducedType
))
2646 // Check whether we've already declared deduction guides for this template.
2647 // FIXME: Consider storing a flag on the template to indicate this.
2648 auto Existing
= DC
->lookup(Transform
.DeductionGuideName
);
2649 for (auto *D
: Existing
)
2650 if (D
->isImplicit())
2653 // In case we were expanding a pack when we attempted to declare deduction
2654 // guides, turn off pack expansion for everything we're about to do.
2655 ArgumentPackSubstitutionIndexRAII
SubstIndex(*this, -1);
2656 // Create a template instantiation record to track the "instantiation" of
2657 // constructors into deduction guides.
2658 InstantiatingTemplate
BuildingDeductionGuides(
2659 *this, Loc
, Template
,
2660 Sema::InstantiatingTemplate::BuildingDeductionGuidesTag
{});
2661 if (BuildingDeductionGuides
.isInvalid())
2664 // If the template is nested, then we need to use the original
2665 // pattern to iterate over the constructors.
2666 ClassTemplateDecl
*Pattern
= Transform
.Template
;
2667 while (Pattern
->getInstantiatedFromMemberTemplate()) {
2668 if (Pattern
->isMemberSpecialization())
2670 Pattern
= Pattern
->getInstantiatedFromMemberTemplate();
2671 Transform
.NestedPattern
= Pattern
;
2674 // Convert declared constructors into deduction guide templates.
2675 // FIXME: Skip constructors for which deduction must necessarily fail (those
2676 // for which some class template parameter without a default argument never
2677 // appears in a deduced context).
2678 ContextRAII
SavedContext(*this, Pattern
->getTemplatedDecl());
2679 llvm::SmallPtrSet
<NamedDecl
*, 8> ProcessedCtors
;
2680 bool AddedAny
= false;
2681 for (NamedDecl
*D
: LookupConstructors(Pattern
->getTemplatedDecl())) {
2682 D
= D
->getUnderlyingDecl();
2683 if (D
->isInvalidDecl() || D
->isImplicit())
2686 D
= cast
<NamedDecl
>(D
->getCanonicalDecl());
2688 // Within C++20 modules, we may have multiple same constructors in
2689 // multiple same RecordDecls. And it doesn't make sense to create
2690 // duplicated deduction guides for the duplicated constructors.
2691 if (ProcessedCtors
.count(D
))
2694 auto *FTD
= dyn_cast
<FunctionTemplateDecl
>(D
);
2696 dyn_cast_or_null
<CXXConstructorDecl
>(FTD
? FTD
->getTemplatedDecl() : D
);
2697 // Class-scope explicit specializations (MS extension) do not result in
2698 // deduction guides.
2699 if (!CD
|| (!FTD
&& CD
->isFunctionTemplateSpecialization()))
2702 // Cannot make a deduction guide when unparsed arguments are present.
2703 if (llvm::any_of(CD
->parameters(), [](ParmVarDecl
*P
) {
2704 return !P
|| P
->hasUnparsedDefaultArg();
2708 ProcessedCtors
.insert(D
);
2709 Transform
.transformConstructor(FTD
, CD
);
2713 // C++17 [over.match.class.deduct]
2714 // -- If C is not defined or does not declare any constructors, an
2715 // additional function template derived as above from a hypothetical
2718 Transform
.buildSimpleDeductionGuide(std::nullopt
);
2720 // -- An additional function template derived as above from a hypothetical
2721 // constructor C(C), called the copy deduction candidate.
2722 cast
<CXXDeductionGuideDecl
>(
2723 cast
<FunctionTemplateDecl
>(
2724 Transform
.buildSimpleDeductionGuide(Transform
.DeducedType
))
2725 ->getTemplatedDecl())
2726 ->setDeductionCandidateKind(DeductionCandidate::Copy
);
2731 /// Diagnose the presence of a default template argument on a
2732 /// template parameter, which is ill-formed in certain contexts.
2734 /// \returns true if the default template argument should be dropped.
2735 static bool DiagnoseDefaultTemplateArgument(Sema
&S
,
2736 Sema::TemplateParamListContext TPC
,
2737 SourceLocation ParamLoc
,
2738 SourceRange DefArgRange
) {
2740 case Sema::TPC_ClassTemplate
:
2741 case Sema::TPC_VarTemplate
:
2742 case Sema::TPC_TypeAliasTemplate
:
2745 case Sema::TPC_FunctionTemplate
:
2746 case Sema::TPC_FriendFunctionTemplateDefinition
:
2747 // C++ [temp.param]p9:
2748 // A default template-argument shall not be specified in a
2749 // function template declaration or a function template
2751 // If a friend function template declaration specifies a default
2752 // template-argument, that declaration shall be a definition and shall be
2753 // the only declaration of the function template in the translation unit.
2754 // (C++98/03 doesn't have this wording; see DR226).
2755 S
.Diag(ParamLoc
, S
.getLangOpts().CPlusPlus11
?
2756 diag::warn_cxx98_compat_template_parameter_default_in_function_template
2757 : diag::ext_template_parameter_default_in_function_template
)
2761 case Sema::TPC_ClassTemplateMember
:
2762 // C++0x [temp.param]p9:
2763 // A default template-argument shall not be specified in the
2764 // template-parameter-lists of the definition of a member of a
2765 // class template that appears outside of the member's class.
2766 S
.Diag(ParamLoc
, diag::err_template_parameter_default_template_member
)
2770 case Sema::TPC_FriendClassTemplate
:
2771 case Sema::TPC_FriendFunctionTemplate
:
2772 // C++ [temp.param]p9:
2773 // A default template-argument shall not be specified in a
2774 // friend template declaration.
2775 S
.Diag(ParamLoc
, diag::err_template_parameter_default_friend_template
)
2779 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2780 // for friend function templates if there is only a single
2781 // declaration (and it is a definition). Strange!
2784 llvm_unreachable("Invalid TemplateParamListContext!");
2787 /// Check for unexpanded parameter packs within the template parameters
2788 /// of a template template parameter, recursively.
2789 static bool DiagnoseUnexpandedParameterPacks(Sema
&S
,
2790 TemplateTemplateParmDecl
*TTP
) {
2791 // A template template parameter which is a parameter pack is also a pack
2793 if (TTP
->isParameterPack())
2796 TemplateParameterList
*Params
= TTP
->getTemplateParameters();
2797 for (unsigned I
= 0, N
= Params
->size(); I
!= N
; ++I
) {
2798 NamedDecl
*P
= Params
->getParam(I
);
2799 if (TemplateTypeParmDecl
*TTP
= dyn_cast
<TemplateTypeParmDecl
>(P
)) {
2800 if (!TTP
->isParameterPack())
2801 if (const TypeConstraint
*TC
= TTP
->getTypeConstraint())
2802 if (TC
->hasExplicitTemplateArgs())
2803 for (auto &ArgLoc
: TC
->getTemplateArgsAsWritten()->arguments())
2804 if (S
.DiagnoseUnexpandedParameterPack(ArgLoc
,
2805 Sema::UPPC_TypeConstraint
))
2810 if (NonTypeTemplateParmDecl
*NTTP
= dyn_cast
<NonTypeTemplateParmDecl
>(P
)) {
2811 if (!NTTP
->isParameterPack() &&
2812 S
.DiagnoseUnexpandedParameterPack(NTTP
->getLocation(),
2813 NTTP
->getTypeSourceInfo(),
2814 Sema::UPPC_NonTypeTemplateParameterType
))
2820 if (TemplateTemplateParmDecl
*InnerTTP
2821 = dyn_cast
<TemplateTemplateParmDecl
>(P
))
2822 if (DiagnoseUnexpandedParameterPacks(S
, InnerTTP
))
2829 /// Checks the validity of a template parameter list, possibly
2830 /// considering the template parameter list from a previous
2833 /// If an "old" template parameter list is provided, it must be
2834 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
2835 /// template parameter list.
2837 /// \param NewParams Template parameter list for a new template
2838 /// declaration. This template parameter list will be updated with any
2839 /// default arguments that are carried through from the previous
2840 /// template parameter list.
2842 /// \param OldParams If provided, template parameter list from a
2843 /// previous declaration of the same template. Default template
2844 /// arguments will be merged from the old template parameter list to
2845 /// the new template parameter list.
2847 /// \param TPC Describes the context in which we are checking the given
2848 /// template parameter list.
2850 /// \param SkipBody If we might have already made a prior merged definition
2851 /// of this template visible, the corresponding body-skipping information.
2852 /// Default argument redefinition is not an error when skipping such a body,
2853 /// because (under the ODR) we can assume the default arguments are the same
2854 /// as the prior merged definition.
2856 /// \returns true if an error occurred, false otherwise.
2857 bool Sema::CheckTemplateParameterList(TemplateParameterList
*NewParams
,
2858 TemplateParameterList
*OldParams
,
2859 TemplateParamListContext TPC
,
2860 SkipBodyInfo
*SkipBody
) {
2861 bool Invalid
= false;
2863 // C++ [temp.param]p10:
2864 // The set of default template-arguments available for use with a
2865 // template declaration or definition is obtained by merging the
2866 // default arguments from the definition (if in scope) and all
2867 // declarations in scope in the same way default function
2868 // arguments are (8.3.6).
2869 bool SawDefaultArgument
= false;
2870 SourceLocation PreviousDefaultArgLoc
;
2872 // Dummy initialization to avoid warnings.
2873 TemplateParameterList::iterator OldParam
= NewParams
->end();
2875 OldParam
= OldParams
->begin();
2877 bool RemoveDefaultArguments
= false;
2878 for (TemplateParameterList::iterator NewParam
= NewParams
->begin(),
2879 NewParamEnd
= NewParams
->end();
2880 NewParam
!= NewParamEnd
; ++NewParam
) {
2881 // Whether we've seen a duplicate default argument in the same translation
2883 bool RedundantDefaultArg
= false;
2884 // Whether we've found inconsis inconsitent default arguments in different
2885 // translation unit.
2886 bool InconsistentDefaultArg
= false;
2887 // The name of the module which contains the inconsistent default argument.
2888 std::string PrevModuleName
;
2890 SourceLocation OldDefaultLoc
;
2891 SourceLocation NewDefaultLoc
;
2893 // Variable used to diagnose missing default arguments
2894 bool MissingDefaultArg
= false;
2896 // Variable used to diagnose non-final parameter packs
2897 bool SawParameterPack
= false;
2899 if (TemplateTypeParmDecl
*NewTypeParm
2900 = dyn_cast
<TemplateTypeParmDecl
>(*NewParam
)) {
2901 // Check the presence of a default argument here.
2902 if (NewTypeParm
->hasDefaultArgument() &&
2903 DiagnoseDefaultTemplateArgument(*this, TPC
,
2904 NewTypeParm
->getLocation(),
2905 NewTypeParm
->getDefaultArgumentInfo()->getTypeLoc()
2907 NewTypeParm
->removeDefaultArgument();
2909 // Merge default arguments for template type parameters.
2910 TemplateTypeParmDecl
*OldTypeParm
2911 = OldParams
? cast
<TemplateTypeParmDecl
>(*OldParam
) : nullptr;
2912 if (NewTypeParm
->isParameterPack()) {
2913 assert(!NewTypeParm
->hasDefaultArgument() &&
2914 "Parameter packs can't have a default argument!");
2915 SawParameterPack
= true;
2916 } else if (OldTypeParm
&& hasVisibleDefaultArgument(OldTypeParm
) &&
2917 NewTypeParm
->hasDefaultArgument() &&
2918 (!SkipBody
|| !SkipBody
->ShouldSkip
)) {
2919 OldDefaultLoc
= OldTypeParm
->getDefaultArgumentLoc();
2920 NewDefaultLoc
= NewTypeParm
->getDefaultArgumentLoc();
2921 SawDefaultArgument
= true;
2923 if (!OldTypeParm
->getOwningModule())
2924 RedundantDefaultArg
= true;
2925 else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm
,
2927 InconsistentDefaultArg
= true;
2929 OldTypeParm
->getImportedOwningModule()->getFullModuleName();
2931 PreviousDefaultArgLoc
= NewDefaultLoc
;
2932 } else if (OldTypeParm
&& OldTypeParm
->hasDefaultArgument()) {
2933 // Merge the default argument from the old declaration to the
2935 NewTypeParm
->setInheritedDefaultArgument(Context
, OldTypeParm
);
2936 PreviousDefaultArgLoc
= OldTypeParm
->getDefaultArgumentLoc();
2937 } else if (NewTypeParm
->hasDefaultArgument()) {
2938 SawDefaultArgument
= true;
2939 PreviousDefaultArgLoc
= NewTypeParm
->getDefaultArgumentLoc();
2940 } else if (SawDefaultArgument
)
2941 MissingDefaultArg
= true;
2942 } else if (NonTypeTemplateParmDecl
*NewNonTypeParm
2943 = dyn_cast
<NonTypeTemplateParmDecl
>(*NewParam
)) {
2944 // Check for unexpanded parameter packs.
2945 if (!NewNonTypeParm
->isParameterPack() &&
2946 DiagnoseUnexpandedParameterPack(NewNonTypeParm
->getLocation(),
2947 NewNonTypeParm
->getTypeSourceInfo(),
2948 UPPC_NonTypeTemplateParameterType
)) {
2953 // Check the presence of a default argument here.
2954 if (NewNonTypeParm
->hasDefaultArgument() &&
2955 DiagnoseDefaultTemplateArgument(*this, TPC
,
2956 NewNonTypeParm
->getLocation(),
2957 NewNonTypeParm
->getDefaultArgument()->getSourceRange())) {
2958 NewNonTypeParm
->removeDefaultArgument();
2961 // Merge default arguments for non-type template parameters
2962 NonTypeTemplateParmDecl
*OldNonTypeParm
2963 = OldParams
? cast
<NonTypeTemplateParmDecl
>(*OldParam
) : nullptr;
2964 if (NewNonTypeParm
->isParameterPack()) {
2965 assert(!NewNonTypeParm
->hasDefaultArgument() &&
2966 "Parameter packs can't have a default argument!");
2967 if (!NewNonTypeParm
->isPackExpansion())
2968 SawParameterPack
= true;
2969 } else if (OldNonTypeParm
&& hasVisibleDefaultArgument(OldNonTypeParm
) &&
2970 NewNonTypeParm
->hasDefaultArgument() &&
2971 (!SkipBody
|| !SkipBody
->ShouldSkip
)) {
2972 OldDefaultLoc
= OldNonTypeParm
->getDefaultArgumentLoc();
2973 NewDefaultLoc
= NewNonTypeParm
->getDefaultArgumentLoc();
2974 SawDefaultArgument
= true;
2975 if (!OldNonTypeParm
->getOwningModule())
2976 RedundantDefaultArg
= true;
2977 else if (!getASTContext().isSameDefaultTemplateArgument(
2978 OldNonTypeParm
, NewNonTypeParm
)) {
2979 InconsistentDefaultArg
= true;
2981 OldNonTypeParm
->getImportedOwningModule()->getFullModuleName();
2983 PreviousDefaultArgLoc
= NewDefaultLoc
;
2984 } else if (OldNonTypeParm
&& OldNonTypeParm
->hasDefaultArgument()) {
2985 // Merge the default argument from the old declaration to the
2987 NewNonTypeParm
->setInheritedDefaultArgument(Context
, OldNonTypeParm
);
2988 PreviousDefaultArgLoc
= OldNonTypeParm
->getDefaultArgumentLoc();
2989 } else if (NewNonTypeParm
->hasDefaultArgument()) {
2990 SawDefaultArgument
= true;
2991 PreviousDefaultArgLoc
= NewNonTypeParm
->getDefaultArgumentLoc();
2992 } else if (SawDefaultArgument
)
2993 MissingDefaultArg
= true;
2995 TemplateTemplateParmDecl
*NewTemplateParm
2996 = cast
<TemplateTemplateParmDecl
>(*NewParam
);
2998 // Check for unexpanded parameter packs, recursively.
2999 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm
)) {
3004 // Check the presence of a default argument here.
3005 if (NewTemplateParm
->hasDefaultArgument() &&
3006 DiagnoseDefaultTemplateArgument(*this, TPC
,
3007 NewTemplateParm
->getLocation(),
3008 NewTemplateParm
->getDefaultArgument().getSourceRange()))
3009 NewTemplateParm
->removeDefaultArgument();
3011 // Merge default arguments for template template parameters
3012 TemplateTemplateParmDecl
*OldTemplateParm
3013 = OldParams
? cast
<TemplateTemplateParmDecl
>(*OldParam
) : nullptr;
3014 if (NewTemplateParm
->isParameterPack()) {
3015 assert(!NewTemplateParm
->hasDefaultArgument() &&
3016 "Parameter packs can't have a default argument!");
3017 if (!NewTemplateParm
->isPackExpansion())
3018 SawParameterPack
= true;
3019 } else if (OldTemplateParm
&&
3020 hasVisibleDefaultArgument(OldTemplateParm
) &&
3021 NewTemplateParm
->hasDefaultArgument() &&
3022 (!SkipBody
|| !SkipBody
->ShouldSkip
)) {
3023 OldDefaultLoc
= OldTemplateParm
->getDefaultArgument().getLocation();
3024 NewDefaultLoc
= NewTemplateParm
->getDefaultArgument().getLocation();
3025 SawDefaultArgument
= true;
3026 if (!OldTemplateParm
->getOwningModule())
3027 RedundantDefaultArg
= true;
3028 else if (!getASTContext().isSameDefaultTemplateArgument(
3029 OldTemplateParm
, NewTemplateParm
)) {
3030 InconsistentDefaultArg
= true;
3032 OldTemplateParm
->getImportedOwningModule()->getFullModuleName();
3034 PreviousDefaultArgLoc
= NewDefaultLoc
;
3035 } else if (OldTemplateParm
&& OldTemplateParm
->hasDefaultArgument()) {
3036 // Merge the default argument from the old declaration to the
3038 NewTemplateParm
->setInheritedDefaultArgument(Context
, OldTemplateParm
);
3039 PreviousDefaultArgLoc
3040 = OldTemplateParm
->getDefaultArgument().getLocation();
3041 } else if (NewTemplateParm
->hasDefaultArgument()) {
3042 SawDefaultArgument
= true;
3043 PreviousDefaultArgLoc
3044 = NewTemplateParm
->getDefaultArgument().getLocation();
3045 } else if (SawDefaultArgument
)
3046 MissingDefaultArg
= true;
3049 // C++11 [temp.param]p11:
3050 // If a template parameter of a primary class template or alias template
3051 // is a template parameter pack, it shall be the last template parameter.
3052 if (SawParameterPack
&& (NewParam
+ 1) != NewParamEnd
&&
3053 (TPC
== TPC_ClassTemplate
|| TPC
== TPC_VarTemplate
||
3054 TPC
== TPC_TypeAliasTemplate
)) {
3055 Diag((*NewParam
)->getLocation(),
3056 diag::err_template_param_pack_must_be_last_template_parameter
);
3060 // [basic.def.odr]/13:
3061 // There can be more than one definition of a
3063 // default template argument
3065 // in a program provided that each definition appears in a different
3066 // translation unit and the definitions satisfy the [same-meaning
3067 // criteria of the ODR].
3069 // Simply, the design of modules allows the definition of template default
3070 // argument to be repeated across translation unit. Note that the ODR is
3071 // checked elsewhere. But it is still not allowed to repeat template default
3072 // argument in the same translation unit.
3073 if (RedundantDefaultArg
) {
3074 Diag(NewDefaultLoc
, diag::err_template_param_default_arg_redefinition
);
3075 Diag(OldDefaultLoc
, diag::note_template_param_prev_default_arg
);
3077 } else if (InconsistentDefaultArg
) {
3078 // We could only diagnose about the case that the OldParam is imported.
3079 // The case NewParam is imported should be handled in ASTReader.
3081 diag::err_template_param_default_arg_inconsistent_redefinition
);
3083 diag::note_template_param_prev_default_arg_in_other_module
)
3086 } else if (MissingDefaultArg
&& TPC
!= TPC_FunctionTemplate
) {
3087 // C++ [temp.param]p11:
3088 // If a template-parameter of a class template has a default
3089 // template-argument, each subsequent template-parameter shall either
3090 // have a default template-argument supplied or be a template parameter
3092 Diag((*NewParam
)->getLocation(),
3093 diag::err_template_param_default_arg_missing
);
3094 Diag(PreviousDefaultArgLoc
, diag::note_template_param_prev_default_arg
);
3096 RemoveDefaultArguments
= true;
3099 // If we have an old template parameter list that we're merging
3100 // in, move on to the next parameter.
3105 // We were missing some default arguments at the end of the list, so remove
3106 // all of the default arguments.
3107 if (RemoveDefaultArguments
) {
3108 for (TemplateParameterList::iterator NewParam
= NewParams
->begin(),
3109 NewParamEnd
= NewParams
->end();
3110 NewParam
!= NewParamEnd
; ++NewParam
) {
3111 if (TemplateTypeParmDecl
*TTP
= dyn_cast
<TemplateTypeParmDecl
>(*NewParam
))
3112 TTP
->removeDefaultArgument();
3113 else if (NonTypeTemplateParmDecl
*NTTP
3114 = dyn_cast
<NonTypeTemplateParmDecl
>(*NewParam
))
3115 NTTP
->removeDefaultArgument();
3117 cast
<TemplateTemplateParmDecl
>(*NewParam
)->removeDefaultArgument();
3126 /// A class which looks for a use of a certain level of template
3128 struct DependencyChecker
: RecursiveASTVisitor
<DependencyChecker
> {
3129 typedef RecursiveASTVisitor
<DependencyChecker
> super
;
3133 // Whether we're looking for a use of a template parameter that makes the
3134 // overall construct type-dependent / a dependent type. This is strictly
3135 // best-effort for now; we may fail to match at all for a dependent type
3136 // in some cases if this is set.
3137 bool IgnoreNonTypeDependent
;
3140 SourceLocation MatchLoc
;
3142 DependencyChecker(unsigned Depth
, bool IgnoreNonTypeDependent
)
3143 : Depth(Depth
), IgnoreNonTypeDependent(IgnoreNonTypeDependent
),
3146 DependencyChecker(TemplateParameterList
*Params
, bool IgnoreNonTypeDependent
)
3147 : IgnoreNonTypeDependent(IgnoreNonTypeDependent
), Match(false) {
3148 NamedDecl
*ND
= Params
->getParam(0);
3149 if (TemplateTypeParmDecl
*PD
= dyn_cast
<TemplateTypeParmDecl
>(ND
)) {
3150 Depth
= PD
->getDepth();
3151 } else if (NonTypeTemplateParmDecl
*PD
=
3152 dyn_cast
<NonTypeTemplateParmDecl
>(ND
)) {
3153 Depth
= PD
->getDepth();
3155 Depth
= cast
<TemplateTemplateParmDecl
>(ND
)->getDepth();
3159 bool Matches(unsigned ParmDepth
, SourceLocation Loc
= SourceLocation()) {
3160 if (ParmDepth
>= Depth
) {
3168 bool TraverseStmt(Stmt
*S
, DataRecursionQueue
*Q
= nullptr) {
3169 // Prune out non-type-dependent expressions if requested. This can
3170 // sometimes result in us failing to find a template parameter reference
3171 // (if a value-dependent expression creates a dependent type), but this
3172 // mode is best-effort only.
3173 if (auto *E
= dyn_cast_or_null
<Expr
>(S
))
3174 if (IgnoreNonTypeDependent
&& !E
->isTypeDependent())
3176 return super::TraverseStmt(S
, Q
);
3179 bool TraverseTypeLoc(TypeLoc TL
) {
3180 if (IgnoreNonTypeDependent
&& !TL
.isNull() &&
3181 !TL
.getType()->isDependentType())
3183 return super::TraverseTypeLoc(TL
);
3186 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL
) {
3187 return !Matches(TL
.getTypePtr()->getDepth(), TL
.getNameLoc());
3190 bool VisitTemplateTypeParmType(const TemplateTypeParmType
*T
) {
3191 // For a best-effort search, keep looking until we find a location.
3192 return IgnoreNonTypeDependent
|| !Matches(T
->getDepth());
3195 bool TraverseTemplateName(TemplateName N
) {
3196 if (TemplateTemplateParmDecl
*PD
=
3197 dyn_cast_or_null
<TemplateTemplateParmDecl
>(N
.getAsTemplateDecl()))
3198 if (Matches(PD
->getDepth()))
3200 return super::TraverseTemplateName(N
);
3203 bool VisitDeclRefExpr(DeclRefExpr
*E
) {
3204 if (NonTypeTemplateParmDecl
*PD
=
3205 dyn_cast
<NonTypeTemplateParmDecl
>(E
->getDecl()))
3206 if (Matches(PD
->getDepth(), E
->getExprLoc()))
3208 return super::VisitDeclRefExpr(E
);
3211 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType
*T
) {
3212 return TraverseType(T
->getReplacementType());
3216 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType
*T
) {
3217 return TraverseTemplateArgument(T
->getArgumentPack());
3220 bool TraverseInjectedClassNameType(const InjectedClassNameType
*T
) {
3221 return TraverseType(T
->getInjectedSpecializationType());
3224 } // end anonymous namespace
3226 /// Determines whether a given type depends on the given parameter
3229 DependsOnTemplateParameters(QualType T
, TemplateParameterList
*Params
) {
3230 if (!Params
->size())
3233 DependencyChecker
Checker(Params
, /*IgnoreNonTypeDependent*/false);
3234 Checker
.TraverseType(T
);
3235 return Checker
.Match
;
3238 // Find the source range corresponding to the named type in the given
3239 // nested-name-specifier, if any.
3240 static SourceRange
getRangeOfTypeInNestedNameSpecifier(ASTContext
&Context
,
3242 const CXXScopeSpec
&SS
) {
3243 NestedNameSpecifierLoc
NNSLoc(SS
.getScopeRep(), SS
.location_data());
3244 while (NestedNameSpecifier
*NNS
= NNSLoc
.getNestedNameSpecifier()) {
3245 if (const Type
*CurType
= NNS
->getAsType()) {
3246 if (Context
.hasSameUnqualifiedType(T
, QualType(CurType
, 0)))
3247 return NNSLoc
.getTypeLoc().getSourceRange();
3251 NNSLoc
= NNSLoc
.getPrefix();
3254 return SourceRange();
3257 /// Match the given template parameter lists to the given scope
3258 /// specifier, returning the template parameter list that applies to the
3261 /// \param DeclStartLoc the start of the declaration that has a scope
3262 /// specifier or a template parameter list.
3264 /// \param DeclLoc The location of the declaration itself.
3266 /// \param SS the scope specifier that will be matched to the given template
3267 /// parameter lists. This scope specifier precedes a qualified name that is
3270 /// \param TemplateId The template-id following the scope specifier, if there
3271 /// is one. Used to check for a missing 'template<>'.
3273 /// \param ParamLists the template parameter lists, from the outermost to the
3274 /// innermost template parameter lists.
3276 /// \param IsFriend Whether to apply the slightly different rules for
3277 /// matching template parameters to scope specifiers in friend
3280 /// \param IsMemberSpecialization will be set true if the scope specifier
3281 /// denotes a fully-specialized type, and therefore this is a declaration of
3282 /// a member specialization.
3284 /// \returns the template parameter list, if any, that corresponds to the
3285 /// name that is preceded by the scope specifier @p SS. This template
3286 /// parameter list may have template parameters (if we're declaring a
3287 /// template) or may have no template parameters (if we're declaring a
3288 /// template specialization), or may be NULL (if what we're declaring isn't
3289 /// itself a template).
3290 TemplateParameterList
*Sema::MatchTemplateParametersToScopeSpecifier(
3291 SourceLocation DeclStartLoc
, SourceLocation DeclLoc
, const CXXScopeSpec
&SS
,
3292 TemplateIdAnnotation
*TemplateId
,
3293 ArrayRef
<TemplateParameterList
*> ParamLists
, bool IsFriend
,
3294 bool &IsMemberSpecialization
, bool &Invalid
, bool SuppressDiagnostic
) {
3295 IsMemberSpecialization
= false;
3298 // The sequence of nested types to which we will match up the template
3299 // parameter lists. We first build this list by starting with the type named
3300 // by the nested-name-specifier and walking out until we run out of types.
3301 SmallVector
<QualType
, 4> NestedTypes
;
3303 if (SS
.getScopeRep()) {
3304 if (CXXRecordDecl
*Record
3305 = dyn_cast_or_null
<CXXRecordDecl
>(computeDeclContext(SS
, true)))
3306 T
= Context
.getTypeDeclType(Record
);
3308 T
= QualType(SS
.getScopeRep()->getAsType(), 0);
3311 // If we found an explicit specialization that prevents us from needing
3312 // 'template<>' headers, this will be set to the location of that
3313 // explicit specialization.
3314 SourceLocation ExplicitSpecLoc
;
3316 while (!T
.isNull()) {
3317 NestedTypes
.push_back(T
);
3319 // Retrieve the parent of a record type.
3320 if (CXXRecordDecl
*Record
= T
->getAsCXXRecordDecl()) {
3321 // If this type is an explicit specialization, we're done.
3322 if (ClassTemplateSpecializationDecl
*Spec
3323 = dyn_cast
<ClassTemplateSpecializationDecl
>(Record
)) {
3324 if (!isa
<ClassTemplatePartialSpecializationDecl
>(Spec
) &&
3325 Spec
->getSpecializationKind() == TSK_ExplicitSpecialization
) {
3326 ExplicitSpecLoc
= Spec
->getLocation();
3329 } else if (Record
->getTemplateSpecializationKind()
3330 == TSK_ExplicitSpecialization
) {
3331 ExplicitSpecLoc
= Record
->getLocation();
3335 if (TypeDecl
*Parent
= dyn_cast
<TypeDecl
>(Record
->getParent()))
3336 T
= Context
.getTypeDeclType(Parent
);
3342 if (const TemplateSpecializationType
*TST
3343 = T
->getAs
<TemplateSpecializationType
>()) {
3344 if (TemplateDecl
*Template
= TST
->getTemplateName().getAsTemplateDecl()) {
3345 if (TypeDecl
*Parent
= dyn_cast
<TypeDecl
>(Template
->getDeclContext()))
3346 T
= Context
.getTypeDeclType(Parent
);
3353 // Look one step prior in a dependent template specialization type.
3354 if (const DependentTemplateSpecializationType
*DependentTST
3355 = T
->getAs
<DependentTemplateSpecializationType
>()) {
3356 if (NestedNameSpecifier
*NNS
= DependentTST
->getQualifier())
3357 T
= QualType(NNS
->getAsType(), 0);
3363 // Look one step prior in a dependent name type.
3364 if (const DependentNameType
*DependentName
= T
->getAs
<DependentNameType
>()){
3365 if (NestedNameSpecifier
*NNS
= DependentName
->getQualifier())
3366 T
= QualType(NNS
->getAsType(), 0);
3372 // Retrieve the parent of an enumeration type.
3373 if (const EnumType
*EnumT
= T
->getAs
<EnumType
>()) {
3374 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
3376 EnumDecl
*Enum
= EnumT
->getDecl();
3378 // Get to the parent type.
3379 if (TypeDecl
*Parent
= dyn_cast
<TypeDecl
>(Enum
->getParent()))
3380 T
= Context
.getTypeDeclType(Parent
);
3388 // Reverse the nested types list, since we want to traverse from the outermost
3389 // to the innermost while checking template-parameter-lists.
3390 std::reverse(NestedTypes
.begin(), NestedTypes
.end());
3392 // C++0x [temp.expl.spec]p17:
3393 // A member or a member template may be nested within many
3394 // enclosing class templates. In an explicit specialization for
3395 // such a member, the member declaration shall be preceded by a
3396 // template<> for each enclosing class template that is
3397 // explicitly specialized.
3398 bool SawNonEmptyTemplateParameterList
= false;
3400 auto CheckExplicitSpecialization
= [&](SourceRange Range
, bool Recovery
) {
3401 if (SawNonEmptyTemplateParameterList
) {
3402 if (!SuppressDiagnostic
)
3403 Diag(DeclLoc
, diag::err_specialize_member_of_template
)
3404 << !Recovery
<< Range
;
3406 IsMemberSpecialization
= false;
3413 auto DiagnoseMissingExplicitSpecialization
= [&] (SourceRange Range
) {
3414 // Check that we can have an explicit specialization here.
3415 if (CheckExplicitSpecialization(Range
, true))
3418 // We don't have a template header, but we should.
3419 SourceLocation ExpectedTemplateLoc
;
3420 if (!ParamLists
.empty())
3421 ExpectedTemplateLoc
= ParamLists
[0]->getTemplateLoc();
3423 ExpectedTemplateLoc
= DeclStartLoc
;
3425 if (!SuppressDiagnostic
)
3426 Diag(DeclLoc
, diag::err_template_spec_needs_header
)
3428 << FixItHint::CreateInsertion(ExpectedTemplateLoc
, "template<> ");
3432 unsigned ParamIdx
= 0;
3433 for (unsigned TypeIdx
= 0, NumTypes
= NestedTypes
.size(); TypeIdx
!= NumTypes
;
3435 T
= NestedTypes
[TypeIdx
];
3437 // Whether we expect a 'template<>' header.
3438 bool NeedEmptyTemplateHeader
= false;
3440 // Whether we expect a template header with parameters.
3441 bool NeedNonemptyTemplateHeader
= false;
3443 // For a dependent type, the set of template parameters that we
3445 TemplateParameterList
*ExpectedTemplateParams
= nullptr;
3447 // C++0x [temp.expl.spec]p15:
3448 // A member or a member template may be nested within many enclosing
3449 // class templates. In an explicit specialization for such a member, the
3450 // member declaration shall be preceded by a template<> for each
3451 // enclosing class template that is explicitly specialized.
3452 if (CXXRecordDecl
*Record
= T
->getAsCXXRecordDecl()) {
3453 if (ClassTemplatePartialSpecializationDecl
*Partial
3454 = dyn_cast
<ClassTemplatePartialSpecializationDecl
>(Record
)) {
3455 ExpectedTemplateParams
= Partial
->getTemplateParameters();
3456 NeedNonemptyTemplateHeader
= true;
3457 } else if (Record
->isDependentType()) {
3458 if (Record
->getDescribedClassTemplate()) {
3459 ExpectedTemplateParams
= Record
->getDescribedClassTemplate()
3460 ->getTemplateParameters();
3461 NeedNonemptyTemplateHeader
= true;
3463 } else if (ClassTemplateSpecializationDecl
*Spec
3464 = dyn_cast
<ClassTemplateSpecializationDecl
>(Record
)) {
3465 // C++0x [temp.expl.spec]p4:
3466 // Members of an explicitly specialized class template are defined
3467 // in the same manner as members of normal classes, and not using
3468 // the template<> syntax.
3469 if (Spec
->getSpecializationKind() != TSK_ExplicitSpecialization
)
3470 NeedEmptyTemplateHeader
= true;
3473 } else if (Record
->getTemplateSpecializationKind()) {
3474 if (Record
->getTemplateSpecializationKind()
3475 != TSK_ExplicitSpecialization
&&
3476 TypeIdx
== NumTypes
- 1)
3477 IsMemberSpecialization
= true;
3481 } else if (const TemplateSpecializationType
*TST
3482 = T
->getAs
<TemplateSpecializationType
>()) {
3483 if (TemplateDecl
*Template
= TST
->getTemplateName().getAsTemplateDecl()) {
3484 ExpectedTemplateParams
= Template
->getTemplateParameters();
3485 NeedNonemptyTemplateHeader
= true;
3487 } else if (T
->getAs
<DependentTemplateSpecializationType
>()) {
3488 // FIXME: We actually could/should check the template arguments here
3489 // against the corresponding template parameter list.
3490 NeedNonemptyTemplateHeader
= false;
3493 // C++ [temp.expl.spec]p16:
3494 // In an explicit specialization declaration for a member of a class
3495 // template or a member template that ap- pears in namespace scope, the
3496 // member template and some of its enclosing class templates may remain
3497 // unspecialized, except that the declaration shall not explicitly
3498 // specialize a class member template if its en- closing class templates
3499 // are not explicitly specialized as well.
3500 if (ParamIdx
< ParamLists
.size()) {
3501 if (ParamLists
[ParamIdx
]->size() == 0) {
3502 if (CheckExplicitSpecialization(ParamLists
[ParamIdx
]->getSourceRange(),
3506 SawNonEmptyTemplateParameterList
= true;
3509 if (NeedEmptyTemplateHeader
) {
3510 // If we're on the last of the types, and we need a 'template<>' header
3511 // here, then it's a member specialization.
3512 if (TypeIdx
== NumTypes
- 1)
3513 IsMemberSpecialization
= true;
3515 if (ParamIdx
< ParamLists
.size()) {
3516 if (ParamLists
[ParamIdx
]->size() > 0) {
3517 // The header has template parameters when it shouldn't. Complain.
3518 if (!SuppressDiagnostic
)
3519 Diag(ParamLists
[ParamIdx
]->getTemplateLoc(),
3520 diag::err_template_param_list_matches_nontemplate
)
3522 << SourceRange(ParamLists
[ParamIdx
]->getLAngleLoc(),
3523 ParamLists
[ParamIdx
]->getRAngleLoc())
3524 << getRangeOfTypeInNestedNameSpecifier(Context
, T
, SS
);
3529 // Consume this template header.
3535 if (DiagnoseMissingExplicitSpecialization(
3536 getRangeOfTypeInNestedNameSpecifier(Context
, T
, SS
)))
3542 if (NeedNonemptyTemplateHeader
) {
3543 // In friend declarations we can have template-ids which don't
3544 // depend on the corresponding template parameter lists. But
3545 // assume that empty parameter lists are supposed to match this
3547 if (IsFriend
&& T
->isDependentType()) {
3548 if (ParamIdx
< ParamLists
.size() &&
3549 DependsOnTemplateParameters(T
, ParamLists
[ParamIdx
]))
3550 ExpectedTemplateParams
= nullptr;
3555 if (ParamIdx
< ParamLists
.size()) {
3556 // Check the template parameter list, if we can.
3557 if (ExpectedTemplateParams
&&
3558 !TemplateParameterListsAreEqual(ParamLists
[ParamIdx
],
3559 ExpectedTemplateParams
,
3560 !SuppressDiagnostic
, TPL_TemplateMatch
))
3564 CheckTemplateParameterList(ParamLists
[ParamIdx
], nullptr,
3565 TPC_ClassTemplateMember
))
3572 if (!SuppressDiagnostic
)
3573 Diag(DeclLoc
, diag::err_template_spec_needs_template_parameters
)
3575 << getRangeOfTypeInNestedNameSpecifier(Context
, T
, SS
);
3581 // If there were at least as many template-ids as there were template
3582 // parameter lists, then there are no template parameter lists remaining for
3583 // the declaration itself.
3584 if (ParamIdx
>= ParamLists
.size()) {
3585 if (TemplateId
&& !IsFriend
) {
3586 // We don't have a template header for the declaration itself, but we
3588 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId
->LAngleLoc
,
3589 TemplateId
->RAngleLoc
));
3591 // Fabricate an empty template parameter list for the invented header.
3592 return TemplateParameterList::Create(Context
, SourceLocation(),
3593 SourceLocation(), std::nullopt
,
3594 SourceLocation(), nullptr);
3600 // If there were too many template parameter lists, complain about that now.
3601 if (ParamIdx
< ParamLists
.size() - 1) {
3602 bool HasAnyExplicitSpecHeader
= false;
3603 bool AllExplicitSpecHeaders
= true;
3604 for (unsigned I
= ParamIdx
, E
= ParamLists
.size() - 1; I
!= E
; ++I
) {
3605 if (ParamLists
[I
]->size() == 0)
3606 HasAnyExplicitSpecHeader
= true;
3608 AllExplicitSpecHeaders
= false;
3611 if (!SuppressDiagnostic
)
3612 Diag(ParamLists
[ParamIdx
]->getTemplateLoc(),
3613 AllExplicitSpecHeaders
? diag::warn_template_spec_extra_headers
3614 : diag::err_template_spec_extra_headers
)
3615 << SourceRange(ParamLists
[ParamIdx
]->getTemplateLoc(),
3616 ParamLists
[ParamLists
.size() - 2]->getRAngleLoc());
3618 // If there was a specialization somewhere, such that 'template<>' is
3619 // not required, and there were any 'template<>' headers, note where the
3620 // specialization occurred.
3621 if (ExplicitSpecLoc
.isValid() && HasAnyExplicitSpecHeader
&&
3622 !SuppressDiagnostic
)
3623 Diag(ExplicitSpecLoc
,
3624 diag::note_explicit_template_spec_does_not_need_header
)
3625 << NestedTypes
.back();
3627 // We have a template parameter list with no corresponding scope, which
3628 // means that the resulting template declaration can't be instantiated
3629 // properly (we'll end up with dependent nodes when we shouldn't).
3630 if (!AllExplicitSpecHeaders
)
3634 // C++ [temp.expl.spec]p16:
3635 // In an explicit specialization declaration for a member of a class
3636 // template or a member template that ap- pears in namespace scope, the
3637 // member template and some of its enclosing class templates may remain
3638 // unspecialized, except that the declaration shall not explicitly
3639 // specialize a class member template if its en- closing class templates
3640 // are not explicitly specialized as well.
3641 if (ParamLists
.back()->size() == 0 &&
3642 CheckExplicitSpecialization(ParamLists
[ParamIdx
]->getSourceRange(),
3646 // Return the last template parameter list, which corresponds to the
3647 // entity being declared.
3648 return ParamLists
.back();
3651 void Sema::NoteAllFoundTemplates(TemplateName Name
) {
3652 if (TemplateDecl
*Template
= Name
.getAsTemplateDecl()) {
3653 Diag(Template
->getLocation(), diag::note_template_declared_here
)
3654 << (isa
<FunctionTemplateDecl
>(Template
)
3656 : isa
<ClassTemplateDecl
>(Template
)
3658 : isa
<VarTemplateDecl
>(Template
)
3660 : isa
<TypeAliasTemplateDecl
>(Template
) ? 3 : 4)
3661 << Template
->getDeclName();
3665 if (OverloadedTemplateStorage
*OST
= Name
.getAsOverloadedTemplate()) {
3666 for (OverloadedTemplateStorage::iterator I
= OST
->begin(),
3669 Diag((*I
)->getLocation(), diag::note_template_declared_here
)
3670 << 0 << (*I
)->getDeclName();
3677 checkBuiltinTemplateIdType(Sema
&SemaRef
, BuiltinTemplateDecl
*BTD
,
3678 ArrayRef
<TemplateArgument
> Converted
,
3679 SourceLocation TemplateLoc
,
3680 TemplateArgumentListInfo
&TemplateArgs
) {
3681 ASTContext
&Context
= SemaRef
.getASTContext();
3683 switch (BTD
->getBuiltinTemplateKind()) {
3684 case BTK__make_integer_seq
: {
3685 // Specializations of __make_integer_seq<S, T, N> are treated like
3686 // S<T, 0, ..., N-1>.
3688 QualType OrigType
= Converted
[1].getAsType();
3689 // C++14 [inteseq.intseq]p1:
3690 // T shall be an integer type.
3691 if (!OrigType
->isDependentType() && !OrigType
->isIntegralType(Context
)) {
3692 SemaRef
.Diag(TemplateArgs
[1].getLocation(),
3693 diag::err_integer_sequence_integral_element_type
);
3697 TemplateArgument NumArgsArg
= Converted
[2];
3698 if (NumArgsArg
.isDependent())
3699 return Context
.getCanonicalTemplateSpecializationType(TemplateName(BTD
),
3702 TemplateArgumentListInfo SyntheticTemplateArgs
;
3703 // The type argument, wrapped in substitution sugar, gets reused as the
3704 // first template argument in the synthetic template argument list.
3705 SyntheticTemplateArgs
.addArgument(
3706 TemplateArgumentLoc(TemplateArgument(OrigType
),
3707 SemaRef
.Context
.getTrivialTypeSourceInfo(
3708 OrigType
, TemplateArgs
[1].getLocation())));
3710 if (llvm::APSInt NumArgs
= NumArgsArg
.getAsIntegral(); NumArgs
>= 0) {
3711 // Expand N into 0 ... N-1.
3712 for (llvm::APSInt
I(NumArgs
.getBitWidth(), NumArgs
.isUnsigned());
3714 TemplateArgument
TA(Context
, I
, OrigType
);
3715 SyntheticTemplateArgs
.addArgument(SemaRef
.getTrivialTemplateArgumentLoc(
3716 TA
, OrigType
, TemplateArgs
[2].getLocation()));
3719 // C++14 [inteseq.make]p1:
3720 // If N is negative the program is ill-formed.
3721 SemaRef
.Diag(TemplateArgs
[2].getLocation(),
3722 diag::err_integer_sequence_negative_length
);
3726 // The first template argument will be reused as the template decl that
3727 // our synthetic template arguments will be applied to.
3728 return SemaRef
.CheckTemplateIdType(Converted
[0].getAsTemplate(),
3729 TemplateLoc
, SyntheticTemplateArgs
);
3732 case BTK__type_pack_element
:
3733 // Specializations of
3734 // __type_pack_element<Index, T_1, ..., T_N>
3735 // are treated like T_Index.
3736 assert(Converted
.size() == 2 &&
3737 "__type_pack_element should be given an index and a parameter pack");
3739 TemplateArgument IndexArg
= Converted
[0], Ts
= Converted
[1];
3740 if (IndexArg
.isDependent() || Ts
.isDependent())
3741 return Context
.getCanonicalTemplateSpecializationType(TemplateName(BTD
),
3744 llvm::APSInt Index
= IndexArg
.getAsIntegral();
3745 assert(Index
>= 0 && "the index used with __type_pack_element should be of "
3746 "type std::size_t, and hence be non-negative");
3747 // If the Index is out of bounds, the program is ill-formed.
3748 if (Index
>= Ts
.pack_size()) {
3749 SemaRef
.Diag(TemplateArgs
[0].getLocation(),
3750 diag::err_type_pack_element_out_of_bounds
);
3754 // We simply return the type at index `Index`.
3755 int64_t N
= Index
.getExtValue();
3756 return Ts
.getPackAsArray()[N
].getAsType();
3758 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3761 /// Determine whether this alias template is "enable_if_t".
3762 /// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3763 static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl
*AliasTemplate
) {
3764 return AliasTemplate
->getName().equals("enable_if_t") ||
3765 AliasTemplate
->getName().equals("__enable_if_t");
3768 /// Collect all of the separable terms in the given condition, which
3769 /// might be a conjunction.
3771 /// FIXME: The right answer is to convert the logical expression into
3772 /// disjunctive normal form, so we can find the first failed term
3773 /// within each possible clause.
3774 static void collectConjunctionTerms(Expr
*Clause
,
3775 SmallVectorImpl
<Expr
*> &Terms
) {
3776 if (auto BinOp
= dyn_cast
<BinaryOperator
>(Clause
->IgnoreParenImpCasts())) {
3777 if (BinOp
->getOpcode() == BO_LAnd
) {
3778 collectConjunctionTerms(BinOp
->getLHS(), Terms
);
3779 collectConjunctionTerms(BinOp
->getRHS(), Terms
);
3784 Terms
.push_back(Clause
);
3787 // The ranges-v3 library uses an odd pattern of a top-level "||" with
3788 // a left-hand side that is value-dependent but never true. Identify
3789 // the idiom and ignore that term.
3790 static Expr
*lookThroughRangesV3Condition(Preprocessor
&PP
, Expr
*Cond
) {
3792 auto *BinOp
= dyn_cast
<BinaryOperator
>(Cond
->IgnoreParenImpCasts());
3793 if (!BinOp
) return Cond
;
3795 if (BinOp
->getOpcode() != BO_LOr
) return Cond
;
3797 // With an inner '==' that has a literal on the right-hand side.
3798 Expr
*LHS
= BinOp
->getLHS();
3799 auto *InnerBinOp
= dyn_cast
<BinaryOperator
>(LHS
->IgnoreParenImpCasts());
3800 if (!InnerBinOp
) return Cond
;
3802 if (InnerBinOp
->getOpcode() != BO_EQ
||
3803 !isa
<IntegerLiteral
>(InnerBinOp
->getRHS()))
3806 // If the inner binary operation came from a macro expansion named
3807 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3808 // of the '||', which is the real, user-provided condition.
3809 SourceLocation Loc
= InnerBinOp
->getExprLoc();
3810 if (!Loc
.isMacroID()) return Cond
;
3812 StringRef MacroName
= PP
.getImmediateMacroName(Loc
);
3813 if (MacroName
== "CONCEPT_REQUIRES" || MacroName
== "CONCEPT_REQUIRES_")
3814 return BinOp
->getRHS();
3821 // A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3822 // within failing boolean expression, such as substituting template parameters
3823 // for actual types.
3824 class FailedBooleanConditionPrinterHelper
: public PrinterHelper
{
3826 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy
&P
)
3829 bool handledStmt(Stmt
*E
, raw_ostream
&OS
) override
{
3830 const auto *DR
= dyn_cast
<DeclRefExpr
>(E
);
3831 if (DR
&& DR
->getQualifier()) {
3832 // If this is a qualified name, expand the template arguments in nested
3834 DR
->getQualifier()->print(OS
, Policy
, true);
3835 // Then print the decl itself.
3836 const ValueDecl
*VD
= DR
->getDecl();
3837 OS
<< VD
->getName();
3838 if (const auto *IV
= dyn_cast
<VarTemplateSpecializationDecl
>(VD
)) {
3839 // This is a template variable, print the expanded template arguments.
3840 printTemplateArgumentList(
3841 OS
, IV
->getTemplateArgs().asArray(), Policy
,
3842 IV
->getSpecializedTemplate()->getTemplateParameters());
3850 const PrintingPolicy Policy
;
3853 } // end anonymous namespace
3855 std::pair
<Expr
*, std::string
>
3856 Sema::findFailedBooleanCondition(Expr
*Cond
) {
3857 Cond
= lookThroughRangesV3Condition(PP
, Cond
);
3859 // Separate out all of the terms in a conjunction.
3860 SmallVector
<Expr
*, 4> Terms
;
3861 collectConjunctionTerms(Cond
, Terms
);
3863 // Determine which term failed.
3864 Expr
*FailedCond
= nullptr;
3865 for (Expr
*Term
: Terms
) {
3866 Expr
*TermAsWritten
= Term
->IgnoreParenImpCasts();
3868 // Literals are uninteresting.
3869 if (isa
<CXXBoolLiteralExpr
>(TermAsWritten
) ||
3870 isa
<IntegerLiteral
>(TermAsWritten
))
3873 // The initialization of the parameter from the argument is
3874 // a constant-evaluated context.
3875 EnterExpressionEvaluationContext
ConstantEvaluated(
3876 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated
);
3879 if (Term
->EvaluateAsBooleanCondition(Succeeded
, Context
) &&
3881 FailedCond
= TermAsWritten
;
3886 FailedCond
= Cond
->IgnoreParenImpCasts();
3888 std::string Description
;
3890 llvm::raw_string_ostream
Out(Description
);
3891 PrintingPolicy Policy
= getPrintingPolicy();
3892 Policy
.PrintCanonicalTypes
= true;
3893 FailedBooleanConditionPrinterHelper
Helper(Policy
);
3894 FailedCond
->printPretty(Out
, &Helper
, Policy
, 0, "\n", nullptr);
3896 return { FailedCond
, Description
};
3899 QualType
Sema::CheckTemplateIdType(TemplateName Name
,
3900 SourceLocation TemplateLoc
,
3901 TemplateArgumentListInfo
&TemplateArgs
) {
3902 DependentTemplateName
*DTN
3903 = Name
.getUnderlying().getAsDependentTemplateName();
3904 if (DTN
&& DTN
->isIdentifier())
3905 // When building a template-id where the template-name is dependent,
3906 // assume the template is a type template. Either our assumption is
3907 // correct, or the code is ill-formed and will be diagnosed when the
3908 // dependent name is substituted.
3909 return Context
.getDependentTemplateSpecializationType(
3910 ElaboratedTypeKeyword::None
, DTN
->getQualifier(), DTN
->getIdentifier(),
3911 TemplateArgs
.arguments());
3913 if (Name
.getAsAssumedTemplateName() &&
3914 resolveAssumedTemplateNameAsType(/*Scope*/nullptr, Name
, TemplateLoc
))
3917 TemplateDecl
*Template
= Name
.getAsTemplateDecl();
3918 if (!Template
|| isa
<FunctionTemplateDecl
>(Template
) ||
3919 isa
<VarTemplateDecl
>(Template
) || isa
<ConceptDecl
>(Template
)) {
3920 // We might have a substituted template template parameter pack. If so,
3921 // build a template specialization type for it.
3922 if (Name
.getAsSubstTemplateTemplateParmPack())
3923 return Context
.getTemplateSpecializationType(Name
,
3924 TemplateArgs
.arguments());
3926 Diag(TemplateLoc
, diag::err_template_id_not_a_type
)
3928 NoteAllFoundTemplates(Name
);
3932 // Check that the template argument list is well-formed for this
3934 SmallVector
<TemplateArgument
, 4> SugaredConverted
, CanonicalConverted
;
3935 if (CheckTemplateArgumentList(Template
, TemplateLoc
, TemplateArgs
, false,
3936 SugaredConverted
, CanonicalConverted
,
3937 /*UpdateArgsWithConversions=*/true))
3942 if (TypeAliasTemplateDecl
*AliasTemplate
=
3943 dyn_cast
<TypeAliasTemplateDecl
>(Template
)) {
3945 // Find the canonical type for this type alias template specialization.
3946 TypeAliasDecl
*Pattern
= AliasTemplate
->getTemplatedDecl();
3947 if (Pattern
->isInvalidDecl())
3950 // Only substitute for the innermost template argument list.
3951 MultiLevelTemplateArgumentList TemplateArgLists
;
3952 TemplateArgLists
.addOuterTemplateArguments(Template
, CanonicalConverted
,
3954 TemplateArgLists
.addOuterRetainedLevels(
3955 AliasTemplate
->getTemplateParameters()->getDepth());
3957 LocalInstantiationScope
Scope(*this);
3958 InstantiatingTemplate
Inst(*this, TemplateLoc
, Template
);
3959 if (Inst
.isInvalid())
3962 CanonType
= SubstType(Pattern
->getUnderlyingType(),
3963 TemplateArgLists
, AliasTemplate
->getLocation(),
3964 AliasTemplate
->getDeclName());
3965 if (CanonType
.isNull()) {
3966 // If this was enable_if and we failed to find the nested type
3967 // within enable_if in a SFINAE context, dig out the specific
3968 // enable_if condition that failed and present that instead.
3969 if (isEnableIfAliasTemplate(AliasTemplate
)) {
3970 if (auto DeductionInfo
= isSFINAEContext()) {
3971 if (*DeductionInfo
&&
3972 (*DeductionInfo
)->hasSFINAEDiagnostic() &&
3973 (*DeductionInfo
)->peekSFINAEDiagnostic().second
.getDiagID() ==
3974 diag::err_typename_nested_not_found_enable_if
&&
3975 TemplateArgs
[0].getArgument().getKind()
3976 == TemplateArgument::Expression
) {
3978 std::string FailedDescription
;
3979 std::tie(FailedCond
, FailedDescription
) =
3980 findFailedBooleanCondition(TemplateArgs
[0].getSourceExpression());
3982 // Remove the old SFINAE diagnostic.
3983 PartialDiagnosticAt OldDiag
=
3984 {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3985 (*DeductionInfo
)->takeSFINAEDiagnostic(OldDiag
);
3987 // Add a new SFINAE diagnostic specifying which condition
3989 (*DeductionInfo
)->addSFINAEDiagnostic(
3991 PDiag(diag::err_typename_nested_not_found_requirement
)
3992 << FailedDescription
3993 << FailedCond
->getSourceRange());
4000 } else if (auto *BTD
= dyn_cast
<BuiltinTemplateDecl
>(Template
)) {
4001 CanonType
= checkBuiltinTemplateIdType(*this, BTD
, SugaredConverted
,
4002 TemplateLoc
, TemplateArgs
);
4003 } else if (Name
.isDependent() ||
4004 TemplateSpecializationType::anyDependentTemplateArguments(
4005 TemplateArgs
, CanonicalConverted
)) {
4006 // This class template specialization is a dependent
4007 // type. Therefore, its canonical type is another class template
4008 // specialization type that contains all of the converted
4009 // arguments in canonical form. This ensures that, e.g., A<T> and
4010 // A<T, T> have identical types when A is declared as:
4012 // template<typename T, typename U = T> struct A;
4013 CanonType
= Context
.getCanonicalTemplateSpecializationType(
4014 Name
, CanonicalConverted
);
4016 // This might work out to be a current instantiation, in which
4017 // case the canonical type needs to be the InjectedClassNameType.
4019 // TODO: in theory this could be a simple hashtable lookup; most
4020 // changes to CurContext don't change the set of current
4022 if (isa
<ClassTemplateDecl
>(Template
)) {
4023 for (DeclContext
*Ctx
= CurContext
; Ctx
; Ctx
= Ctx
->getLookupParent()) {
4024 // If we get out to a namespace, we're done.
4025 if (Ctx
->isFileContext()) break;
4027 // If this isn't a record, keep looking.
4028 CXXRecordDecl
*Record
= dyn_cast
<CXXRecordDecl
>(Ctx
);
4029 if (!Record
) continue;
4031 // Look for one of the two cases with InjectedClassNameTypes
4032 // and check whether it's the same template.
4033 if (!isa
<ClassTemplatePartialSpecializationDecl
>(Record
) &&
4034 !Record
->getDescribedClassTemplate())
4037 // Fetch the injected class name type and check whether its
4038 // injected type is equal to the type we just built.
4039 QualType ICNT
= Context
.getTypeDeclType(Record
);
4040 QualType Injected
= cast
<InjectedClassNameType
>(ICNT
)
4041 ->getInjectedSpecializationType();
4043 if (CanonType
!= Injected
->getCanonicalTypeInternal())
4046 // If so, the canonical type of this TST is the injected
4047 // class name type of the record we just found.
4048 assert(ICNT
.isCanonical());
4053 } else if (ClassTemplateDecl
*ClassTemplate
=
4054 dyn_cast
<ClassTemplateDecl
>(Template
)) {
4055 // Find the class template specialization declaration that
4056 // corresponds to these arguments.
4057 void *InsertPos
= nullptr;
4058 ClassTemplateSpecializationDecl
*Decl
=
4059 ClassTemplate
->findSpecialization(CanonicalConverted
, InsertPos
);
4061 // This is the first time we have referenced this class template
4062 // specialization. Create the canonical declaration and add it to
4063 // the set of specializations.
4064 Decl
= ClassTemplateSpecializationDecl::Create(
4065 Context
, ClassTemplate
->getTemplatedDecl()->getTagKind(),
4066 ClassTemplate
->getDeclContext(),
4067 ClassTemplate
->getTemplatedDecl()->getBeginLoc(),
4068 ClassTemplate
->getLocation(), ClassTemplate
, CanonicalConverted
,
4070 ClassTemplate
->AddSpecialization(Decl
, InsertPos
);
4071 if (ClassTemplate
->isOutOfLine())
4072 Decl
->setLexicalDeclContext(ClassTemplate
->getLexicalDeclContext());
4075 if (Decl
->getSpecializationKind() == TSK_Undeclared
&&
4076 ClassTemplate
->getTemplatedDecl()->hasAttrs()) {
4077 InstantiatingTemplate
Inst(*this, TemplateLoc
, Decl
);
4078 if (!Inst
.isInvalid()) {
4079 MultiLevelTemplateArgumentList
TemplateArgLists(Template
,
4082 InstantiateAttrsForDecl(TemplateArgLists
,
4083 ClassTemplate
->getTemplatedDecl(), Decl
);
4087 // Diagnose uses of this specialization.
4088 (void)DiagnoseUseOfDecl(Decl
, TemplateLoc
);
4090 CanonType
= Context
.getTypeDeclType(Decl
);
4091 assert(isa
<RecordType
>(CanonType
) &&
4092 "type of non-dependent specialization is not a RecordType");
4094 llvm_unreachable("Unhandled template kind");
4097 // Build the fully-sugared type for this class template
4098 // specialization, which refers back to the class template
4099 // specialization we created or found.
4100 return Context
.getTemplateSpecializationType(Name
, TemplateArgs
.arguments(),
4104 void Sema::ActOnUndeclaredTypeTemplateName(Scope
*S
, TemplateTy
&ParsedName
,
4105 TemplateNameKind
&TNK
,
4106 SourceLocation NameLoc
,
4107 IdentifierInfo
*&II
) {
4108 assert(TNK
== TNK_Undeclared_template
&& "not an undeclared template name");
4110 TemplateName Name
= ParsedName
.get();
4111 auto *ATN
= Name
.getAsAssumedTemplateName();
4112 assert(ATN
&& "not an assumed template name");
4113 II
= ATN
->getDeclName().getAsIdentifierInfo();
4115 if (!resolveAssumedTemplateNameAsType(S
, Name
, NameLoc
, /*Diagnose*/false)) {
4116 // Resolved to a type template name.
4117 ParsedName
= TemplateTy::make(Name
);
4118 TNK
= TNK_Type_template
;
4122 bool Sema::resolveAssumedTemplateNameAsType(Scope
*S
, TemplateName
&Name
,
4123 SourceLocation NameLoc
,
4125 // We assumed this undeclared identifier to be an (ADL-only) function
4126 // template name, but it was used in a context where a type was required.
4127 // Try to typo-correct it now.
4128 AssumedTemplateStorage
*ATN
= Name
.getAsAssumedTemplateName();
4129 assert(ATN
&& "not an assumed template name");
4131 LookupResult
R(*this, ATN
->getDeclName(), NameLoc
, LookupOrdinaryName
);
4132 struct CandidateCallback
: CorrectionCandidateCallback
{
4133 bool ValidateCandidate(const TypoCorrection
&TC
) override
{
4134 return TC
.getCorrectionDecl() &&
4135 getAsTypeTemplateDecl(TC
.getCorrectionDecl());
4137 std::unique_ptr
<CorrectionCandidateCallback
> clone() override
{
4138 return std::make_unique
<CandidateCallback
>(*this);
4142 TypoCorrection Corrected
=
4143 CorrectTypo(R
.getLookupNameInfo(), R
.getLookupKind(), S
, nullptr,
4144 FilterCCC
, CTK_ErrorRecovery
);
4145 if (Corrected
&& Corrected
.getFoundDecl()) {
4146 diagnoseTypo(Corrected
, PDiag(diag::err_no_template_suggest
)
4147 << ATN
->getDeclName());
4148 Name
= TemplateName(Corrected
.getCorrectionDeclAs
<TemplateDecl
>());
4153 Diag(R
.getNameLoc(), diag::err_no_template
) << R
.getLookupName();
4157 TypeResult
Sema::ActOnTemplateIdType(
4158 Scope
*S
, CXXScopeSpec
&SS
, SourceLocation TemplateKWLoc
,
4159 TemplateTy TemplateD
, IdentifierInfo
*TemplateII
,
4160 SourceLocation TemplateIILoc
, SourceLocation LAngleLoc
,
4161 ASTTemplateArgsPtr TemplateArgsIn
, SourceLocation RAngleLoc
,
4162 bool IsCtorOrDtorName
, bool IsClassName
,
4163 ImplicitTypenameContext AllowImplicitTypename
) {
4167 if (!IsCtorOrDtorName
&& !IsClassName
&& SS
.isSet()) {
4168 DeclContext
*LookupCtx
= computeDeclContext(SS
, /*EnteringContext*/false);
4170 // C++ [temp.res]p3:
4171 // A qualified-id that refers to a type and in which the
4172 // nested-name-specifier depends on a template-parameter (14.6.2)
4173 // shall be prefixed by the keyword typename to indicate that the
4174 // qualified-id denotes a type, forming an
4175 // elaborated-type-specifier (7.1.5.3).
4176 if (!LookupCtx
&& isDependentScopeSpecifier(SS
)) {
4177 // C++2a relaxes some of those restrictions in [temp.res]p5.
4178 if (AllowImplicitTypename
== ImplicitTypenameContext::Yes
) {
4179 if (getLangOpts().CPlusPlus20
)
4180 Diag(SS
.getBeginLoc(), diag::warn_cxx17_compat_implicit_typename
);
4182 Diag(SS
.getBeginLoc(), diag::ext_implicit_typename
)
4183 << SS
.getScopeRep() << TemplateII
->getName()
4184 << FixItHint::CreateInsertion(SS
.getBeginLoc(), "typename ");
4186 Diag(SS
.getBeginLoc(), diag::err_typename_missing_template
)
4187 << SS
.getScopeRep() << TemplateII
->getName();
4189 // FIXME: This is not quite correct recovery as we don't transform SS
4190 // into the corresponding dependent form (and we don't diagnose missing
4191 // 'template' keywords within SS as a result).
4192 return ActOnTypenameType(nullptr, SourceLocation(), SS
, TemplateKWLoc
,
4193 TemplateD
, TemplateII
, TemplateIILoc
, LAngleLoc
,
4194 TemplateArgsIn
, RAngleLoc
);
4197 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
4198 // it's not actually allowed to be used as a type in most cases. Because
4199 // we annotate it before we know whether it's valid, we have to check for
4201 auto *LookupRD
= dyn_cast_or_null
<CXXRecordDecl
>(LookupCtx
);
4202 if (LookupRD
&& LookupRD
->getIdentifier() == TemplateII
) {
4204 TemplateKWLoc
.isInvalid()
4205 ? diag::err_out_of_line_qualified_id_type_names_constructor
4206 : diag::ext_out_of_line_qualified_id_type_names_constructor
)
4207 << TemplateII
<< 0 /*injected-class-name used as template name*/
4208 << 1 /*if any keyword was present, it was 'template'*/;
4212 TemplateName Template
= TemplateD
.get();
4213 if (Template
.getAsAssumedTemplateName() &&
4214 resolveAssumedTemplateNameAsType(S
, Template
, TemplateIILoc
))
4217 // Translate the parser's template argument list in our AST format.
4218 TemplateArgumentListInfo
TemplateArgs(LAngleLoc
, RAngleLoc
);
4219 translateTemplateArguments(TemplateArgsIn
, TemplateArgs
);
4221 if (DependentTemplateName
*DTN
= Template
.getAsDependentTemplateName()) {
4222 assert(SS
.getScopeRep() == DTN
->getQualifier());
4223 QualType T
= Context
.getDependentTemplateSpecializationType(
4224 ElaboratedTypeKeyword::None
, DTN
->getQualifier(), DTN
->getIdentifier(),
4225 TemplateArgs
.arguments());
4226 // Build type-source information.
4228 DependentTemplateSpecializationTypeLoc SpecTL
4229 = TLB
.push
<DependentTemplateSpecializationTypeLoc
>(T
);
4230 SpecTL
.setElaboratedKeywordLoc(SourceLocation());
4231 SpecTL
.setQualifierLoc(SS
.getWithLocInContext(Context
));
4232 SpecTL
.setTemplateKeywordLoc(TemplateKWLoc
);
4233 SpecTL
.setTemplateNameLoc(TemplateIILoc
);
4234 SpecTL
.setLAngleLoc(LAngleLoc
);
4235 SpecTL
.setRAngleLoc(RAngleLoc
);
4236 for (unsigned I
= 0, N
= SpecTL
.getNumArgs(); I
!= N
; ++I
)
4237 SpecTL
.setArgLocInfo(I
, TemplateArgs
[I
].getLocInfo());
4238 return CreateParsedType(T
, TLB
.getTypeSourceInfo(Context
, T
));
4241 QualType SpecTy
= CheckTemplateIdType(Template
, TemplateIILoc
, TemplateArgs
);
4242 if (SpecTy
.isNull())
4245 // Build type-source information.
4247 TemplateSpecializationTypeLoc SpecTL
=
4248 TLB
.push
<TemplateSpecializationTypeLoc
>(SpecTy
);
4249 SpecTL
.setTemplateKeywordLoc(TemplateKWLoc
);
4250 SpecTL
.setTemplateNameLoc(TemplateIILoc
);
4251 SpecTL
.setLAngleLoc(LAngleLoc
);
4252 SpecTL
.setRAngleLoc(RAngleLoc
);
4253 for (unsigned i
= 0, e
= SpecTL
.getNumArgs(); i
!= e
; ++i
)
4254 SpecTL
.setArgLocInfo(i
, TemplateArgs
[i
].getLocInfo());
4256 // Create an elaborated-type-specifier containing the nested-name-specifier.
4258 getElaboratedType(ElaboratedTypeKeyword::None
,
4259 !IsCtorOrDtorName
? SS
: CXXScopeSpec(), SpecTy
);
4260 ElaboratedTypeLoc ElabTL
= TLB
.push
<ElaboratedTypeLoc
>(ElTy
);
4261 ElabTL
.setElaboratedKeywordLoc(SourceLocation());
4262 if (!ElabTL
.isEmpty())
4263 ElabTL
.setQualifierLoc(SS
.getWithLocInContext(Context
));
4264 return CreateParsedType(ElTy
, TLB
.getTypeSourceInfo(Context
, ElTy
));
4267 TypeResult
Sema::ActOnTagTemplateIdType(TagUseKind TUK
,
4268 TypeSpecifierType TagSpec
,
4269 SourceLocation TagLoc
,
4271 SourceLocation TemplateKWLoc
,
4272 TemplateTy TemplateD
,
4273 SourceLocation TemplateLoc
,
4274 SourceLocation LAngleLoc
,
4275 ASTTemplateArgsPtr TemplateArgsIn
,
4276 SourceLocation RAngleLoc
) {
4278 return TypeResult(true);
4280 TemplateName Template
= TemplateD
.get();
4282 // Translate the parser's template argument list in our AST format.
4283 TemplateArgumentListInfo
TemplateArgs(LAngleLoc
, RAngleLoc
);
4284 translateTemplateArguments(TemplateArgsIn
, TemplateArgs
);
4286 // Determine the tag kind
4287 TagTypeKind TagKind
= TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec
);
4288 ElaboratedTypeKeyword Keyword
4289 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind
);
4291 if (DependentTemplateName
*DTN
= Template
.getAsDependentTemplateName()) {
4292 assert(SS
.getScopeRep() == DTN
->getQualifier());
4293 QualType T
= Context
.getDependentTemplateSpecializationType(
4294 Keyword
, DTN
->getQualifier(), DTN
->getIdentifier(),
4295 TemplateArgs
.arguments());
4297 // Build type-source information.
4299 DependentTemplateSpecializationTypeLoc SpecTL
4300 = TLB
.push
<DependentTemplateSpecializationTypeLoc
>(T
);
4301 SpecTL
.setElaboratedKeywordLoc(TagLoc
);
4302 SpecTL
.setQualifierLoc(SS
.getWithLocInContext(Context
));
4303 SpecTL
.setTemplateKeywordLoc(TemplateKWLoc
);
4304 SpecTL
.setTemplateNameLoc(TemplateLoc
);
4305 SpecTL
.setLAngleLoc(LAngleLoc
);
4306 SpecTL
.setRAngleLoc(RAngleLoc
);
4307 for (unsigned I
= 0, N
= SpecTL
.getNumArgs(); I
!= N
; ++I
)
4308 SpecTL
.setArgLocInfo(I
, TemplateArgs
[I
].getLocInfo());
4309 return CreateParsedType(T
, TLB
.getTypeSourceInfo(Context
, T
));
4312 if (TypeAliasTemplateDecl
*TAT
=
4313 dyn_cast_or_null
<TypeAliasTemplateDecl
>(Template
.getAsTemplateDecl())) {
4314 // C++0x [dcl.type.elab]p2:
4315 // If the identifier resolves to a typedef-name or the simple-template-id
4316 // resolves to an alias template specialization, the
4317 // elaborated-type-specifier is ill-formed.
4318 Diag(TemplateLoc
, diag::err_tag_reference_non_tag
)
4319 << TAT
<< NTK_TypeAliasTemplate
<< TagKind
;
4320 Diag(TAT
->getLocation(), diag::note_declared_at
);
4323 QualType Result
= CheckTemplateIdType(Template
, TemplateLoc
, TemplateArgs
);
4324 if (Result
.isNull())
4325 return TypeResult(true);
4327 // Check the tag kind
4328 if (const RecordType
*RT
= Result
->getAs
<RecordType
>()) {
4329 RecordDecl
*D
= RT
->getDecl();
4331 IdentifierInfo
*Id
= D
->getIdentifier();
4332 assert(Id
&& "templated class must have an identifier");
4334 if (!isAcceptableTagRedeclaration(D
, TagKind
, TUK
== TUK_Definition
,
4336 Diag(TagLoc
, diag::err_use_with_wrong_tag
)
4338 << FixItHint::CreateReplacement(SourceRange(TagLoc
), D
->getKindName());
4339 Diag(D
->getLocation(), diag::note_previous_use
);
4343 // Provide source-location information for the template specialization.
4345 TemplateSpecializationTypeLoc SpecTL
4346 = TLB
.push
<TemplateSpecializationTypeLoc
>(Result
);
4347 SpecTL
.setTemplateKeywordLoc(TemplateKWLoc
);
4348 SpecTL
.setTemplateNameLoc(TemplateLoc
);
4349 SpecTL
.setLAngleLoc(LAngleLoc
);
4350 SpecTL
.setRAngleLoc(RAngleLoc
);
4351 for (unsigned i
= 0, e
= SpecTL
.getNumArgs(); i
!= e
; ++i
)
4352 SpecTL
.setArgLocInfo(i
, TemplateArgs
[i
].getLocInfo());
4354 // Construct an elaborated type containing the nested-name-specifier (if any)
4356 Result
= Context
.getElaboratedType(Keyword
, SS
.getScopeRep(), Result
);
4357 ElaboratedTypeLoc ElabTL
= TLB
.push
<ElaboratedTypeLoc
>(Result
);
4358 ElabTL
.setElaboratedKeywordLoc(TagLoc
);
4359 ElabTL
.setQualifierLoc(SS
.getWithLocInContext(Context
));
4360 return CreateParsedType(Result
, TLB
.getTypeSourceInfo(Context
, Result
));
4363 static bool CheckTemplateSpecializationScope(Sema
&S
, NamedDecl
*Specialized
,
4364 NamedDecl
*PrevDecl
,
4366 bool IsPartialSpecialization
);
4368 static TemplateSpecializationKind
getTemplateSpecializationKind(Decl
*D
);
4370 static bool isTemplateArgumentTemplateParameter(
4371 const TemplateArgument
&Arg
, unsigned Depth
, unsigned Index
) {
4372 switch (Arg
.getKind()) {
4373 case TemplateArgument::Null
:
4374 case TemplateArgument::NullPtr
:
4375 case TemplateArgument::Integral
:
4376 case TemplateArgument::Declaration
:
4377 case TemplateArgument::Pack
:
4378 case TemplateArgument::TemplateExpansion
:
4381 case TemplateArgument::Type
: {
4382 QualType Type
= Arg
.getAsType();
4383 const TemplateTypeParmType
*TPT
=
4384 Arg
.getAsType()->getAs
<TemplateTypeParmType
>();
4385 return TPT
&& !Type
.hasQualifiers() &&
4386 TPT
->getDepth() == Depth
&& TPT
->getIndex() == Index
;
4389 case TemplateArgument::Expression
: {
4390 DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(Arg
.getAsExpr());
4391 if (!DRE
|| !DRE
->getDecl())
4393 const NonTypeTemplateParmDecl
*NTTP
=
4394 dyn_cast
<NonTypeTemplateParmDecl
>(DRE
->getDecl());
4395 return NTTP
&& NTTP
->getDepth() == Depth
&& NTTP
->getIndex() == Index
;
4398 case TemplateArgument::Template
:
4399 const TemplateTemplateParmDecl
*TTP
=
4400 dyn_cast_or_null
<TemplateTemplateParmDecl
>(
4401 Arg
.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
4402 return TTP
&& TTP
->getDepth() == Depth
&& TTP
->getIndex() == Index
;
4404 llvm_unreachable("unexpected kind of template argument");
4407 static bool isSameAsPrimaryTemplate(TemplateParameterList
*Params
,
4408 ArrayRef
<TemplateArgument
> Args
) {
4409 if (Params
->size() != Args
.size())
4412 unsigned Depth
= Params
->getDepth();
4414 for (unsigned I
= 0, N
= Args
.size(); I
!= N
; ++I
) {
4415 TemplateArgument Arg
= Args
[I
];
4417 // If the parameter is a pack expansion, the argument must be a pack
4418 // whose only element is a pack expansion.
4419 if (Params
->getParam(I
)->isParameterPack()) {
4420 if (Arg
.getKind() != TemplateArgument::Pack
|| Arg
.pack_size() != 1 ||
4421 !Arg
.pack_begin()->isPackExpansion())
4423 Arg
= Arg
.pack_begin()->getPackExpansionPattern();
4426 if (!isTemplateArgumentTemplateParameter(Arg
, Depth
, I
))
4433 template<typename PartialSpecDecl
>
4434 static void checkMoreSpecializedThanPrimary(Sema
&S
, PartialSpecDecl
*Partial
) {
4435 if (Partial
->getDeclContext()->isDependentContext())
4438 // FIXME: Get the TDK from deduction in order to provide better diagnostics
4439 // for non-substitution-failure issues?
4440 TemplateDeductionInfo
Info(Partial
->getLocation());
4441 if (S
.isMoreSpecializedThanPrimary(Partial
, Info
))
4444 auto *Template
= Partial
->getSpecializedTemplate();
4445 S
.Diag(Partial
->getLocation(),
4446 diag::ext_partial_spec_not_more_specialized_than_primary
)
4447 << isa
<VarTemplateDecl
>(Template
);
4449 if (Info
.hasSFINAEDiagnostic()) {
4450 PartialDiagnosticAt Diag
= {SourceLocation(),
4451 PartialDiagnostic::NullDiagnostic()};
4452 Info
.takeSFINAEDiagnostic(Diag
);
4453 SmallString
<128> SFINAEArgString
;
4454 Diag
.second
.EmitToString(S
.getDiagnostics(), SFINAEArgString
);
4456 diag::note_partial_spec_not_more_specialized_than_primary
)
4460 S
.Diag(Template
->getLocation(), diag::note_template_decl_here
);
4461 SmallVector
<const Expr
*, 3> PartialAC
, TemplateAC
;
4462 Template
->getAssociatedConstraints(TemplateAC
);
4463 Partial
->getAssociatedConstraints(PartialAC
);
4464 S
.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Partial
, PartialAC
, Template
,
4469 noteNonDeducibleParameters(Sema
&S
, TemplateParameterList
*TemplateParams
,
4470 const llvm::SmallBitVector
&DeducibleParams
) {
4471 for (unsigned I
= 0, N
= DeducibleParams
.size(); I
!= N
; ++I
) {
4472 if (!DeducibleParams
[I
]) {
4473 NamedDecl
*Param
= TemplateParams
->getParam(I
);
4474 if (Param
->getDeclName())
4475 S
.Diag(Param
->getLocation(), diag::note_non_deducible_parameter
)
4476 << Param
->getDeclName();
4478 S
.Diag(Param
->getLocation(), diag::note_non_deducible_parameter
)
4485 template<typename PartialSpecDecl
>
4486 static void checkTemplatePartialSpecialization(Sema
&S
,
4487 PartialSpecDecl
*Partial
) {
4488 // C++1z [temp.class.spec]p8: (DR1495)
4489 // - The specialization shall be more specialized than the primary
4490 // template (14.5.5.2).
4491 checkMoreSpecializedThanPrimary(S
, Partial
);
4493 // C++ [temp.class.spec]p8: (DR1315)
4494 // - Each template-parameter shall appear at least once in the
4495 // template-id outside a non-deduced context.
4496 // C++1z [temp.class.spec.match]p3 (P0127R2)
4497 // If the template arguments of a partial specialization cannot be
4498 // deduced because of the structure of its template-parameter-list
4499 // and the template-id, the program is ill-formed.
4500 auto *TemplateParams
= Partial
->getTemplateParameters();
4501 llvm::SmallBitVector
DeducibleParams(TemplateParams
->size());
4502 S
.MarkUsedTemplateParameters(Partial
->getTemplateArgs(), true,
4503 TemplateParams
->getDepth(), DeducibleParams
);
4505 if (!DeducibleParams
.all()) {
4506 unsigned NumNonDeducible
= DeducibleParams
.size() - DeducibleParams
.count();
4507 S
.Diag(Partial
->getLocation(), diag::ext_partial_specs_not_deducible
)
4508 << isa
<VarTemplatePartialSpecializationDecl
>(Partial
)
4509 << (NumNonDeducible
> 1)
4510 << SourceRange(Partial
->getLocation(),
4511 Partial
->getTemplateArgsAsWritten()->RAngleLoc
);
4512 noteNonDeducibleParameters(S
, TemplateParams
, DeducibleParams
);
4516 void Sema::CheckTemplatePartialSpecialization(
4517 ClassTemplatePartialSpecializationDecl
*Partial
) {
4518 checkTemplatePartialSpecialization(*this, Partial
);
4521 void Sema::CheckTemplatePartialSpecialization(
4522 VarTemplatePartialSpecializationDecl
*Partial
) {
4523 checkTemplatePartialSpecialization(*this, Partial
);
4526 void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl
*TD
) {
4527 // C++1z [temp.param]p11:
4528 // A template parameter of a deduction guide template that does not have a
4529 // default-argument shall be deducible from the parameter-type-list of the
4530 // deduction guide template.
4531 auto *TemplateParams
= TD
->getTemplateParameters();
4532 llvm::SmallBitVector
DeducibleParams(TemplateParams
->size());
4533 MarkDeducedTemplateParameters(TD
, DeducibleParams
);
4534 for (unsigned I
= 0; I
!= TemplateParams
->size(); ++I
) {
4535 // A parameter pack is deducible (to an empty pack).
4536 auto *Param
= TemplateParams
->getParam(I
);
4537 if (Param
->isParameterPack() || hasVisibleDefaultArgument(Param
))
4538 DeducibleParams
[I
] = true;
4541 if (!DeducibleParams
.all()) {
4542 unsigned NumNonDeducible
= DeducibleParams
.size() - DeducibleParams
.count();
4543 Diag(TD
->getLocation(), diag::err_deduction_guide_template_not_deducible
)
4544 << (NumNonDeducible
> 1);
4545 noteNonDeducibleParameters(*this, TemplateParams
, DeducibleParams
);
4549 DeclResult
Sema::ActOnVarTemplateSpecialization(
4550 Scope
*S
, Declarator
&D
, TypeSourceInfo
*DI
, SourceLocation TemplateKWLoc
,
4551 TemplateParameterList
*TemplateParams
, StorageClass SC
,
4552 bool IsPartialSpecialization
) {
4553 // D must be variable template id.
4554 assert(D
.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
&&
4555 "Variable template specialization is declared with a template id.");
4557 TemplateIdAnnotation
*TemplateId
= D
.getName().TemplateId
;
4558 TemplateArgumentListInfo TemplateArgs
=
4559 makeTemplateArgumentListInfo(*this, *TemplateId
);
4560 SourceLocation TemplateNameLoc
= D
.getIdentifierLoc();
4561 SourceLocation LAngleLoc
= TemplateId
->LAngleLoc
;
4562 SourceLocation RAngleLoc
= TemplateId
->RAngleLoc
;
4564 TemplateName Name
= TemplateId
->Template
.get();
4566 // The template-id must name a variable template.
4567 VarTemplateDecl
*VarTemplate
=
4568 dyn_cast_or_null
<VarTemplateDecl
>(Name
.getAsTemplateDecl());
4570 NamedDecl
*FnTemplate
;
4571 if (auto *OTS
= Name
.getAsOverloadedTemplate())
4572 FnTemplate
= *OTS
->begin();
4574 FnTemplate
= dyn_cast_or_null
<FunctionTemplateDecl
>(Name
.getAsTemplateDecl());
4576 return Diag(D
.getIdentifierLoc(), diag::err_var_spec_no_template_but_method
)
4577 << FnTemplate
->getDeclName();
4578 return Diag(D
.getIdentifierLoc(), diag::err_var_spec_no_template
)
4579 << IsPartialSpecialization
;
4582 // Check for unexpanded parameter packs in any of the template arguments.
4583 for (unsigned I
= 0, N
= TemplateArgs
.size(); I
!= N
; ++I
)
4584 if (DiagnoseUnexpandedParameterPack(TemplateArgs
[I
],
4585 UPPC_PartialSpecialization
))
4588 // Check that the template argument list is well-formed for this
4590 SmallVector
<TemplateArgument
, 4> SugaredConverted
, CanonicalConverted
;
4591 if (CheckTemplateArgumentList(VarTemplate
, TemplateNameLoc
, TemplateArgs
,
4592 false, SugaredConverted
, CanonicalConverted
,
4593 /*UpdateArgsWithConversions=*/true))
4596 // Find the variable template (partial) specialization declaration that
4597 // corresponds to these arguments.
4598 if (IsPartialSpecialization
) {
4599 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc
, VarTemplate
,
4600 TemplateArgs
.size(),
4601 CanonicalConverted
))
4604 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
4605 // also do them during instantiation.
4606 if (!Name
.isDependent() &&
4607 !TemplateSpecializationType::anyDependentTemplateArguments(
4608 TemplateArgs
, CanonicalConverted
)) {
4609 Diag(TemplateNameLoc
, diag::err_partial_spec_fully_specialized
)
4610 << VarTemplate
->getDeclName();
4611 IsPartialSpecialization
= false;
4614 if (isSameAsPrimaryTemplate(VarTemplate
->getTemplateParameters(),
4615 CanonicalConverted
) &&
4616 (!Context
.getLangOpts().CPlusPlus20
||
4617 !TemplateParams
->hasAssociatedConstraints())) {
4618 // C++ [temp.class.spec]p9b3:
4620 // -- The argument list of the specialization shall not be identical
4621 // to the implicit argument list of the primary template.
4622 Diag(TemplateNameLoc
, diag::err_partial_spec_args_match_primary_template
)
4623 << /*variable template*/ 1
4624 << /*is definition*/(SC
!= SC_Extern
&& !CurContext
->isRecord())
4625 << FixItHint::CreateRemoval(SourceRange(LAngleLoc
, RAngleLoc
));
4626 // FIXME: Recover from this by treating the declaration as a redeclaration
4627 // of the primary template.
4632 void *InsertPos
= nullptr;
4633 VarTemplateSpecializationDecl
*PrevDecl
= nullptr;
4635 if (IsPartialSpecialization
)
4636 PrevDecl
= VarTemplate
->findPartialSpecialization(
4637 CanonicalConverted
, TemplateParams
, InsertPos
);
4639 PrevDecl
= VarTemplate
->findSpecialization(CanonicalConverted
, InsertPos
);
4641 VarTemplateSpecializationDecl
*Specialization
= nullptr;
4643 // Check whether we can declare a variable template specialization in
4644 // the current scope.
4645 if (CheckTemplateSpecializationScope(*this, VarTemplate
, PrevDecl
,
4647 IsPartialSpecialization
))
4650 if (PrevDecl
&& PrevDecl
->getSpecializationKind() == TSK_Undeclared
) {
4651 // Since the only prior variable template specialization with these
4652 // arguments was referenced but not declared, reuse that
4653 // declaration node as our own, updating its source location and
4654 // the list of outer template parameters to reflect our new declaration.
4655 Specialization
= PrevDecl
;
4656 Specialization
->setLocation(TemplateNameLoc
);
4658 } else if (IsPartialSpecialization
) {
4659 // Create a new class template partial specialization declaration node.
4660 VarTemplatePartialSpecializationDecl
*PrevPartial
=
4661 cast_or_null
<VarTemplatePartialSpecializationDecl
>(PrevDecl
);
4662 VarTemplatePartialSpecializationDecl
*Partial
=
4663 VarTemplatePartialSpecializationDecl::Create(
4664 Context
, VarTemplate
->getDeclContext(), TemplateKWLoc
,
4665 TemplateNameLoc
, TemplateParams
, VarTemplate
, DI
->getType(), DI
, SC
,
4666 CanonicalConverted
, TemplateArgs
);
4669 VarTemplate
->AddPartialSpecialization(Partial
, InsertPos
);
4670 Specialization
= Partial
;
4672 // If we are providing an explicit specialization of a member variable
4673 // template specialization, make a note of that.
4674 if (PrevPartial
&& PrevPartial
->getInstantiatedFromMember())
4675 PrevPartial
->setMemberSpecialization();
4677 CheckTemplatePartialSpecialization(Partial
);
4679 // Create a new class template specialization declaration node for
4680 // this explicit specialization or friend declaration.
4681 Specialization
= VarTemplateSpecializationDecl::Create(
4682 Context
, VarTemplate
->getDeclContext(), TemplateKWLoc
, TemplateNameLoc
,
4683 VarTemplate
, DI
->getType(), DI
, SC
, CanonicalConverted
);
4684 Specialization
->setTemplateArgsInfo(TemplateArgs
);
4687 VarTemplate
->AddSpecialization(Specialization
, InsertPos
);
4690 // C++ [temp.expl.spec]p6:
4691 // If a template, a member template or the member of a class template is
4692 // explicitly specialized then that specialization shall be declared
4693 // before the first use of that specialization that would cause an implicit
4694 // instantiation to take place, in every translation unit in which such a
4695 // use occurs; no diagnostic is required.
4696 if (PrevDecl
&& PrevDecl
->getPointOfInstantiation().isValid()) {
4698 for (Decl
*Prev
= PrevDecl
; Prev
; Prev
= Prev
->getPreviousDecl()) {
4699 // Is there any previous explicit specialization declaration?
4700 if (getTemplateSpecializationKind(Prev
) == TSK_ExplicitSpecialization
) {
4707 SourceRange
Range(TemplateNameLoc
, RAngleLoc
);
4708 Diag(TemplateNameLoc
, diag::err_specialization_after_instantiation
)
4711 Diag(PrevDecl
->getPointOfInstantiation(),
4712 diag::note_instantiation_required_here
)
4713 << (PrevDecl
->getTemplateSpecializationKind() !=
4714 TSK_ImplicitInstantiation
);
4719 Specialization
->setTemplateKeywordLoc(TemplateKWLoc
);
4720 Specialization
->setLexicalDeclContext(CurContext
);
4722 // Add the specialization into its lexical context, so that it can
4723 // be seen when iterating through the list of declarations in that
4724 // context. However, specializations are not found by name lookup.
4725 CurContext
->addDecl(Specialization
);
4727 // Note that this is an explicit specialization.
4728 Specialization
->setSpecializationKind(TSK_ExplicitSpecialization
);
4731 // Check that this isn't a redefinition of this specialization,
4732 // merging with previous declarations.
4733 LookupResult
PrevSpec(*this, GetNameForDeclarator(D
), LookupOrdinaryName
,
4734 forRedeclarationInCurContext());
4735 PrevSpec
.addDecl(PrevDecl
);
4736 D
.setRedeclaration(CheckVariableDeclaration(Specialization
, PrevSpec
));
4737 } else if (Specialization
->isStaticDataMember() &&
4738 Specialization
->isOutOfLine()) {
4739 Specialization
->setAccess(VarTemplate
->getAccess());
4742 return Specialization
;
4746 /// A partial specialization whose template arguments have matched
4747 /// a given template-id.
4748 struct PartialSpecMatchResult
{
4749 VarTemplatePartialSpecializationDecl
*Partial
;
4750 TemplateArgumentList
*Args
;
4752 } // end anonymous namespace
4755 Sema::CheckVarTemplateId(VarTemplateDecl
*Template
, SourceLocation TemplateLoc
,
4756 SourceLocation TemplateNameLoc
,
4757 const TemplateArgumentListInfo
&TemplateArgs
) {
4758 assert(Template
&& "A variable template id without template?");
4760 // Check that the template argument list is well-formed for this template.
4761 SmallVector
<TemplateArgument
, 4> SugaredConverted
, CanonicalConverted
;
4762 if (CheckTemplateArgumentList(
4763 Template
, TemplateNameLoc
,
4764 const_cast<TemplateArgumentListInfo
&>(TemplateArgs
), false,
4765 SugaredConverted
, CanonicalConverted
,
4766 /*UpdateArgsWithConversions=*/true))
4769 // Produce a placeholder value if the specialization is dependent.
4770 if (Template
->getDeclContext()->isDependentContext() ||
4771 TemplateSpecializationType::anyDependentTemplateArguments(
4772 TemplateArgs
, CanonicalConverted
))
4773 return DeclResult();
4775 // Find the variable template specialization declaration that
4776 // corresponds to these arguments.
4777 void *InsertPos
= nullptr;
4778 if (VarTemplateSpecializationDecl
*Spec
=
4779 Template
->findSpecialization(CanonicalConverted
, InsertPos
)) {
4780 checkSpecializationReachability(TemplateNameLoc
, Spec
);
4781 // If we already have a variable template specialization, return it.
4785 // This is the first time we have referenced this variable template
4786 // specialization. Create the canonical declaration and add it to
4787 // the set of specializations, based on the closest partial specialization
4788 // that it represents. That is,
4789 VarDecl
*InstantiationPattern
= Template
->getTemplatedDecl();
4790 TemplateArgumentList
TemplateArgList(TemplateArgumentList::OnStack
,
4791 CanonicalConverted
);
4792 TemplateArgumentList
*InstantiationArgs
= &TemplateArgList
;
4793 bool AmbiguousPartialSpec
= false;
4794 typedef PartialSpecMatchResult MatchResult
;
4795 SmallVector
<MatchResult
, 4> Matched
;
4796 SourceLocation PointOfInstantiation
= TemplateNameLoc
;
4797 TemplateSpecCandidateSet
FailedCandidates(PointOfInstantiation
,
4798 /*ForTakingAddress=*/false);
4800 // 1. Attempt to find the closest partial specialization that this
4801 // specializes, if any.
4802 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4803 // Perhaps better after unification of DeduceTemplateArguments() and
4804 // getMoreSpecializedPartialSpecialization().
4805 SmallVector
<VarTemplatePartialSpecializationDecl
*, 4> PartialSpecs
;
4806 Template
->getPartialSpecializations(PartialSpecs
);
4808 for (unsigned I
= 0, N
= PartialSpecs
.size(); I
!= N
; ++I
) {
4809 VarTemplatePartialSpecializationDecl
*Partial
= PartialSpecs
[I
];
4810 TemplateDeductionInfo
Info(FailedCandidates
.getLocation());
4812 if (TemplateDeductionResult Result
=
4813 DeduceTemplateArguments(Partial
, TemplateArgList
, Info
)) {
4814 // Store the failed-deduction information for use in diagnostics, later.
4815 // TODO: Actually use the failed-deduction info?
4816 FailedCandidates
.addCandidate().set(
4817 DeclAccessPair::make(Template
, AS_public
), Partial
,
4818 MakeDeductionFailureInfo(Context
, Result
, Info
));
4821 Matched
.push_back(PartialSpecMatchResult());
4822 Matched
.back().Partial
= Partial
;
4823 Matched
.back().Args
= Info
.takeCanonical();
4827 if (Matched
.size() >= 1) {
4828 SmallVector
<MatchResult
, 4>::iterator Best
= Matched
.begin();
4829 if (Matched
.size() == 1) {
4830 // -- If exactly one matching specialization is found, the
4831 // instantiation is generated from that specialization.
4832 // We don't need to do anything for this.
4834 // -- If more than one matching specialization is found, the
4835 // partial order rules (14.5.4.2) are used to determine
4836 // whether one of the specializations is more specialized
4837 // than the others. If none of the specializations is more
4838 // specialized than all of the other matching
4839 // specializations, then the use of the variable template is
4840 // ambiguous and the program is ill-formed.
4841 for (SmallVector
<MatchResult
, 4>::iterator P
= Best
+ 1,
4842 PEnd
= Matched
.end();
4844 if (getMoreSpecializedPartialSpecialization(P
->Partial
, Best
->Partial
,
4845 PointOfInstantiation
) ==
4850 // Determine if the best partial specialization is more specialized than
4852 for (SmallVector
<MatchResult
, 4>::iterator P
= Matched
.begin(),
4853 PEnd
= Matched
.end();
4855 if (P
!= Best
&& getMoreSpecializedPartialSpecialization(
4856 P
->Partial
, Best
->Partial
,
4857 PointOfInstantiation
) != Best
->Partial
) {
4858 AmbiguousPartialSpec
= true;
4864 // Instantiate using the best variable template partial specialization.
4865 InstantiationPattern
= Best
->Partial
;
4866 InstantiationArgs
= Best
->Args
;
4868 // -- If no match is found, the instantiation is generated
4869 // from the primary template.
4870 // InstantiationPattern = Template->getTemplatedDecl();
4873 // 2. Create the canonical declaration.
4874 // Note that we do not instantiate a definition until we see an odr-use
4875 // in DoMarkVarDeclReferenced().
4876 // FIXME: LateAttrs et al.?
4877 VarTemplateSpecializationDecl
*Decl
= BuildVarTemplateInstantiation(
4878 Template
, InstantiationPattern
, *InstantiationArgs
, TemplateArgs
,
4879 CanonicalConverted
, TemplateNameLoc
/*, LateAttrs, StartingScope*/);
4883 if (AmbiguousPartialSpec
) {
4884 // Partial ordering did not produce a clear winner. Complain.
4885 Decl
->setInvalidDecl();
4886 Diag(PointOfInstantiation
, diag::err_partial_spec_ordering_ambiguous
)
4889 // Print the matching partial specializations.
4890 for (MatchResult P
: Matched
)
4891 Diag(P
.Partial
->getLocation(), diag::note_partial_spec_match
)
4892 << getTemplateArgumentBindingsText(P
.Partial
->getTemplateParameters(),
4897 if (VarTemplatePartialSpecializationDecl
*D
=
4898 dyn_cast
<VarTemplatePartialSpecializationDecl
>(InstantiationPattern
))
4899 Decl
->setInstantiationOf(D
, InstantiationArgs
);
4901 checkSpecializationReachability(TemplateNameLoc
, Decl
);
4903 assert(Decl
&& "No variable template specialization?");
4908 Sema::CheckVarTemplateId(const CXXScopeSpec
&SS
,
4909 const DeclarationNameInfo
&NameInfo
,
4910 VarTemplateDecl
*Template
, SourceLocation TemplateLoc
,
4911 const TemplateArgumentListInfo
*TemplateArgs
) {
4913 DeclResult Decl
= CheckVarTemplateId(Template
, TemplateLoc
, NameInfo
.getLoc(),
4915 if (Decl
.isInvalid())
4919 return ExprResult();
4921 VarDecl
*Var
= cast
<VarDecl
>(Decl
.get());
4922 if (!Var
->getTemplateSpecializationKind())
4923 Var
->setTemplateSpecializationKind(TSK_ImplicitInstantiation
,
4926 // Build an ordinary singleton decl ref.
4927 return BuildDeclarationNameExpr(SS
, NameInfo
, Var
,
4928 /*FoundD=*/nullptr, TemplateArgs
);
4931 void Sema::diagnoseMissingTemplateArguments(TemplateName Name
,
4932 SourceLocation Loc
) {
4933 Diag(Loc
, diag::err_template_missing_args
)
4934 << (int)getTemplateNameKindForDiagnostics(Name
) << Name
;
4935 if (TemplateDecl
*TD
= Name
.getAsTemplateDecl()) {
4936 Diag(TD
->getLocation(), diag::note_template_decl_here
)
4937 << TD
->getTemplateParameters()->getSourceRange();
4942 Sema::CheckConceptTemplateId(const CXXScopeSpec
&SS
,
4943 SourceLocation TemplateKWLoc
,
4944 const DeclarationNameInfo
&ConceptNameInfo
,
4945 NamedDecl
*FoundDecl
,
4946 ConceptDecl
*NamedConcept
,
4947 const TemplateArgumentListInfo
*TemplateArgs
) {
4948 assert(NamedConcept
&& "A concept template id without a template?");
4950 llvm::SmallVector
<TemplateArgument
, 4> SugaredConverted
, CanonicalConverted
;
4951 if (CheckTemplateArgumentList(
4952 NamedConcept
, ConceptNameInfo
.getLoc(),
4953 const_cast<TemplateArgumentListInfo
&>(*TemplateArgs
),
4954 /*PartialTemplateArgs=*/false, SugaredConverted
, CanonicalConverted
,
4955 /*UpdateArgsWithConversions=*/false))
4958 auto *CSD
= ImplicitConceptSpecializationDecl::Create(
4959 Context
, NamedConcept
->getDeclContext(), NamedConcept
->getLocation(),
4960 CanonicalConverted
);
4961 ConstraintSatisfaction Satisfaction
;
4962 bool AreArgsDependent
=
4963 TemplateSpecializationType::anyDependentTemplateArguments(
4964 *TemplateArgs
, CanonicalConverted
);
4965 MultiLevelTemplateArgumentList
MLTAL(NamedConcept
, CanonicalConverted
,
4967 LocalInstantiationScope
Scope(*this);
4969 EnterExpressionEvaluationContext EECtx
{
4970 *this, ExpressionEvaluationContext::ConstantEvaluated
, CSD
};
4972 if (!AreArgsDependent
&&
4973 CheckConstraintSatisfaction(
4974 NamedConcept
, {NamedConcept
->getConstraintExpr()}, MLTAL
,
4975 SourceRange(SS
.isSet() ? SS
.getBeginLoc() : ConceptNameInfo
.getLoc(),
4976 TemplateArgs
->getRAngleLoc()),
4979 auto *CL
= ConceptReference::Create(
4981 SS
.isSet() ? SS
.getWithLocInContext(Context
) : NestedNameSpecifierLoc
{},
4982 TemplateKWLoc
, ConceptNameInfo
, FoundDecl
, NamedConcept
,
4983 ASTTemplateArgumentListInfo::Create(Context
, *TemplateArgs
));
4984 return ConceptSpecializationExpr::Create(
4985 Context
, CL
, CSD
, AreArgsDependent
? nullptr : &Satisfaction
);
4988 ExprResult
Sema::BuildTemplateIdExpr(const CXXScopeSpec
&SS
,
4989 SourceLocation TemplateKWLoc
,
4992 const TemplateArgumentListInfo
*TemplateArgs
) {
4993 // FIXME: Can we do any checking at this point? I guess we could check the
4994 // template arguments that we have against the template name, if the template
4995 // name refers to a single template. That's not a terribly common case,
4997 // foo<int> could identify a single function unambiguously
4998 // This approach does NOT work, since f<int>(1);
4999 // gets resolved prior to resorting to overload resolution
5000 // i.e., template<class T> void f(double);
5001 // vs template<class T, class U> void f(U);
5003 // These should be filtered out by our callers.
5004 assert(!R
.isAmbiguous() && "ambiguous lookup when building templateid");
5006 // Non-function templates require a template argument list.
5007 if (auto *TD
= R
.getAsSingle
<TemplateDecl
>()) {
5008 if (!TemplateArgs
&& !isa
<FunctionTemplateDecl
>(TD
)) {
5009 diagnoseMissingTemplateArguments(TemplateName(TD
), R
.getNameLoc());
5013 bool KnownDependent
= false;
5014 // In C++1y, check variable template ids.
5015 if (R
.getAsSingle
<VarTemplateDecl
>()) {
5016 ExprResult Res
= CheckVarTemplateId(SS
, R
.getLookupNameInfo(),
5017 R
.getAsSingle
<VarTemplateDecl
>(),
5018 TemplateKWLoc
, TemplateArgs
);
5019 if (Res
.isInvalid() || Res
.isUsable())
5021 // Result is dependent. Carry on to build an UnresolvedLookupEpxr.
5022 KnownDependent
= true;
5025 if (R
.getAsSingle
<ConceptDecl
>()) {
5026 return CheckConceptTemplateId(SS
, TemplateKWLoc
, R
.getLookupNameInfo(),
5028 R
.getAsSingle
<ConceptDecl
>(), TemplateArgs
);
5031 // We don't want lookup warnings at this point.
5032 R
.suppressDiagnostics();
5034 UnresolvedLookupExpr
*ULE
= UnresolvedLookupExpr::Create(
5035 Context
, R
.getNamingClass(), SS
.getWithLocInContext(Context
),
5036 TemplateKWLoc
, R
.getLookupNameInfo(), RequiresADL
, TemplateArgs
,
5037 R
.begin(), R
.end(), KnownDependent
);
5042 // We actually only call this from template instantiation.
5044 Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec
&SS
,
5045 SourceLocation TemplateKWLoc
,
5046 const DeclarationNameInfo
&NameInfo
,
5047 const TemplateArgumentListInfo
*TemplateArgs
) {
5049 assert(TemplateArgs
|| TemplateKWLoc
.isValid());
5051 if (!(DC
= computeDeclContext(SS
, false)) ||
5052 DC
->isDependentContext() ||
5053 RequireCompleteDeclContext(SS
, DC
))
5054 return BuildDependentDeclRefExpr(SS
, TemplateKWLoc
, NameInfo
, TemplateArgs
);
5056 bool MemberOfUnknownSpecialization
;
5057 LookupResult
R(*this, NameInfo
, LookupOrdinaryName
);
5058 if (LookupTemplateName(R
, (Scope
*)nullptr, SS
, QualType(),
5059 /*Entering*/false, MemberOfUnknownSpecialization
,
5063 if (R
.isAmbiguous())
5067 Diag(NameInfo
.getLoc(), diag::err_no_member
)
5068 << NameInfo
.getName() << DC
<< SS
.getRange();
5072 auto DiagnoseTypeTemplateDecl
= [&](TemplateDecl
*Temp
,
5073 bool isTypeAliasTemplateDecl
) {
5074 Diag(NameInfo
.getLoc(), diag::err_template_kw_refers_to_type_template
)
5075 << SS
.getScopeRep() << NameInfo
.getName().getAsString() << SS
.getRange()
5076 << isTypeAliasTemplateDecl
;
5077 Diag(Temp
->getLocation(), diag::note_referenced_type_template
) << 0;
5081 if (ClassTemplateDecl
*Temp
= R
.getAsSingle
<ClassTemplateDecl
>())
5082 return DiagnoseTypeTemplateDecl(Temp
, false);
5084 if (TypeAliasTemplateDecl
*Temp
= R
.getAsSingle
<TypeAliasTemplateDecl
>())
5085 return DiagnoseTypeTemplateDecl(Temp
, true);
5087 return BuildTemplateIdExpr(SS
, TemplateKWLoc
, R
, /*ADL*/ false, TemplateArgs
);
5090 /// Form a template name from a name that is syntactically required to name a
5091 /// template, either due to use of the 'template' keyword or because a name in
5092 /// this syntactic context is assumed to name a template (C++ [temp.names]p2-4).
5094 /// This action forms a template name given the name of the template and its
5095 /// optional scope specifier. This is used when the 'template' keyword is used
5096 /// or when the parsing context unambiguously treats a following '<' as
5097 /// introducing a template argument list. Note that this may produce a
5098 /// non-dependent template name if we can perform the lookup now and identify
5099 /// the named template.
5101 /// For example, given "x.MetaFun::template apply", the scope specifier
5102 /// \p SS will be "MetaFun::", \p TemplateKWLoc contains the location
5103 /// of the "template" keyword, and "apply" is the \p Name.
5104 TemplateNameKind
Sema::ActOnTemplateName(Scope
*S
,
5106 SourceLocation TemplateKWLoc
,
5107 const UnqualifiedId
&Name
,
5108 ParsedType ObjectType
,
5109 bool EnteringContext
,
5111 bool AllowInjectedClassName
) {
5112 if (TemplateKWLoc
.isValid() && S
&& !S
->getTemplateParamParent())
5114 getLangOpts().CPlusPlus11
?
5115 diag::warn_cxx98_compat_template_outside_of_template
:
5116 diag::ext_template_outside_of_template
)
5117 << FixItHint::CreateRemoval(TemplateKWLoc
);
5120 return TNK_Non_template
;
5122 // Figure out where isTemplateName is going to look.
5123 DeclContext
*LookupCtx
= nullptr;
5124 if (SS
.isNotEmpty())
5125 LookupCtx
= computeDeclContext(SS
, EnteringContext
);
5126 else if (ObjectType
)
5127 LookupCtx
= computeDeclContext(GetTypeFromParser(ObjectType
));
5129 // C++0x [temp.names]p5:
5130 // If a name prefixed by the keyword template is not the name of
5131 // a template, the program is ill-formed. [Note: the keyword
5132 // template may not be applied to non-template members of class
5133 // templates. -end note ] [ Note: as is the case with the
5134 // typename prefix, the template prefix is allowed in cases
5135 // where it is not strictly necessary; i.e., when the
5136 // nested-name-specifier or the expression on the left of the ->
5137 // or . is not dependent on a template-parameter, or the use
5138 // does not appear in the scope of a template. -end note]
5140 // Note: C++03 was more strict here, because it banned the use of
5141 // the "template" keyword prior to a template-name that was not a
5142 // dependent name. C++ DR468 relaxed this requirement (the
5143 // "template" keyword is now permitted). We follow the C++0x
5144 // rules, even in C++03 mode with a warning, retroactively applying the DR.
5145 bool MemberOfUnknownSpecialization
;
5146 TemplateNameKind TNK
= isTemplateName(S
, SS
, TemplateKWLoc
.isValid(), Name
,
5147 ObjectType
, EnteringContext
, Result
,
5148 MemberOfUnknownSpecialization
);
5149 if (TNK
!= TNK_Non_template
) {
5150 // We resolved this to a (non-dependent) template name. Return it.
5151 auto *LookupRD
= dyn_cast_or_null
<CXXRecordDecl
>(LookupCtx
);
5152 if (!AllowInjectedClassName
&& SS
.isNotEmpty() && LookupRD
&&
5153 Name
.getKind() == UnqualifiedIdKind::IK_Identifier
&&
5154 Name
.Identifier
&& LookupRD
->getIdentifier() == Name
.Identifier
) {
5155 // C++14 [class.qual]p2:
5156 // In a lookup in which function names are not ignored and the
5157 // nested-name-specifier nominates a class C, if the name specified
5158 // [...] is the injected-class-name of C, [...] the name is instead
5159 // considered to name the constructor
5161 // We don't get here if naming the constructor would be valid, so we
5162 // just reject immediately and recover by treating the
5163 // injected-class-name as naming the template.
5164 Diag(Name
.getBeginLoc(),
5165 diag::ext_out_of_line_qualified_id_type_names_constructor
)
5167 << 0 /*injected-class-name used as template name*/
5168 << TemplateKWLoc
.isValid();
5173 if (!MemberOfUnknownSpecialization
) {
5174 // Didn't find a template name, and the lookup wasn't dependent.
5175 // Do the lookup again to determine if this is a "nothing found" case or
5176 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
5178 DeclarationNameInfo DNI
= GetNameFromUnqualifiedId(Name
);
5179 LookupResult
R(*this, DNI
.getName(), Name
.getBeginLoc(),
5180 LookupOrdinaryName
);
5182 // Tell LookupTemplateName that we require a template so that it diagnoses
5183 // cases where it finds a non-template.
5184 RequiredTemplateKind RTK
= TemplateKWLoc
.isValid()
5185 ? RequiredTemplateKind(TemplateKWLoc
)
5186 : TemplateNameIsRequired
;
5187 if (!LookupTemplateName(R
, S
, SS
, ObjectType
.get(), EnteringContext
, MOUS
,
5188 RTK
, nullptr, /*AllowTypoCorrection=*/false) &&
5191 Diag(Name
.getBeginLoc(), diag::err_no_member
)
5192 << DNI
.getName() << LookupCtx
<< SS
.getRange();
5194 Diag(Name
.getBeginLoc(), diag::err_undeclared_use
)
5195 << DNI
.getName() << SS
.getRange();
5197 return TNK_Non_template
;
5200 NestedNameSpecifier
*Qualifier
= SS
.getScopeRep();
5202 switch (Name
.getKind()) {
5203 case UnqualifiedIdKind::IK_Identifier
:
5204 Result
= TemplateTy::make(
5205 Context
.getDependentTemplateName(Qualifier
, Name
.Identifier
));
5206 return TNK_Dependent_template_name
;
5208 case UnqualifiedIdKind::IK_OperatorFunctionId
:
5209 Result
= TemplateTy::make(Context
.getDependentTemplateName(
5210 Qualifier
, Name
.OperatorFunctionId
.Operator
));
5211 return TNK_Function_template
;
5213 case UnqualifiedIdKind::IK_LiteralOperatorId
:
5214 // This is a kind of template name, but can never occur in a dependent
5215 // scope (literal operators can only be declared at namespace scope).
5222 // This name cannot possibly name a dependent template. Diagnose this now
5223 // rather than building a dependent template name that can never be valid.
5224 Diag(Name
.getBeginLoc(),
5225 diag::err_template_kw_refers_to_dependent_non_template
)
5226 << GetNameFromUnqualifiedId(Name
).getName() << Name
.getSourceRange()
5227 << TemplateKWLoc
.isValid() << TemplateKWLoc
;
5228 return TNK_Non_template
;
5231 bool Sema::CheckTemplateTypeArgument(
5232 TemplateTypeParmDecl
*Param
, TemplateArgumentLoc
&AL
,
5233 SmallVectorImpl
<TemplateArgument
> &SugaredConverted
,
5234 SmallVectorImpl
<TemplateArgument
> &CanonicalConverted
) {
5235 const TemplateArgument
&Arg
= AL
.getArgument();
5237 TypeSourceInfo
*TSI
= nullptr;
5239 // Check template type parameter.
5240 switch(Arg
.getKind()) {
5241 case TemplateArgument::Type
:
5242 // C++ [temp.arg.type]p1:
5243 // A template-argument for a template-parameter which is a
5244 // type shall be a type-id.
5245 ArgType
= Arg
.getAsType();
5246 TSI
= AL
.getTypeSourceInfo();
5248 case TemplateArgument::Template
:
5249 case TemplateArgument::TemplateExpansion
: {
5250 // We have a template type parameter but the template argument
5251 // is a template without any arguments.
5252 SourceRange SR
= AL
.getSourceRange();
5253 TemplateName Name
= Arg
.getAsTemplateOrTemplatePattern();
5254 diagnoseMissingTemplateArguments(Name
, SR
.getEnd());
5257 case TemplateArgument::Expression
: {
5258 // We have a template type parameter but the template argument is an
5259 // expression; see if maybe it is missing the "typename" keyword.
5261 DeclarationNameInfo NameInfo
;
5263 if (DependentScopeDeclRefExpr
*ArgExpr
=
5264 dyn_cast
<DependentScopeDeclRefExpr
>(Arg
.getAsExpr())) {
5265 SS
.Adopt(ArgExpr
->getQualifierLoc());
5266 NameInfo
= ArgExpr
->getNameInfo();
5267 } else if (CXXDependentScopeMemberExpr
*ArgExpr
=
5268 dyn_cast
<CXXDependentScopeMemberExpr
>(Arg
.getAsExpr())) {
5269 if (ArgExpr
->isImplicitAccess()) {
5270 SS
.Adopt(ArgExpr
->getQualifierLoc());
5271 NameInfo
= ArgExpr
->getMemberNameInfo();
5275 if (auto *II
= NameInfo
.getName().getAsIdentifierInfo()) {
5276 LookupResult
Result(*this, NameInfo
, LookupOrdinaryName
);
5277 LookupParsedName(Result
, CurScope
, &SS
);
5279 if (Result
.getAsSingle
<TypeDecl
>() ||
5280 Result
.getResultKind() ==
5281 LookupResult::NotFoundInCurrentInstantiation
) {
5282 assert(SS
.getScopeRep() && "dependent scope expr must has a scope!");
5283 // Suggest that the user add 'typename' before the NNS.
5284 SourceLocation Loc
= AL
.getSourceRange().getBegin();
5285 Diag(Loc
, getLangOpts().MSVCCompat
5286 ? diag::ext_ms_template_type_arg_missing_typename
5287 : diag::err_template_arg_must_be_type_suggest
)
5288 << FixItHint::CreateInsertion(Loc
, "typename ");
5289 Diag(Param
->getLocation(), diag::note_template_param_here
);
5291 // Recover by synthesizing a type using the location information that we
5293 ArgType
= Context
.getDependentNameType(ElaboratedTypeKeyword::Typename
,
5294 SS
.getScopeRep(), II
);
5296 DependentNameTypeLoc TL
= TLB
.push
<DependentNameTypeLoc
>(ArgType
);
5297 TL
.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
5298 TL
.setQualifierLoc(SS
.getWithLocInContext(Context
));
5299 TL
.setNameLoc(NameInfo
.getLoc());
5300 TSI
= TLB
.getTypeSourceInfo(Context
, ArgType
);
5302 // Overwrite our input TemplateArgumentLoc so that we can recover
5304 AL
= TemplateArgumentLoc(TemplateArgument(ArgType
),
5305 TemplateArgumentLocInfo(TSI
));
5314 // We have a template type parameter but the template argument
5316 SourceRange SR
= AL
.getSourceRange();
5317 Diag(SR
.getBegin(), diag::err_template_arg_must_be_type
) << SR
;
5318 Diag(Param
->getLocation(), diag::note_template_param_here
);
5324 if (CheckTemplateArgument(TSI
))
5328 // If an explicitly-specified template argument type is a lifetime type
5329 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
5330 if (getLangOpts().ObjCAutoRefCount
&&
5331 ArgType
->isObjCLifetimeType() &&
5332 !ArgType
.getObjCLifetime()) {
5334 Qs
.setObjCLifetime(Qualifiers::OCL_Strong
);
5335 ArgType
= Context
.getQualifiedType(ArgType
, Qs
);
5338 SugaredConverted
.push_back(TemplateArgument(ArgType
));
5339 CanonicalConverted
.push_back(
5340 TemplateArgument(Context
.getCanonicalType(ArgType
)));
5344 /// Substitute template arguments into the default template argument for
5345 /// the given template type parameter.
5347 /// \param SemaRef the semantic analysis object for which we are performing
5348 /// the substitution.
5350 /// \param Template the template that we are synthesizing template arguments
5353 /// \param TemplateLoc the location of the template name that started the
5354 /// template-id we are checking.
5356 /// \param RAngleLoc the location of the right angle bracket ('>') that
5357 /// terminates the template-id.
5359 /// \param Param the template template parameter whose default we are
5360 /// substituting into.
5362 /// \param Converted the list of template arguments provided for template
5363 /// parameters that precede \p Param in the template parameter list.
5364 /// \returns the substituted template argument, or NULL if an error occurred.
5365 static TypeSourceInfo
*SubstDefaultTemplateArgument(
5366 Sema
&SemaRef
, TemplateDecl
*Template
, SourceLocation TemplateLoc
,
5367 SourceLocation RAngleLoc
, TemplateTypeParmDecl
*Param
,
5368 ArrayRef
<TemplateArgument
> SugaredConverted
,
5369 ArrayRef
<TemplateArgument
> CanonicalConverted
) {
5370 TypeSourceInfo
*ArgType
= Param
->getDefaultArgumentInfo();
5372 // If the argument type is dependent, instantiate it now based
5373 // on the previously-computed template arguments.
5374 if (ArgType
->getType()->isInstantiationDependentType()) {
5375 Sema::InstantiatingTemplate
Inst(SemaRef
, TemplateLoc
, Param
, Template
,
5377 SourceRange(TemplateLoc
, RAngleLoc
));
5378 if (Inst
.isInvalid())
5381 // Only substitute for the innermost template argument list.
5382 MultiLevelTemplateArgumentList
TemplateArgLists(Template
, SugaredConverted
,
5384 for (unsigned i
= 0, e
= Param
->getDepth(); i
!= e
; ++i
)
5385 TemplateArgLists
.addOuterTemplateArguments(std::nullopt
);
5387 bool ForLambdaCallOperator
= false;
5388 if (const auto *Rec
= dyn_cast
<CXXRecordDecl
>(Template
->getDeclContext()))
5389 ForLambdaCallOperator
= Rec
->isLambda();
5390 Sema::ContextRAII
SavedContext(SemaRef
, Template
->getDeclContext(),
5391 !ForLambdaCallOperator
);
5393 SemaRef
.SubstType(ArgType
, TemplateArgLists
,
5394 Param
->getDefaultArgumentLoc(), Param
->getDeclName());
5400 /// Substitute template arguments into the default template argument for
5401 /// the given non-type template parameter.
5403 /// \param SemaRef the semantic analysis object for which we are performing
5404 /// the substitution.
5406 /// \param Template the template that we are synthesizing template arguments
5409 /// \param TemplateLoc the location of the template name that started the
5410 /// template-id we are checking.
5412 /// \param RAngleLoc the location of the right angle bracket ('>') that
5413 /// terminates the template-id.
5415 /// \param Param the non-type template parameter whose default we are
5416 /// substituting into.
5418 /// \param Converted the list of template arguments provided for template
5419 /// parameters that precede \p Param in the template parameter list.
5421 /// \returns the substituted template argument, or NULL if an error occurred.
5422 static ExprResult
SubstDefaultTemplateArgument(
5423 Sema
&SemaRef
, TemplateDecl
*Template
, SourceLocation TemplateLoc
,
5424 SourceLocation RAngleLoc
, NonTypeTemplateParmDecl
*Param
,
5425 ArrayRef
<TemplateArgument
> SugaredConverted
,
5426 ArrayRef
<TemplateArgument
> CanonicalConverted
) {
5427 Sema::InstantiatingTemplate
Inst(SemaRef
, TemplateLoc
, Param
, Template
,
5429 SourceRange(TemplateLoc
, RAngleLoc
));
5430 if (Inst
.isInvalid())
5433 // Only substitute for the innermost template argument list.
5434 MultiLevelTemplateArgumentList
TemplateArgLists(Template
, SugaredConverted
,
5436 for (unsigned i
= 0, e
= Param
->getDepth(); i
!= e
; ++i
)
5437 TemplateArgLists
.addOuterTemplateArguments(std::nullopt
);
5439 Sema::ContextRAII
SavedContext(SemaRef
, Template
->getDeclContext());
5440 EnterExpressionEvaluationContext
ConstantEvaluated(
5441 SemaRef
, Sema::ExpressionEvaluationContext::ConstantEvaluated
);
5442 return SemaRef
.SubstExpr(Param
->getDefaultArgument(), TemplateArgLists
);
5445 /// Substitute template arguments into the default template argument for
5446 /// the given template template parameter.
5448 /// \param SemaRef the semantic analysis object for which we are performing
5449 /// the substitution.
5451 /// \param Template the template that we are synthesizing template arguments
5454 /// \param TemplateLoc the location of the template name that started the
5455 /// template-id we are checking.
5457 /// \param RAngleLoc the location of the right angle bracket ('>') that
5458 /// terminates the template-id.
5460 /// \param Param the template template parameter whose default we are
5461 /// substituting into.
5463 /// \param Converted the list of template arguments provided for template
5464 /// parameters that precede \p Param in the template parameter list.
5466 /// \param QualifierLoc Will be set to the nested-name-specifier (with
5467 /// source-location information) that precedes the template name.
5469 /// \returns the substituted template argument, or NULL if an error occurred.
5470 static TemplateName
SubstDefaultTemplateArgument(
5471 Sema
&SemaRef
, TemplateDecl
*Template
, SourceLocation TemplateLoc
,
5472 SourceLocation RAngleLoc
, TemplateTemplateParmDecl
*Param
,
5473 ArrayRef
<TemplateArgument
> SugaredConverted
,
5474 ArrayRef
<TemplateArgument
> CanonicalConverted
,
5475 NestedNameSpecifierLoc
&QualifierLoc
) {
5476 Sema::InstantiatingTemplate
Inst(
5477 SemaRef
, TemplateLoc
, TemplateParameter(Param
), Template
,
5478 SugaredConverted
, SourceRange(TemplateLoc
, RAngleLoc
));
5479 if (Inst
.isInvalid())
5480 return TemplateName();
5482 // Only substitute for the innermost template argument list.
5483 MultiLevelTemplateArgumentList
TemplateArgLists(Template
, SugaredConverted
,
5485 for (unsigned i
= 0, e
= Param
->getDepth(); i
!= e
; ++i
)
5486 TemplateArgLists
.addOuterTemplateArguments(std::nullopt
);
5488 Sema::ContextRAII
SavedContext(SemaRef
, Template
->getDeclContext());
5489 // Substitute into the nested-name-specifier first,
5490 QualifierLoc
= Param
->getDefaultArgument().getTemplateQualifierLoc();
5493 SemaRef
.SubstNestedNameSpecifierLoc(QualifierLoc
, TemplateArgLists
);
5495 return TemplateName();
5498 return SemaRef
.SubstTemplateName(
5500 Param
->getDefaultArgument().getArgument().getAsTemplate(),
5501 Param
->getDefaultArgument().getTemplateNameLoc(),
5505 /// If the given template parameter has a default template
5506 /// argument, substitute into that default template argument and
5507 /// return the corresponding template argument.
5508 TemplateArgumentLoc
Sema::SubstDefaultTemplateArgumentIfAvailable(
5509 TemplateDecl
*Template
, SourceLocation TemplateLoc
,
5510 SourceLocation RAngleLoc
, Decl
*Param
,
5511 ArrayRef
<TemplateArgument
> SugaredConverted
,
5512 ArrayRef
<TemplateArgument
> CanonicalConverted
, bool &HasDefaultArg
) {
5513 HasDefaultArg
= false;
5515 if (TemplateTypeParmDecl
*TypeParm
= dyn_cast
<TemplateTypeParmDecl
>(Param
)) {
5516 if (!hasReachableDefaultArgument(TypeParm
))
5517 return TemplateArgumentLoc();
5519 HasDefaultArg
= true;
5520 TypeSourceInfo
*DI
= SubstDefaultTemplateArgument(
5521 *this, Template
, TemplateLoc
, RAngleLoc
, TypeParm
, SugaredConverted
,
5522 CanonicalConverted
);
5524 return TemplateArgumentLoc(TemplateArgument(DI
->getType()), DI
);
5526 return TemplateArgumentLoc();
5529 if (NonTypeTemplateParmDecl
*NonTypeParm
5530 = dyn_cast
<NonTypeTemplateParmDecl
>(Param
)) {
5531 if (!hasReachableDefaultArgument(NonTypeParm
))
5532 return TemplateArgumentLoc();
5534 HasDefaultArg
= true;
5535 ExprResult Arg
= SubstDefaultTemplateArgument(
5536 *this, Template
, TemplateLoc
, RAngleLoc
, NonTypeParm
, SugaredConverted
,
5537 CanonicalConverted
);
5538 if (Arg
.isInvalid())
5539 return TemplateArgumentLoc();
5541 Expr
*ArgE
= Arg
.getAs
<Expr
>();
5542 return TemplateArgumentLoc(TemplateArgument(ArgE
), ArgE
);
5545 TemplateTemplateParmDecl
*TempTempParm
5546 = cast
<TemplateTemplateParmDecl
>(Param
);
5547 if (!hasReachableDefaultArgument(TempTempParm
))
5548 return TemplateArgumentLoc();
5550 HasDefaultArg
= true;
5551 NestedNameSpecifierLoc QualifierLoc
;
5552 TemplateName TName
= SubstDefaultTemplateArgument(
5553 *this, Template
, TemplateLoc
, RAngleLoc
, TempTempParm
, SugaredConverted
,
5554 CanonicalConverted
, QualifierLoc
);
5556 return TemplateArgumentLoc();
5558 return TemplateArgumentLoc(
5559 Context
, TemplateArgument(TName
),
5560 TempTempParm
->getDefaultArgument().getTemplateQualifierLoc(),
5561 TempTempParm
->getDefaultArgument().getTemplateNameLoc());
5564 /// Convert a template-argument that we parsed as a type into a template, if
5565 /// possible. C++ permits injected-class-names to perform dual service as
5566 /// template template arguments and as template type arguments.
5567 static TemplateArgumentLoc
5568 convertTypeTemplateArgumentToTemplate(ASTContext
&Context
, TypeLoc TLoc
) {
5569 // Extract and step over any surrounding nested-name-specifier.
5570 NestedNameSpecifierLoc QualLoc
;
5571 if (auto ETLoc
= TLoc
.getAs
<ElaboratedTypeLoc
>()) {
5572 if (ETLoc
.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None
)
5573 return TemplateArgumentLoc();
5575 QualLoc
= ETLoc
.getQualifierLoc();
5576 TLoc
= ETLoc
.getNamedTypeLoc();
5578 // If this type was written as an injected-class-name, it can be used as a
5579 // template template argument.
5580 if (auto InjLoc
= TLoc
.getAs
<InjectedClassNameTypeLoc
>())
5581 return TemplateArgumentLoc(Context
, InjLoc
.getTypePtr()->getTemplateName(),
5582 QualLoc
, InjLoc
.getNameLoc());
5584 // If this type was written as an injected-class-name, it may have been
5585 // converted to a RecordType during instantiation. If the RecordType is
5586 // *not* wrapped in a TemplateSpecializationType and denotes a class
5587 // template specialization, it must have come from an injected-class-name.
5588 if (auto RecLoc
= TLoc
.getAs
<RecordTypeLoc
>())
5590 dyn_cast
<ClassTemplateSpecializationDecl
>(RecLoc
.getDecl()))
5591 return TemplateArgumentLoc(Context
,
5592 TemplateName(CTSD
->getSpecializedTemplate()),
5593 QualLoc
, RecLoc
.getNameLoc());
5595 return TemplateArgumentLoc();
5598 /// Check that the given template argument corresponds to the given
5599 /// template parameter.
5601 /// \param Param The template parameter against which the argument will be
5604 /// \param Arg The template argument, which may be updated due to conversions.
5606 /// \param Template The template in which the template argument resides.
5608 /// \param TemplateLoc The location of the template name for the template
5609 /// whose argument list we're matching.
5611 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
5612 /// the template argument list.
5614 /// \param ArgumentPackIndex The index into the argument pack where this
5615 /// argument will be placed. Only valid if the parameter is a parameter pack.
5617 /// \param Converted The checked, converted argument will be added to the
5618 /// end of this small vector.
5620 /// \param CTAK Describes how we arrived at this particular template argument:
5621 /// explicitly written, deduced, etc.
5623 /// \returns true on error, false otherwise.
5624 bool Sema::CheckTemplateArgument(
5625 NamedDecl
*Param
, TemplateArgumentLoc
&Arg
, NamedDecl
*Template
,
5626 SourceLocation TemplateLoc
, SourceLocation RAngleLoc
,
5627 unsigned ArgumentPackIndex
,
5628 SmallVectorImpl
<TemplateArgument
> &SugaredConverted
,
5629 SmallVectorImpl
<TemplateArgument
> &CanonicalConverted
,
5630 CheckTemplateArgumentKind CTAK
) {
5631 // Check template type parameters.
5632 if (TemplateTypeParmDecl
*TTP
= dyn_cast
<TemplateTypeParmDecl
>(Param
))
5633 return CheckTemplateTypeArgument(TTP
, Arg
, SugaredConverted
,
5634 CanonicalConverted
);
5636 // Check non-type template parameters.
5637 if (NonTypeTemplateParmDecl
*NTTP
=dyn_cast
<NonTypeTemplateParmDecl
>(Param
)) {
5638 // Do substitution on the type of the non-type template parameter
5639 // with the template arguments we've seen thus far. But if the
5640 // template has a dependent context then we cannot substitute yet.
5641 QualType NTTPType
= NTTP
->getType();
5642 if (NTTP
->isParameterPack() && NTTP
->isExpandedParameterPack())
5643 NTTPType
= NTTP
->getExpansionType(ArgumentPackIndex
);
5645 if (NTTPType
->isInstantiationDependentType() &&
5646 !isa
<TemplateTemplateParmDecl
>(Template
) &&
5647 !Template
->getDeclContext()->isDependentContext()) {
5648 // Do substitution on the type of the non-type template parameter.
5649 InstantiatingTemplate
Inst(*this, TemplateLoc
, Template
, NTTP
,
5651 SourceRange(TemplateLoc
, RAngleLoc
));
5652 if (Inst
.isInvalid())
5655 MultiLevelTemplateArgumentList
MLTAL(Template
, SugaredConverted
,
5657 // If the parameter is a pack expansion, expand this slice of the pack.
5658 if (auto *PET
= NTTPType
->getAs
<PackExpansionType
>()) {
5659 Sema::ArgumentPackSubstitutionIndexRAII
SubstIndex(*this,
5661 NTTPType
= SubstType(PET
->getPattern(), MLTAL
, NTTP
->getLocation(),
5662 NTTP
->getDeclName());
5664 NTTPType
= SubstType(NTTPType
, MLTAL
, NTTP
->getLocation(),
5665 NTTP
->getDeclName());
5668 // If that worked, check the non-type template parameter type
5670 if (!NTTPType
.isNull())
5671 NTTPType
= CheckNonTypeTemplateParameterType(NTTPType
,
5672 NTTP
->getLocation());
5673 if (NTTPType
.isNull())
5677 switch (Arg
.getArgument().getKind()) {
5678 case TemplateArgument::Null
:
5679 llvm_unreachable("Should never see a NULL template argument here");
5681 case TemplateArgument::Expression
: {
5682 Expr
*E
= Arg
.getArgument().getAsExpr();
5683 TemplateArgument SugaredResult
, CanonicalResult
;
5684 unsigned CurSFINAEErrors
= NumSFINAEErrors
;
5685 ExprResult Res
= CheckTemplateArgument(NTTP
, NTTPType
, E
, SugaredResult
,
5686 CanonicalResult
, CTAK
);
5687 if (Res
.isInvalid())
5689 // If the current template argument causes an error, give up now.
5690 if (CurSFINAEErrors
< NumSFINAEErrors
)
5693 // If the resulting expression is new, then use it in place of the
5694 // old expression in the template argument.
5695 if (Res
.get() != E
) {
5696 TemplateArgument
TA(Res
.get());
5697 Arg
= TemplateArgumentLoc(TA
, Res
.get());
5700 SugaredConverted
.push_back(SugaredResult
);
5701 CanonicalConverted
.push_back(CanonicalResult
);
5705 case TemplateArgument::Declaration
:
5706 case TemplateArgument::Integral
:
5707 case TemplateArgument::NullPtr
:
5708 // We've already checked this template argument, so just copy
5709 // it to the list of converted arguments.
5710 SugaredConverted
.push_back(Arg
.getArgument());
5711 CanonicalConverted
.push_back(
5712 Context
.getCanonicalTemplateArgument(Arg
.getArgument()));
5715 case TemplateArgument::Template
:
5716 case TemplateArgument::TemplateExpansion
:
5717 // We were given a template template argument. It may not be ill-formed;
5719 if (DependentTemplateName
*DTN
5720 = Arg
.getArgument().getAsTemplateOrTemplatePattern()
5721 .getAsDependentTemplateName()) {
5722 // We have a template argument such as \c T::template X, which we
5723 // parsed as a template template argument. However, since we now
5724 // know that we need a non-type template argument, convert this
5725 // template name into an expression.
5727 DeclarationNameInfo
NameInfo(DTN
->getIdentifier(),
5728 Arg
.getTemplateNameLoc());
5731 SS
.Adopt(Arg
.getTemplateQualifierLoc());
5732 // FIXME: the template-template arg was a DependentTemplateName,
5733 // so it was provided with a template keyword. However, its source
5734 // location is not stored in the template argument structure.
5735 SourceLocation TemplateKWLoc
;
5736 ExprResult E
= DependentScopeDeclRefExpr::Create(
5737 Context
, SS
.getWithLocInContext(Context
), TemplateKWLoc
, NameInfo
,
5740 // If we parsed the template argument as a pack expansion, create a
5741 // pack expansion expression.
5742 if (Arg
.getArgument().getKind() == TemplateArgument::TemplateExpansion
){
5743 E
= ActOnPackExpansion(E
.get(), Arg
.getTemplateEllipsisLoc());
5748 TemplateArgument SugaredResult
, CanonicalResult
;
5749 E
= CheckTemplateArgument(NTTP
, NTTPType
, E
.get(), SugaredResult
,
5750 CanonicalResult
, CTAK_Specified
);
5754 SugaredConverted
.push_back(SugaredResult
);
5755 CanonicalConverted
.push_back(CanonicalResult
);
5759 // We have a template argument that actually does refer to a class
5760 // template, alias template, or template template parameter, and
5761 // therefore cannot be a non-type template argument.
5762 Diag(Arg
.getLocation(), diag::err_template_arg_must_be_expr
)
5763 << Arg
.getSourceRange();
5765 Diag(Param
->getLocation(), diag::note_template_param_here
);
5768 case TemplateArgument::Type
: {
5769 // We have a non-type template parameter but the template
5770 // argument is a type.
5772 // C++ [temp.arg]p2:
5773 // In a template-argument, an ambiguity between a type-id and
5774 // an expression is resolved to a type-id, regardless of the
5775 // form of the corresponding template-parameter.
5777 // We warn specifically about this case, since it can be rather
5778 // confusing for users.
5779 QualType T
= Arg
.getArgument().getAsType();
5780 SourceRange SR
= Arg
.getSourceRange();
5781 if (T
->isFunctionType())
5782 Diag(SR
.getBegin(), diag::err_template_arg_nontype_ambig
) << SR
<< T
;
5784 Diag(SR
.getBegin(), diag::err_template_arg_must_be_expr
) << SR
;
5785 Diag(Param
->getLocation(), diag::note_template_param_here
);
5789 case TemplateArgument::Pack
:
5790 llvm_unreachable("Caller must expand template argument packs");
5797 // Check template template parameters.
5798 TemplateTemplateParmDecl
*TempParm
= cast
<TemplateTemplateParmDecl
>(Param
);
5800 TemplateParameterList
*Params
= TempParm
->getTemplateParameters();
5801 if (TempParm
->isExpandedParameterPack())
5802 Params
= TempParm
->getExpansionTemplateParameters(ArgumentPackIndex
);
5804 // Substitute into the template parameter list of the template
5805 // template parameter, since previously-supplied template arguments
5806 // may appear within the template template parameter.
5808 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5810 // Set up a template instantiation context.
5811 LocalInstantiationScope
Scope(*this);
5812 InstantiatingTemplate
Inst(*this, TemplateLoc
, Template
, TempParm
,
5814 SourceRange(TemplateLoc
, RAngleLoc
));
5815 if (Inst
.isInvalid())
5819 SubstTemplateParams(Params
, CurContext
,
5820 MultiLevelTemplateArgumentList(
5821 Template
, SugaredConverted
, /*Final=*/true),
5822 /*EvaluateConstraints=*/false);
5827 // C++1z [temp.local]p1: (DR1004)
5828 // When [the injected-class-name] is used [...] as a template-argument for
5829 // a template template-parameter [...] it refers to the class template
5831 if (Arg
.getArgument().getKind() == TemplateArgument::Type
) {
5832 TemplateArgumentLoc ConvertedArg
= convertTypeTemplateArgumentToTemplate(
5833 Context
, Arg
.getTypeSourceInfo()->getTypeLoc());
5834 if (!ConvertedArg
.getArgument().isNull())
5838 switch (Arg
.getArgument().getKind()) {
5839 case TemplateArgument::Null
:
5840 llvm_unreachable("Should never see a NULL template argument here");
5842 case TemplateArgument::Template
:
5843 case TemplateArgument::TemplateExpansion
:
5844 if (CheckTemplateTemplateArgument(TempParm
, Params
, Arg
))
5847 SugaredConverted
.push_back(Arg
.getArgument());
5848 CanonicalConverted
.push_back(
5849 Context
.getCanonicalTemplateArgument(Arg
.getArgument()));
5852 case TemplateArgument::Expression
:
5853 case TemplateArgument::Type
:
5854 // We have a template template parameter but the template
5855 // argument does not refer to a template.
5856 Diag(Arg
.getLocation(), diag::err_template_arg_must_be_template
)
5857 << getLangOpts().CPlusPlus11
;
5860 case TemplateArgument::Declaration
:
5861 llvm_unreachable("Declaration argument with template template parameter");
5862 case TemplateArgument::Integral
:
5863 llvm_unreachable("Integral argument with template template parameter");
5864 case TemplateArgument::NullPtr
:
5865 llvm_unreachable("Null pointer argument with template template parameter");
5867 case TemplateArgument::Pack
:
5868 llvm_unreachable("Caller must expand template argument packs");
5874 /// Diagnose a missing template argument.
5875 template<typename TemplateParmDecl
>
5876 static bool diagnoseMissingArgument(Sema
&S
, SourceLocation Loc
,
5878 const TemplateParmDecl
*D
,
5879 TemplateArgumentListInfo
&Args
) {
5880 // Dig out the most recent declaration of the template parameter; there may be
5881 // declarations of the template that are more recent than TD.
5882 D
= cast
<TemplateParmDecl
>(cast
<TemplateDecl
>(TD
->getMostRecentDecl())
5883 ->getTemplateParameters()
5884 ->getParam(D
->getIndex()));
5886 // If there's a default argument that's not reachable, diagnose that we're
5887 // missing a module import.
5888 llvm::SmallVector
<Module
*, 8> Modules
;
5889 if (D
->hasDefaultArgument() && !S
.hasReachableDefaultArgument(D
, &Modules
)) {
5890 S
.diagnoseMissingImport(Loc
, cast
<NamedDecl
>(TD
),
5891 D
->getDefaultArgumentLoc(), Modules
,
5892 Sema::MissingImportKind::DefaultArgument
,
5897 // FIXME: If there's a more recent default argument that *is* visible,
5898 // diagnose that it was declared too late.
5900 TemplateParameterList
*Params
= TD
->getTemplateParameters();
5902 S
.Diag(Loc
, diag::err_template_arg_list_different_arity
)
5903 << /*not enough args*/0
5904 << (int)S
.getTemplateNameKindForDiagnostics(TemplateName(TD
))
5906 S
.Diag(TD
->getLocation(), diag::note_template_decl_here
)
5907 << Params
->getSourceRange();
5911 /// Check that the given template argument list is well-formed
5912 /// for specializing the given template.
5913 bool Sema::CheckTemplateArgumentList(
5914 TemplateDecl
*Template
, SourceLocation TemplateLoc
,
5915 TemplateArgumentListInfo
&TemplateArgs
, bool PartialTemplateArgs
,
5916 SmallVectorImpl
<TemplateArgument
> &SugaredConverted
,
5917 SmallVectorImpl
<TemplateArgument
> &CanonicalConverted
,
5918 bool UpdateArgsWithConversions
, bool *ConstraintsNotSatisfied
) {
5920 if (ConstraintsNotSatisfied
)
5921 *ConstraintsNotSatisfied
= false;
5923 // Make a copy of the template arguments for processing. Only make the
5924 // changes at the end when successful in matching the arguments to the
5926 TemplateArgumentListInfo NewArgs
= TemplateArgs
;
5928 // Make sure we get the template parameter list from the most
5929 // recent declaration, since that is the only one that is guaranteed to
5930 // have all the default template argument information.
5931 TemplateParameterList
*Params
=
5932 cast
<TemplateDecl
>(Template
->getMostRecentDecl())
5933 ->getTemplateParameters();
5935 SourceLocation RAngleLoc
= NewArgs
.getRAngleLoc();
5937 // C++ [temp.arg]p1:
5938 // [...] The type and form of each template-argument specified in
5939 // a template-id shall match the type and form specified for the
5940 // corresponding parameter declared by the template in its
5941 // template-parameter-list.
5942 bool isTemplateTemplateParameter
= isa
<TemplateTemplateParmDecl
>(Template
);
5943 SmallVector
<TemplateArgument
, 2> SugaredArgumentPack
;
5944 SmallVector
<TemplateArgument
, 2> CanonicalArgumentPack
;
5945 unsigned ArgIdx
= 0, NumArgs
= NewArgs
.size();
5946 LocalInstantiationScope
InstScope(*this, true);
5947 for (TemplateParameterList::iterator Param
= Params
->begin(),
5948 ParamEnd
= Params
->end();
5949 Param
!= ParamEnd
; /* increment in loop */) {
5950 // If we have an expanded parameter pack, make sure we don't have too
5952 if (std::optional
<unsigned> Expansions
= getExpandedPackSize(*Param
)) {
5953 if (*Expansions
== SugaredArgumentPack
.size()) {
5954 // We're done with this parameter pack. Pack up its arguments and add
5955 // them to the list.
5956 SugaredConverted
.push_back(
5957 TemplateArgument::CreatePackCopy(Context
, SugaredArgumentPack
));
5958 SugaredArgumentPack
.clear();
5960 CanonicalConverted
.push_back(
5961 TemplateArgument::CreatePackCopy(Context
, CanonicalArgumentPack
));
5962 CanonicalArgumentPack
.clear();
5964 // This argument is assigned to the next parameter.
5967 } else if (ArgIdx
== NumArgs
&& !PartialTemplateArgs
) {
5968 // Not enough arguments for this parameter pack.
5969 Diag(TemplateLoc
, diag::err_template_arg_list_different_arity
)
5970 << /*not enough args*/0
5971 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template
))
5973 Diag(Template
->getLocation(), diag::note_template_decl_here
)
5974 << Params
->getSourceRange();
5979 if (ArgIdx
< NumArgs
) {
5980 // Check the template argument we were given.
5981 if (CheckTemplateArgument(*Param
, NewArgs
[ArgIdx
], Template
, TemplateLoc
,
5982 RAngleLoc
, SugaredArgumentPack
.size(),
5983 SugaredConverted
, CanonicalConverted
,
5987 CanonicalConverted
.back().setIsDefaulted(
5988 clang::isSubstitutedDefaultArgument(
5989 Context
, NewArgs
[ArgIdx
].getArgument(), *Param
,
5990 CanonicalConverted
, Params
->getDepth()));
5992 bool PackExpansionIntoNonPack
=
5993 NewArgs
[ArgIdx
].getArgument().isPackExpansion() &&
5994 (!(*Param
)->isTemplateParameterPack() || getExpandedPackSize(*Param
));
5995 if (PackExpansionIntoNonPack
&& (isa
<TypeAliasTemplateDecl
>(Template
) ||
5996 isa
<ConceptDecl
>(Template
))) {
5997 // Core issue 1430: we have a pack expansion as an argument to an
5998 // alias template, and it's not part of a parameter pack. This
5999 // can't be canonicalized, so reject it now.
6000 // As for concepts - we cannot normalize constraints where this
6001 // situation exists.
6002 Diag(NewArgs
[ArgIdx
].getLocation(),
6003 diag::err_template_expansion_into_fixed_list
)
6004 << (isa
<ConceptDecl
>(Template
) ? 1 : 0)
6005 << NewArgs
[ArgIdx
].getSourceRange();
6006 Diag((*Param
)->getLocation(), diag::note_template_param_here
);
6010 // We're now done with this argument.
6013 if ((*Param
)->isTemplateParameterPack()) {
6014 // The template parameter was a template parameter pack, so take the
6015 // deduced argument and place it on the argument pack. Note that we
6016 // stay on the same template parameter so that we can deduce more
6018 SugaredArgumentPack
.push_back(SugaredConverted
.pop_back_val());
6019 CanonicalArgumentPack
.push_back(CanonicalConverted
.pop_back_val());
6021 // Move to the next template parameter.
6025 // If we just saw a pack expansion into a non-pack, then directly convert
6026 // the remaining arguments, because we don't know what parameters they'll
6028 if (PackExpansionIntoNonPack
) {
6029 if (!SugaredArgumentPack
.empty()) {
6030 // If we were part way through filling in an expanded parameter pack,
6031 // fall back to just producing individual arguments.
6032 SugaredConverted
.insert(SugaredConverted
.end(),
6033 SugaredArgumentPack
.begin(),
6034 SugaredArgumentPack
.end());
6035 SugaredArgumentPack
.clear();
6037 CanonicalConverted
.insert(CanonicalConverted
.end(),
6038 CanonicalArgumentPack
.begin(),
6039 CanonicalArgumentPack
.end());
6040 CanonicalArgumentPack
.clear();
6043 while (ArgIdx
< NumArgs
) {
6044 const TemplateArgument
&Arg
= NewArgs
[ArgIdx
].getArgument();
6045 SugaredConverted
.push_back(Arg
);
6046 CanonicalConverted
.push_back(
6047 Context
.getCanonicalTemplateArgument(Arg
));
6057 // If we're checking a partial template argument list, we're done.
6058 if (PartialTemplateArgs
) {
6059 if ((*Param
)->isTemplateParameterPack() && !SugaredArgumentPack
.empty()) {
6060 SugaredConverted
.push_back(
6061 TemplateArgument::CreatePackCopy(Context
, SugaredArgumentPack
));
6062 CanonicalConverted
.push_back(
6063 TemplateArgument::CreatePackCopy(Context
, CanonicalArgumentPack
));
6068 // If we have a template parameter pack with no more corresponding
6069 // arguments, just break out now and we'll fill in the argument pack below.
6070 if ((*Param
)->isTemplateParameterPack()) {
6071 assert(!getExpandedPackSize(*Param
) &&
6072 "Should have dealt with this already");
6074 // A non-expanded parameter pack before the end of the parameter list
6075 // only occurs for an ill-formed template parameter list, unless we've
6076 // got a partial argument list for a function template, so just bail out.
6077 if (Param
+ 1 != ParamEnd
) {
6079 (Template
->getMostRecentDecl()->getKind() != Decl::Kind::Concept
) &&
6080 "Concept templates must have parameter packs at the end.");
6084 SugaredConverted
.push_back(
6085 TemplateArgument::CreatePackCopy(Context
, SugaredArgumentPack
));
6086 SugaredArgumentPack
.clear();
6088 CanonicalConverted
.push_back(
6089 TemplateArgument::CreatePackCopy(Context
, CanonicalArgumentPack
));
6090 CanonicalArgumentPack
.clear();
6096 // Check whether we have a default argument.
6097 TemplateArgumentLoc Arg
;
6099 // Retrieve the default template argument from the template
6100 // parameter. For each kind of template parameter, we substitute the
6101 // template arguments provided thus far and any "outer" template arguments
6102 // (when the template parameter was part of a nested template) into
6103 // the default argument.
6104 if (TemplateTypeParmDecl
*TTP
= dyn_cast
<TemplateTypeParmDecl
>(*Param
)) {
6105 if (!hasReachableDefaultArgument(TTP
))
6106 return diagnoseMissingArgument(*this, TemplateLoc
, Template
, TTP
,
6109 TypeSourceInfo
*ArgType
= SubstDefaultTemplateArgument(
6110 *this, Template
, TemplateLoc
, RAngleLoc
, TTP
, SugaredConverted
,
6111 CanonicalConverted
);
6115 Arg
= TemplateArgumentLoc(TemplateArgument(ArgType
->getType()),
6117 } else if (NonTypeTemplateParmDecl
*NTTP
6118 = dyn_cast
<NonTypeTemplateParmDecl
>(*Param
)) {
6119 if (!hasReachableDefaultArgument(NTTP
))
6120 return diagnoseMissingArgument(*this, TemplateLoc
, Template
, NTTP
,
6123 ExprResult E
= SubstDefaultTemplateArgument(
6124 *this, Template
, TemplateLoc
, RAngleLoc
, NTTP
, SugaredConverted
,
6125 CanonicalConverted
);
6129 Expr
*Ex
= E
.getAs
<Expr
>();
6130 Arg
= TemplateArgumentLoc(TemplateArgument(Ex
), Ex
);
6132 TemplateTemplateParmDecl
*TempParm
6133 = cast
<TemplateTemplateParmDecl
>(*Param
);
6135 if (!hasReachableDefaultArgument(TempParm
))
6136 return diagnoseMissingArgument(*this, TemplateLoc
, Template
, TempParm
,
6139 NestedNameSpecifierLoc QualifierLoc
;
6140 TemplateName Name
= SubstDefaultTemplateArgument(
6141 *this, Template
, TemplateLoc
, RAngleLoc
, TempParm
, SugaredConverted
,
6142 CanonicalConverted
, QualifierLoc
);
6146 Arg
= TemplateArgumentLoc(
6147 Context
, TemplateArgument(Name
), QualifierLoc
,
6148 TempParm
->getDefaultArgument().getTemplateNameLoc());
6151 // Introduce an instantiation record that describes where we are using
6152 // the default template argument. We're not actually instantiating a
6153 // template here, we just create this object to put a note into the
6155 InstantiatingTemplate
Inst(*this, RAngleLoc
, Template
, *Param
,
6157 SourceRange(TemplateLoc
, RAngleLoc
));
6158 if (Inst
.isInvalid())
6161 // Check the default template argument.
6162 if (CheckTemplateArgument(*Param
, Arg
, Template
, TemplateLoc
, RAngleLoc
, 0,
6163 SugaredConverted
, CanonicalConverted
,
6167 CanonicalConverted
.back().setIsDefaulted(true);
6169 // Core issue 150 (assumed resolution): if this is a template template
6170 // parameter, keep track of the default template arguments from the
6171 // template definition.
6172 if (isTemplateTemplateParameter
)
6173 NewArgs
.addArgument(Arg
);
6175 // Move to the next template parameter and argument.
6180 // If we're performing a partial argument substitution, allow any trailing
6181 // pack expansions; they might be empty. This can happen even if
6182 // PartialTemplateArgs is false (the list of arguments is complete but
6183 // still dependent).
6184 if (ArgIdx
< NumArgs
&& CurrentInstantiationScope
&&
6185 CurrentInstantiationScope
->getPartiallySubstitutedPack()) {
6186 while (ArgIdx
< NumArgs
&&
6187 NewArgs
[ArgIdx
].getArgument().isPackExpansion()) {
6188 const TemplateArgument
&Arg
= NewArgs
[ArgIdx
++].getArgument();
6189 SugaredConverted
.push_back(Arg
);
6190 CanonicalConverted
.push_back(Context
.getCanonicalTemplateArgument(Arg
));
6194 // If we have any leftover arguments, then there were too many arguments.
6195 // Complain and fail.
6196 if (ArgIdx
< NumArgs
) {
6197 Diag(TemplateLoc
, diag::err_template_arg_list_different_arity
)
6198 << /*too many args*/1
6199 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template
))
6201 << SourceRange(NewArgs
[ArgIdx
].getLocation(), NewArgs
.getRAngleLoc());
6202 Diag(Template
->getLocation(), diag::note_template_decl_here
)
6203 << Params
->getSourceRange();
6207 // No problems found with the new argument list, propagate changes back
6209 if (UpdateArgsWithConversions
)
6210 TemplateArgs
= std::move(NewArgs
);
6212 if (!PartialTemplateArgs
) {
6213 TemplateArgumentList
StackTemplateArgs(TemplateArgumentList::OnStack
,
6214 CanonicalConverted
);
6215 // Setup the context/ThisScope for the case where we are needing to
6216 // re-instantiate constraints outside of normal instantiation.
6217 DeclContext
*NewContext
= Template
->getDeclContext();
6219 // If this template is in a template, make sure we extract the templated
6221 if (auto *TD
= dyn_cast
<TemplateDecl
>(NewContext
))
6222 NewContext
= Decl::castToDeclContext(TD
->getTemplatedDecl());
6223 auto *RD
= dyn_cast
<CXXRecordDecl
>(NewContext
);
6225 Qualifiers ThisQuals
;
6226 if (const auto *Method
=
6227 dyn_cast_or_null
<CXXMethodDecl
>(Template
->getTemplatedDecl()))
6228 ThisQuals
= Method
->getMethodQualifiers();
6230 ContextRAII
Context(*this, NewContext
);
6231 CXXThisScopeRAII(*this, RD
, ThisQuals
, RD
!= nullptr);
6233 MultiLevelTemplateArgumentList MLTAL
= getTemplateInstantiationArgs(
6234 Template
, NewContext
, /*Final=*/false, &StackTemplateArgs
,
6235 /*RelativeToPrimary=*/true,
6236 /*Pattern=*/nullptr,
6237 /*ForConceptInstantiation=*/true);
6238 if (EnsureTemplateArgumentListConstraints(
6240 SourceRange(TemplateLoc
, TemplateArgs
.getRAngleLoc()))) {
6241 if (ConstraintsNotSatisfied
)
6242 *ConstraintsNotSatisfied
= true;
6251 class UnnamedLocalNoLinkageFinder
6252 : public TypeVisitor
<UnnamedLocalNoLinkageFinder
, bool>
6257 typedef TypeVisitor
<UnnamedLocalNoLinkageFinder
, bool> inherited
;
6260 UnnamedLocalNoLinkageFinder(Sema
&S
, SourceRange SR
) : S(S
), SR(SR
) { }
6262 bool Visit(QualType T
) {
6263 return T
.isNull() ? false : inherited::Visit(T
.getTypePtr());
6266 #define TYPE(Class, Parent) \
6267 bool Visit##Class##Type(const Class##Type *);
6268 #define ABSTRACT_TYPE(Class, Parent) \
6269 bool Visit##Class##Type(const Class##Type *) { return false; }
6270 #define NON_CANONICAL_TYPE(Class, Parent) \
6271 bool Visit##Class##Type(const Class##Type *) { return false; }
6272 #include "clang/AST/TypeNodes.inc"
6274 bool VisitTagDecl(const TagDecl
*Tag
);
6275 bool VisitNestedNameSpecifier(NestedNameSpecifier
*NNS
);
6277 } // end anonymous namespace
6279 bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType
*) {
6283 bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType
* T
) {
6284 return Visit(T
->getElementType());
6287 bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType
* T
) {
6288 return Visit(T
->getPointeeType());
6291 bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
6292 const BlockPointerType
* T
) {
6293 return Visit(T
->getPointeeType());
6296 bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
6297 const LValueReferenceType
* T
) {
6298 return Visit(T
->getPointeeType());
6301 bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
6302 const RValueReferenceType
* T
) {
6303 return Visit(T
->getPointeeType());
6306 bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
6307 const MemberPointerType
* T
) {
6308 return Visit(T
->getPointeeType()) || Visit(QualType(T
->getClass(), 0));
6311 bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
6312 const ConstantArrayType
* T
) {
6313 return Visit(T
->getElementType());
6316 bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
6317 const IncompleteArrayType
* T
) {
6318 return Visit(T
->getElementType());
6321 bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
6322 const VariableArrayType
* T
) {
6323 return Visit(T
->getElementType());
6326 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
6327 const DependentSizedArrayType
* T
) {
6328 return Visit(T
->getElementType());
6331 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
6332 const DependentSizedExtVectorType
* T
) {
6333 return Visit(T
->getElementType());
6336 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
6337 const DependentSizedMatrixType
*T
) {
6338 return Visit(T
->getElementType());
6341 bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
6342 const DependentAddressSpaceType
*T
) {
6343 return Visit(T
->getPointeeType());
6346 bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType
* T
) {
6347 return Visit(T
->getElementType());
6350 bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
6351 const DependentVectorType
*T
) {
6352 return Visit(T
->getElementType());
6355 bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType
* T
) {
6356 return Visit(T
->getElementType());
6359 bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
6360 const ConstantMatrixType
*T
) {
6361 return Visit(T
->getElementType());
6364 bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
6365 const FunctionProtoType
* T
) {
6366 for (const auto &A
: T
->param_types()) {
6371 return Visit(T
->getReturnType());
6374 bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
6375 const FunctionNoProtoType
* T
) {
6376 return Visit(T
->getReturnType());
6379 bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
6380 const UnresolvedUsingType
*) {
6384 bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType
*) {
6388 bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType
* T
) {
6389 return Visit(T
->getUnmodifiedType());
6392 bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType
*) {
6396 bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
6397 const UnaryTransformType
*) {
6401 bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType
*T
) {
6402 return Visit(T
->getDeducedType());
6405 bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
6406 const DeducedTemplateSpecializationType
*T
) {
6407 return Visit(T
->getDeducedType());
6410 bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType
* T
) {
6411 return VisitTagDecl(T
->getDecl());
6414 bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType
* T
) {
6415 return VisitTagDecl(T
->getDecl());
6418 bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
6419 const TemplateTypeParmType
*) {
6423 bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
6424 const SubstTemplateTypeParmPackType
*) {
6428 bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
6429 const TemplateSpecializationType
*) {
6433 bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
6434 const InjectedClassNameType
* T
) {
6435 return VisitTagDecl(T
->getDecl());
6438 bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6439 const DependentNameType
* T
) {
6440 return VisitNestedNameSpecifier(T
->getQualifier());
6443 bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
6444 const DependentTemplateSpecializationType
* T
) {
6445 if (auto *Q
= T
->getQualifier())
6446 return VisitNestedNameSpecifier(Q
);
6450 bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6451 const PackExpansionType
* T
) {
6452 return Visit(T
->getPattern());
6455 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType
*) {
6459 bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
6460 const ObjCInterfaceType
*) {
6464 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
6465 const ObjCObjectPointerType
*) {
6469 bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType
* T
) {
6470 return Visit(T
->getValueType());
6473 bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType
* T
) {
6477 bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType
*T
) {
6481 bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6482 const DependentBitIntType
*T
) {
6486 bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl
*Tag
) {
6487 if (Tag
->getDeclContext()->isFunctionOrMethod()) {
6488 S
.Diag(SR
.getBegin(),
6489 S
.getLangOpts().CPlusPlus11
?
6490 diag::warn_cxx98_compat_template_arg_local_type
:
6491 diag::ext_template_arg_local_type
)
6492 << S
.Context
.getTypeDeclType(Tag
) << SR
;
6496 if (!Tag
->hasNameForLinkage()) {
6497 S
.Diag(SR
.getBegin(),
6498 S
.getLangOpts().CPlusPlus11
?
6499 diag::warn_cxx98_compat_template_arg_unnamed_type
:
6500 diag::ext_template_arg_unnamed_type
) << SR
;
6501 S
.Diag(Tag
->getLocation(), diag::note_template_unnamed_type_here
);
6508 bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6509 NestedNameSpecifier
*NNS
) {
6511 if (NNS
->getPrefix() && VisitNestedNameSpecifier(NNS
->getPrefix()))
6514 switch (NNS
->getKind()) {
6515 case NestedNameSpecifier::Identifier
:
6516 case NestedNameSpecifier::Namespace
:
6517 case NestedNameSpecifier::NamespaceAlias
:
6518 case NestedNameSpecifier::Global
:
6519 case NestedNameSpecifier::Super
:
6522 case NestedNameSpecifier::TypeSpec
:
6523 case NestedNameSpecifier::TypeSpecWithTemplate
:
6524 return Visit(QualType(NNS
->getAsType(), 0));
6526 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6529 /// Check a template argument against its corresponding
6530 /// template type parameter.
6532 /// This routine implements the semantics of C++ [temp.arg.type]. It
6533 /// returns true if an error occurred, and false otherwise.
6534 bool Sema::CheckTemplateArgument(TypeSourceInfo
*ArgInfo
) {
6535 assert(ArgInfo
&& "invalid TypeSourceInfo");
6536 QualType Arg
= ArgInfo
->getType();
6537 SourceRange SR
= ArgInfo
->getTypeLoc().getSourceRange();
6538 QualType CanonArg
= Context
.getCanonicalType(Arg
);
6540 if (CanonArg
->isVariablyModifiedType()) {
6541 return Diag(SR
.getBegin(), diag::err_variably_modified_template_arg
) << Arg
;
6542 } else if (Context
.hasSameUnqualifiedType(Arg
, Context
.OverloadTy
)) {
6543 return Diag(SR
.getBegin(), diag::err_template_arg_overload_type
) << SR
;
6546 // C++03 [temp.arg.type]p2:
6547 // A local type, a type with no linkage, an unnamed type or a type
6548 // compounded from any of these types shall not be used as a
6549 // template-argument for a template type-parameter.
6551 // C++11 allows these, and even in C++03 we allow them as an extension with
6553 if (LangOpts
.CPlusPlus11
|| CanonArg
->hasUnnamedOrLocalType()) {
6554 UnnamedLocalNoLinkageFinder
Finder(*this, SR
);
6555 (void)Finder
.Visit(CanonArg
);
6561 enum NullPointerValueKind
{
6567 /// Determine whether the given template argument is a null pointer
6568 /// value of the appropriate type.
6569 static NullPointerValueKind
6570 isNullPointerValueTemplateArgument(Sema
&S
, NonTypeTemplateParmDecl
*Param
,
6571 QualType ParamType
, Expr
*Arg
,
6572 Decl
*Entity
= nullptr) {
6573 if (Arg
->isValueDependent() || Arg
->isTypeDependent())
6574 return NPV_NotNullPointer
;
6576 // dllimport'd entities aren't constant but are available inside of template
6578 if (Entity
&& Entity
->hasAttr
<DLLImportAttr
>())
6579 return NPV_NotNullPointer
;
6581 if (!S
.isCompleteType(Arg
->getExprLoc(), ParamType
))
6583 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6585 if (!S
.getLangOpts().CPlusPlus11
)
6586 return NPV_NotNullPointer
;
6588 // Determine whether we have a constant expression.
6589 ExprResult ArgRV
= S
.DefaultFunctionArrayConversion(Arg
);
6590 if (ArgRV
.isInvalid())
6594 Expr::EvalResult EvalResult
;
6595 SmallVector
<PartialDiagnosticAt
, 8> Notes
;
6596 EvalResult
.Diag
= &Notes
;
6597 if (!Arg
->EvaluateAsRValue(EvalResult
, S
.Context
) ||
6598 EvalResult
.HasSideEffects
) {
6599 SourceLocation DiagLoc
= Arg
->getExprLoc();
6601 // If our only note is the usual "invalid subexpression" note, just point
6602 // the caret at its location rather than producing an essentially
6604 if (Notes
.size() == 1 && Notes
[0].second
.getDiagID() ==
6605 diag::note_invalid_subexpr_in_const_expr
) {
6606 DiagLoc
= Notes
[0].first
;
6610 S
.Diag(DiagLoc
, diag::err_template_arg_not_address_constant
)
6611 << Arg
->getType() << Arg
->getSourceRange();
6612 for (unsigned I
= 0, N
= Notes
.size(); I
!= N
; ++I
)
6613 S
.Diag(Notes
[I
].first
, Notes
[I
].second
);
6615 S
.Diag(Param
->getLocation(), diag::note_template_param_here
);
6619 // C++11 [temp.arg.nontype]p1:
6620 // - an address constant expression of type std::nullptr_t
6621 if (Arg
->getType()->isNullPtrType())
6622 return NPV_NullPointer
;
6624 // - a constant expression that evaluates to a null pointer value (4.10); or
6625 // - a constant expression that evaluates to a null member pointer value
6627 if ((EvalResult
.Val
.isLValue() && EvalResult
.Val
.isNullPointer()) ||
6628 (EvalResult
.Val
.isMemberPointer() &&
6629 !EvalResult
.Val
.getMemberPointerDecl())) {
6630 // If our expression has an appropriate type, we've succeeded.
6631 bool ObjCLifetimeConversion
;
6632 if (S
.Context
.hasSameUnqualifiedType(Arg
->getType(), ParamType
) ||
6633 S
.IsQualificationConversion(Arg
->getType(), ParamType
, false,
6634 ObjCLifetimeConversion
))
6635 return NPV_NullPointer
;
6637 // The types didn't match, but we know we got a null pointer; complain,
6638 // then recover as if the types were correct.
6639 S
.Diag(Arg
->getExprLoc(), diag::err_template_arg_wrongtype_null_constant
)
6640 << Arg
->getType() << ParamType
<< Arg
->getSourceRange();
6641 S
.Diag(Param
->getLocation(), diag::note_template_param_here
);
6642 return NPV_NullPointer
;
6645 if (EvalResult
.Val
.isLValue() && !EvalResult
.Val
.getLValueBase()) {
6646 // We found a pointer that isn't null, but doesn't refer to an object.
6647 // We could just return NPV_NotNullPointer, but we can print a better
6648 // message with the information we have here.
6649 S
.Diag(Arg
->getExprLoc(), diag::err_template_arg_invalid
)
6650 << EvalResult
.Val
.getAsString(S
.Context
, ParamType
);
6651 S
.Diag(Param
->getLocation(), diag::note_template_param_here
);
6655 // If we don't have a null pointer value, but we do have a NULL pointer
6656 // constant, suggest a cast to the appropriate type.
6657 if (Arg
->isNullPointerConstant(S
.Context
, Expr::NPC_NeverValueDependent
)) {
6658 std::string Code
= "static_cast<" + ParamType
.getAsString() + ">(";
6659 S
.Diag(Arg
->getExprLoc(), diag::err_template_arg_untyped_null_constant
)
6660 << ParamType
<< FixItHint::CreateInsertion(Arg
->getBeginLoc(), Code
)
6661 << FixItHint::CreateInsertion(S
.getLocForEndOfToken(Arg
->getEndLoc()),
6663 S
.Diag(Param
->getLocation(), diag::note_template_param_here
);
6664 return NPV_NullPointer
;
6667 // FIXME: If we ever want to support general, address-constant expressions
6668 // as non-type template arguments, we should return the ExprResult here to
6669 // be interpreted by the caller.
6670 return NPV_NotNullPointer
;
6673 /// Checks whether the given template argument is compatible with its
6674 /// template parameter.
6675 static bool CheckTemplateArgumentIsCompatibleWithParameter(
6676 Sema
&S
, NonTypeTemplateParmDecl
*Param
, QualType ParamType
, Expr
*ArgIn
,
6677 Expr
*Arg
, QualType ArgType
) {
6678 bool ObjCLifetimeConversion
;
6679 if (ParamType
->isPointerType() &&
6680 !ParamType
->castAs
<PointerType
>()->getPointeeType()->isFunctionType() &&
6681 S
.IsQualificationConversion(ArgType
, ParamType
, false,
6682 ObjCLifetimeConversion
)) {
6683 // For pointer-to-object types, qualification conversions are
6686 if (const ReferenceType
*ParamRef
= ParamType
->getAs
<ReferenceType
>()) {
6687 if (!ParamRef
->getPointeeType()->isFunctionType()) {
6688 // C++ [temp.arg.nontype]p5b3:
6689 // For a non-type template-parameter of type reference to
6690 // object, no conversions apply. The type referred to by the
6691 // reference may be more cv-qualified than the (otherwise
6692 // identical) type of the template- argument. The
6693 // template-parameter is bound directly to the
6694 // template-argument, which shall be an lvalue.
6696 // FIXME: Other qualifiers?
6697 unsigned ParamQuals
= ParamRef
->getPointeeType().getCVRQualifiers();
6698 unsigned ArgQuals
= ArgType
.getCVRQualifiers();
6700 if ((ParamQuals
| ArgQuals
) != ParamQuals
) {
6701 S
.Diag(Arg
->getBeginLoc(),
6702 diag::err_template_arg_ref_bind_ignores_quals
)
6703 << ParamType
<< Arg
->getType() << Arg
->getSourceRange();
6704 S
.Diag(Param
->getLocation(), diag::note_template_param_here
);
6710 // At this point, the template argument refers to an object or
6711 // function with external linkage. We now need to check whether the
6712 // argument and parameter types are compatible.
6713 if (!S
.Context
.hasSameUnqualifiedType(ArgType
,
6714 ParamType
.getNonReferenceType())) {
6715 // We can't perform this conversion or binding.
6716 if (ParamType
->isReferenceType())
6717 S
.Diag(Arg
->getBeginLoc(), diag::err_template_arg_no_ref_bind
)
6718 << ParamType
<< ArgIn
->getType() << Arg
->getSourceRange();
6720 S
.Diag(Arg
->getBeginLoc(), diag::err_template_arg_not_convertible
)
6721 << ArgIn
->getType() << ParamType
<< Arg
->getSourceRange();
6722 S
.Diag(Param
->getLocation(), diag::note_template_param_here
);
6730 /// Checks whether the given template argument is the address
6731 /// of an object or function according to C++ [temp.arg.nontype]p1.
6732 static bool CheckTemplateArgumentAddressOfObjectOrFunction(
6733 Sema
&S
, NonTypeTemplateParmDecl
*Param
, QualType ParamType
, Expr
*ArgIn
,
6734 TemplateArgument
&SugaredConverted
, TemplateArgument
&CanonicalConverted
) {
6735 bool Invalid
= false;
6737 QualType ArgType
= Arg
->getType();
6739 bool AddressTaken
= false;
6740 SourceLocation AddrOpLoc
;
6741 if (S
.getLangOpts().MicrosoftExt
) {
6742 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6743 // dereference and address-of operators.
6744 Arg
= Arg
->IgnoreParenCasts();
6746 bool ExtWarnMSTemplateArg
= false;
6747 UnaryOperatorKind FirstOpKind
;
6748 SourceLocation FirstOpLoc
;
6749 while (UnaryOperator
*UnOp
= dyn_cast
<UnaryOperator
>(Arg
)) {
6750 UnaryOperatorKind UnOpKind
= UnOp
->getOpcode();
6751 if (UnOpKind
== UO_Deref
)
6752 ExtWarnMSTemplateArg
= true;
6753 if (UnOpKind
== UO_AddrOf
|| UnOpKind
== UO_Deref
) {
6754 Arg
= UnOp
->getSubExpr()->IgnoreParenCasts();
6755 if (!AddrOpLoc
.isValid()) {
6756 FirstOpKind
= UnOpKind
;
6757 FirstOpLoc
= UnOp
->getOperatorLoc();
6762 if (FirstOpLoc
.isValid()) {
6763 if (ExtWarnMSTemplateArg
)
6764 S
.Diag(ArgIn
->getBeginLoc(), diag::ext_ms_deref_template_argument
)
6765 << ArgIn
->getSourceRange();
6767 if (FirstOpKind
== UO_AddrOf
)
6768 AddressTaken
= true;
6769 else if (Arg
->getType()->isPointerType()) {
6770 // We cannot let pointers get dereferenced here, that is obviously not a
6771 // constant expression.
6772 assert(FirstOpKind
== UO_Deref
);
6773 S
.Diag(Arg
->getBeginLoc(), diag::err_template_arg_not_decl_ref
)
6774 << Arg
->getSourceRange();
6778 // See through any implicit casts we added to fix the type.
6779 Arg
= Arg
->IgnoreImpCasts();
6781 // C++ [temp.arg.nontype]p1:
6783 // A template-argument for a non-type, non-template
6784 // template-parameter shall be one of: [...]
6786 // -- the address of an object or function with external
6787 // linkage, including function templates and function
6788 // template-ids but excluding non-static class members,
6789 // expressed as & id-expression where the & is optional if
6790 // the name refers to a function or array, or if the
6791 // corresponding template-parameter is a reference; or
6793 // In C++98/03 mode, give an extension warning on any extra parentheses.
6794 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6795 bool ExtraParens
= false;
6796 while (ParenExpr
*Parens
= dyn_cast
<ParenExpr
>(Arg
)) {
6797 if (!Invalid
&& !ExtraParens
) {
6798 S
.Diag(Arg
->getBeginLoc(),
6799 S
.getLangOpts().CPlusPlus11
6800 ? diag::warn_cxx98_compat_template_arg_extra_parens
6801 : diag::ext_template_arg_extra_parens
)
6802 << Arg
->getSourceRange();
6806 Arg
= Parens
->getSubExpr();
6809 while (SubstNonTypeTemplateParmExpr
*subst
=
6810 dyn_cast
<SubstNonTypeTemplateParmExpr
>(Arg
))
6811 Arg
= subst
->getReplacement()->IgnoreImpCasts();
6813 if (UnaryOperator
*UnOp
= dyn_cast
<UnaryOperator
>(Arg
)) {
6814 if (UnOp
->getOpcode() == UO_AddrOf
) {
6815 Arg
= UnOp
->getSubExpr();
6816 AddressTaken
= true;
6817 AddrOpLoc
= UnOp
->getOperatorLoc();
6821 while (SubstNonTypeTemplateParmExpr
*subst
=
6822 dyn_cast
<SubstNonTypeTemplateParmExpr
>(Arg
))
6823 Arg
= subst
->getReplacement()->IgnoreImpCasts();
6826 ValueDecl
*Entity
= nullptr;
6827 if (DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(Arg
))
6828 Entity
= DRE
->getDecl();
6829 else if (CXXUuidofExpr
*CUE
= dyn_cast
<CXXUuidofExpr
>(Arg
))
6830 Entity
= CUE
->getGuidDecl();
6832 // If our parameter has pointer type, check for a null template value.
6833 if (ParamType
->isPointerType() || ParamType
->isNullPtrType()) {
6834 switch (isNullPointerValueTemplateArgument(S
, Param
, ParamType
, ArgIn
,
6836 case NPV_NullPointer
:
6837 S
.Diag(Arg
->getExprLoc(), diag::warn_cxx98_compat_template_arg_null
);
6838 SugaredConverted
= TemplateArgument(ParamType
,
6839 /*isNullPtr=*/true);
6840 CanonicalConverted
=
6841 TemplateArgument(S
.Context
.getCanonicalType(ParamType
),
6842 /*isNullPtr=*/true);
6848 case NPV_NotNullPointer
:
6853 // Stop checking the precise nature of the argument if it is value dependent,
6854 // it should be checked when instantiated.
6855 if (Arg
->isValueDependent()) {
6856 SugaredConverted
= TemplateArgument(ArgIn
);
6857 CanonicalConverted
=
6858 S
.Context
.getCanonicalTemplateArgument(SugaredConverted
);
6863 S
.Diag(Arg
->getBeginLoc(), diag::err_template_arg_not_decl_ref
)
6864 << Arg
->getSourceRange();
6865 S
.Diag(Param
->getLocation(), diag::note_template_param_here
);
6869 // Cannot refer to non-static data members
6870 if (isa
<FieldDecl
>(Entity
) || isa
<IndirectFieldDecl
>(Entity
)) {
6871 S
.Diag(Arg
->getBeginLoc(), diag::err_template_arg_field
)
6872 << Entity
<< Arg
->getSourceRange();
6873 S
.Diag(Param
->getLocation(), diag::note_template_param_here
);
6877 // Cannot refer to non-static member functions
6878 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(Entity
)) {
6879 if (!Method
->isStatic()) {
6880 S
.Diag(Arg
->getBeginLoc(), diag::err_template_arg_method
)
6881 << Method
<< Arg
->getSourceRange();
6882 S
.Diag(Param
->getLocation(), diag::note_template_param_here
);
6887 FunctionDecl
*Func
= dyn_cast
<FunctionDecl
>(Entity
);
6888 VarDecl
*Var
= dyn_cast
<VarDecl
>(Entity
);
6889 MSGuidDecl
*Guid
= dyn_cast
<MSGuidDecl
>(Entity
);
6891 // A non-type template argument must refer to an object or function.
6892 if (!Func
&& !Var
&& !Guid
) {
6893 // We found something, but we don't know specifically what it is.
6894 S
.Diag(Arg
->getBeginLoc(), diag::err_template_arg_not_object_or_func
)
6895 << Arg
->getSourceRange();
6896 S
.Diag(Entity
->getLocation(), diag::note_template_arg_refers_here
);
6900 // Address / reference template args must have external linkage in C++98.
6901 if (Entity
->getFormalLinkage() == InternalLinkage
) {
6902 S
.Diag(Arg
->getBeginLoc(),
6903 S
.getLangOpts().CPlusPlus11
6904 ? diag::warn_cxx98_compat_template_arg_object_internal
6905 : diag::ext_template_arg_object_internal
)
6906 << !Func
<< Entity
<< Arg
->getSourceRange();
6907 S
.Diag(Entity
->getLocation(), diag::note_template_arg_internal_object
)
6909 } else if (!Entity
->hasLinkage()) {
6910 S
.Diag(Arg
->getBeginLoc(), diag::err_template_arg_object_no_linkage
)
6911 << !Func
<< Entity
<< Arg
->getSourceRange();
6912 S
.Diag(Entity
->getLocation(), diag::note_template_arg_internal_object
)
6918 // A value of reference type is not an object.
6919 if (Var
->getType()->isReferenceType()) {
6920 S
.Diag(Arg
->getBeginLoc(), diag::err_template_arg_reference_var
)
6921 << Var
->getType() << Arg
->getSourceRange();
6922 S
.Diag(Param
->getLocation(), diag::note_template_param_here
);
6926 // A template argument must have static storage duration.
6927 if (Var
->getTLSKind()) {
6928 S
.Diag(Arg
->getBeginLoc(), diag::err_template_arg_thread_local
)
6929 << Arg
->getSourceRange();
6930 S
.Diag(Var
->getLocation(), diag::note_template_arg_refers_here
);
6935 if (AddressTaken
&& ParamType
->isReferenceType()) {
6936 // If we originally had an address-of operator, but the
6937 // parameter has reference type, complain and (if things look
6938 // like they will work) drop the address-of operator.
6939 if (!S
.Context
.hasSameUnqualifiedType(Entity
->getType(),
6940 ParamType
.getNonReferenceType())) {
6941 S
.Diag(AddrOpLoc
, diag::err_template_arg_address_of_non_pointer
)
6943 S
.Diag(Param
->getLocation(), diag::note_template_param_here
);
6947 S
.Diag(AddrOpLoc
, diag::err_template_arg_address_of_non_pointer
)
6949 << FixItHint::CreateRemoval(AddrOpLoc
);
6950 S
.Diag(Param
->getLocation(), diag::note_template_param_here
);
6952 ArgType
= Entity
->getType();
6955 // If the template parameter has pointer type, either we must have taken the
6956 // address or the argument must decay to a pointer.
6957 if (!AddressTaken
&& ParamType
->isPointerType()) {
6959 // Function-to-pointer decay.
6960 ArgType
= S
.Context
.getPointerType(Func
->getType());
6961 } else if (Entity
->getType()->isArrayType()) {
6962 // Array-to-pointer decay.
6963 ArgType
= S
.Context
.getArrayDecayedType(Entity
->getType());
6965 // If the template parameter has pointer type but the address of
6966 // this object was not taken, complain and (possibly) recover by
6967 // taking the address of the entity.
6968 ArgType
= S
.Context
.getPointerType(Entity
->getType());
6969 if (!S
.Context
.hasSameUnqualifiedType(ArgType
, ParamType
)) {
6970 S
.Diag(Arg
->getBeginLoc(), diag::err_template_arg_not_address_of
)
6972 S
.Diag(Param
->getLocation(), diag::note_template_param_here
);
6976 S
.Diag(Arg
->getBeginLoc(), diag::err_template_arg_not_address_of
)
6977 << ParamType
<< FixItHint::CreateInsertion(Arg
->getBeginLoc(), "&");
6979 S
.Diag(Param
->getLocation(), diag::note_template_param_here
);
6983 if (CheckTemplateArgumentIsCompatibleWithParameter(S
, Param
, ParamType
, ArgIn
,
6987 // Create the template argument.
6988 SugaredConverted
= TemplateArgument(Entity
, ParamType
);
6989 CanonicalConverted
=
6990 TemplateArgument(cast
<ValueDecl
>(Entity
->getCanonicalDecl()),
6991 S
.Context
.getCanonicalType(ParamType
));
6992 S
.MarkAnyDeclReferenced(Arg
->getBeginLoc(), Entity
, false);
6996 /// Checks whether the given template argument is a pointer to
6997 /// member constant according to C++ [temp.arg.nontype]p1.
6999 CheckTemplateArgumentPointerToMember(Sema
&S
, NonTypeTemplateParmDecl
*Param
,
7000 QualType ParamType
, Expr
*&ResultArg
,
7001 TemplateArgument
&SugaredConverted
,
7002 TemplateArgument
&CanonicalConverted
) {
7003 bool Invalid
= false;
7005 Expr
*Arg
= ResultArg
;
7006 bool ObjCLifetimeConversion
;
7008 // C++ [temp.arg.nontype]p1:
7010 // A template-argument for a non-type, non-template
7011 // template-parameter shall be one of: [...]
7013 // -- a pointer to member expressed as described in 5.3.1.
7014 DeclRefExpr
*DRE
= nullptr;
7016 // In C++98/03 mode, give an extension warning on any extra parentheses.
7017 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
7018 bool ExtraParens
= false;
7019 while (ParenExpr
*Parens
= dyn_cast
<ParenExpr
>(Arg
)) {
7020 if (!Invalid
&& !ExtraParens
) {
7021 S
.Diag(Arg
->getBeginLoc(),
7022 S
.getLangOpts().CPlusPlus11
7023 ? diag::warn_cxx98_compat_template_arg_extra_parens
7024 : diag::ext_template_arg_extra_parens
)
7025 << Arg
->getSourceRange();
7029 Arg
= Parens
->getSubExpr();
7032 while (SubstNonTypeTemplateParmExpr
*subst
=
7033 dyn_cast
<SubstNonTypeTemplateParmExpr
>(Arg
))
7034 Arg
= subst
->getReplacement()->IgnoreImpCasts();
7036 // A pointer-to-member constant written &Class::member.
7037 if (UnaryOperator
*UnOp
= dyn_cast
<UnaryOperator
>(Arg
)) {
7038 if (UnOp
->getOpcode() == UO_AddrOf
) {
7039 DRE
= dyn_cast
<DeclRefExpr
>(UnOp
->getSubExpr());
7040 if (DRE
&& !DRE
->getQualifier())
7044 // A constant of pointer-to-member type.
7045 else if ((DRE
= dyn_cast
<DeclRefExpr
>(Arg
))) {
7046 ValueDecl
*VD
= DRE
->getDecl();
7047 if (VD
->getType()->isMemberPointerType()) {
7048 if (isa
<NonTypeTemplateParmDecl
>(VD
)) {
7049 if (Arg
->isTypeDependent() || Arg
->isValueDependent()) {
7050 SugaredConverted
= TemplateArgument(Arg
);
7051 CanonicalConverted
=
7052 S
.Context
.getCanonicalTemplateArgument(SugaredConverted
);
7054 SugaredConverted
= TemplateArgument(VD
, ParamType
);
7055 CanonicalConverted
=
7056 TemplateArgument(cast
<ValueDecl
>(VD
->getCanonicalDecl()),
7057 S
.Context
.getCanonicalType(ParamType
));
7066 ValueDecl
*Entity
= DRE
? DRE
->getDecl() : nullptr;
7068 // Check for a null pointer value.
7069 switch (isNullPointerValueTemplateArgument(S
, Param
, ParamType
, ResultArg
,
7073 case NPV_NullPointer
:
7074 S
.Diag(ResultArg
->getExprLoc(), diag::warn_cxx98_compat_template_arg_null
);
7075 SugaredConverted
= TemplateArgument(ParamType
,
7076 /*isNullPtr*/ true);
7077 CanonicalConverted
= TemplateArgument(S
.Context
.getCanonicalType(ParamType
),
7078 /*isNullPtr*/ true);
7080 case NPV_NotNullPointer
:
7084 if (S
.IsQualificationConversion(ResultArg
->getType(),
7085 ParamType
.getNonReferenceType(), false,
7086 ObjCLifetimeConversion
)) {
7087 ResultArg
= S
.ImpCastExprToType(ResultArg
, ParamType
, CK_NoOp
,
7088 ResultArg
->getValueKind())
7090 } else if (!S
.Context
.hasSameUnqualifiedType(
7091 ResultArg
->getType(), ParamType
.getNonReferenceType())) {
7092 // We can't perform this conversion.
7093 S
.Diag(ResultArg
->getBeginLoc(), diag::err_template_arg_not_convertible
)
7094 << ResultArg
->getType() << ParamType
<< ResultArg
->getSourceRange();
7095 S
.Diag(Param
->getLocation(), diag::note_template_param_here
);
7100 return S
.Diag(Arg
->getBeginLoc(),
7101 diag::err_template_arg_not_pointer_to_member_form
)
7102 << Arg
->getSourceRange();
7104 if (isa
<FieldDecl
>(DRE
->getDecl()) ||
7105 isa
<IndirectFieldDecl
>(DRE
->getDecl()) ||
7106 isa
<CXXMethodDecl
>(DRE
->getDecl())) {
7107 assert((isa
<FieldDecl
>(DRE
->getDecl()) ||
7108 isa
<IndirectFieldDecl
>(DRE
->getDecl()) ||
7109 cast
<CXXMethodDecl
>(DRE
->getDecl())
7110 ->isImplicitObjectMemberFunction()) &&
7111 "Only non-static member pointers can make it here");
7113 // Okay: this is the address of a non-static member, and therefore
7114 // a member pointer constant.
7115 if (Arg
->isTypeDependent() || Arg
->isValueDependent()) {
7116 SugaredConverted
= TemplateArgument(Arg
);
7117 CanonicalConverted
=
7118 S
.Context
.getCanonicalTemplateArgument(SugaredConverted
);
7120 ValueDecl
*D
= DRE
->getDecl();
7121 SugaredConverted
= TemplateArgument(D
, ParamType
);
7122 CanonicalConverted
=
7123 TemplateArgument(cast
<ValueDecl
>(D
->getCanonicalDecl()),
7124 S
.Context
.getCanonicalType(ParamType
));
7129 // We found something else, but we don't know specifically what it is.
7130 S
.Diag(Arg
->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form
)
7131 << Arg
->getSourceRange();
7132 S
.Diag(DRE
->getDecl()->getLocation(), diag::note_template_arg_refers_here
);
7136 /// Check a template argument against its corresponding
7137 /// non-type template parameter.
7139 /// This routine implements the semantics of C++ [temp.arg.nontype].
7140 /// If an error occurred, it returns ExprError(); otherwise, it
7141 /// returns the converted template argument. \p ParamType is the
7142 /// type of the non-type template parameter after it has been instantiated.
7143 ExprResult
Sema::CheckTemplateArgument(NonTypeTemplateParmDecl
*Param
,
7144 QualType ParamType
, Expr
*Arg
,
7145 TemplateArgument
&SugaredConverted
,
7146 TemplateArgument
&CanonicalConverted
,
7147 CheckTemplateArgumentKind CTAK
) {
7148 SourceLocation StartLoc
= Arg
->getBeginLoc();
7150 // If the parameter type somehow involves auto, deduce the type now.
7151 DeducedType
*DeducedT
= ParamType
->getContainedDeducedType();
7152 if (getLangOpts().CPlusPlus17
&& DeducedT
&& !DeducedT
->isDeduced()) {
7153 // During template argument deduction, we allow 'decltype(auto)' to
7154 // match an arbitrary dependent argument.
7155 // FIXME: The language rules don't say what happens in this case.
7156 // FIXME: We get an opaque dependent type out of decltype(auto) if the
7157 // expression is merely instantiation-dependent; is this enough?
7158 if (CTAK
== CTAK_Deduced
&& Arg
->isTypeDependent()) {
7159 auto *AT
= dyn_cast
<AutoType
>(DeducedT
);
7160 if (AT
&& AT
->isDecltypeAuto()) {
7161 SugaredConverted
= TemplateArgument(Arg
);
7162 CanonicalConverted
= TemplateArgument(
7163 Context
.getCanonicalTemplateArgument(SugaredConverted
));
7168 // When checking a deduced template argument, deduce from its type even if
7169 // the type is dependent, in order to check the types of non-type template
7170 // arguments line up properly in partial ordering.
7171 Expr
*DeductionArg
= Arg
;
7172 if (auto *PE
= dyn_cast
<PackExpansionExpr
>(DeductionArg
))
7173 DeductionArg
= PE
->getPattern();
7174 TypeSourceInfo
*TSI
=
7175 Context
.getTrivialTypeSourceInfo(ParamType
, Param
->getLocation());
7176 if (isa
<DeducedTemplateSpecializationType
>(DeducedT
)) {
7177 InitializedEntity Entity
=
7178 InitializedEntity::InitializeTemplateParameter(ParamType
, Param
);
7179 InitializationKind Kind
= InitializationKind::CreateForInit(
7180 DeductionArg
->getBeginLoc(), /*DirectInit*/false, DeductionArg
);
7181 Expr
*Inits
[1] = {DeductionArg
};
7183 DeduceTemplateSpecializationFromInitializer(TSI
, Entity
, Kind
, Inits
);
7184 if (ParamType
.isNull())
7187 TemplateDeductionInfo
Info(DeductionArg
->getExprLoc(),
7188 Param
->getDepth() + 1);
7189 ParamType
= QualType();
7190 TemplateDeductionResult Result
=
7191 DeduceAutoType(TSI
->getTypeLoc(), DeductionArg
, ParamType
, Info
,
7192 /*DependentDeduction=*/true,
7193 // We do not check constraints right now because the
7194 // immediately-declared constraint of the auto type is
7195 // also an associated constraint, and will be checked
7196 // along with the other associated constraints after
7197 // checking the template argument list.
7198 /*IgnoreConstraints=*/true);
7199 if (Result
== TDK_AlreadyDiagnosed
) {
7200 if (ParamType
.isNull())
7202 } else if (Result
!= TDK_Success
) {
7203 Diag(Arg
->getExprLoc(),
7204 diag::err_non_type_template_parm_type_deduction_failure
)
7205 << Param
->getDeclName() << Param
->getType() << Arg
->getType()
7206 << Arg
->getSourceRange();
7207 Diag(Param
->getLocation(), diag::note_template_param_here
);
7211 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
7212 // an error. The error message normally references the parameter
7213 // declaration, but here we'll pass the argument location because that's
7214 // where the parameter type is deduced.
7215 ParamType
= CheckNonTypeTemplateParameterType(ParamType
, Arg
->getExprLoc());
7216 if (ParamType
.isNull()) {
7217 Diag(Param
->getLocation(), diag::note_template_param_here
);
7222 // We should have already dropped all cv-qualifiers by now.
7223 assert(!ParamType
.hasQualifiers() &&
7224 "non-type template parameter type cannot be qualified");
7226 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
7227 if (CTAK
== CTAK_Deduced
&&
7228 (ParamType
->isReferenceType()
7229 ? !Context
.hasSameType(ParamType
.getNonReferenceType(),
7231 : !Context
.hasSameUnqualifiedType(ParamType
, Arg
->getType()))) {
7232 // FIXME: If either type is dependent, we skip the check. This isn't
7233 // correct, since during deduction we're supposed to have replaced each
7234 // template parameter with some unique (non-dependent) placeholder.
7235 // FIXME: If the argument type contains 'auto', we carry on and fail the
7236 // type check in order to force specific types to be more specialized than
7237 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
7238 // work. Similarly for CTAD, when comparing 'A<x>' against 'A'.
7239 if ((ParamType
->isDependentType() || Arg
->isTypeDependent()) &&
7240 !Arg
->getType()->getContainedDeducedType()) {
7241 SugaredConverted
= TemplateArgument(Arg
);
7242 CanonicalConverted
= TemplateArgument(
7243 Context
.getCanonicalTemplateArgument(SugaredConverted
));
7246 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
7247 // we should actually be checking the type of the template argument in P,
7248 // not the type of the template argument deduced from A, against the
7249 // template parameter type.
7250 Diag(StartLoc
, diag::err_deduced_non_type_template_arg_type_mismatch
)
7252 << ParamType
.getUnqualifiedType();
7253 Diag(Param
->getLocation(), diag::note_template_param_here
);
7257 // If either the parameter has a dependent type or the argument is
7258 // type-dependent, there's nothing we can check now.
7259 if (ParamType
->isDependentType() || Arg
->isTypeDependent()) {
7260 // Force the argument to the type of the parameter to maintain invariants.
7261 auto *PE
= dyn_cast
<PackExpansionExpr
>(Arg
);
7263 Arg
= PE
->getPattern();
7264 ExprResult E
= ImpCastExprToType(
7265 Arg
, ParamType
.getNonLValueExprType(Context
), CK_Dependent
,
7266 ParamType
->isLValueReferenceType() ? VK_LValue
7267 : ParamType
->isRValueReferenceType() ? VK_XValue
7272 // Recreate a pack expansion if we unwrapped one.
7274 PackExpansionExpr(E
.get()->getType(), E
.get(), PE
->getEllipsisLoc(),
7275 PE
->getNumExpansions());
7277 SugaredConverted
= TemplateArgument(E
.get());
7278 CanonicalConverted
= TemplateArgument(
7279 Context
.getCanonicalTemplateArgument(SugaredConverted
));
7283 // The initialization of the parameter from the argument is
7284 // a constant-evaluated context.
7285 EnterExpressionEvaluationContext
ConstantEvaluated(
7286 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated
);
7288 if (getLangOpts().CPlusPlus17
) {
7289 QualType CanonParamType
= Context
.getCanonicalType(ParamType
);
7291 // Avoid making a copy when initializing a template parameter of class type
7292 // from a template parameter object of the same type. This is going beyond
7293 // the standard, but is required for soundness: in
7294 // template<A a> struct X { X *p; X<a> *q; };
7295 // ... we need p and q to have the same type.
7297 // Similarly, don't inject a call to a copy constructor when initializing
7298 // from a template parameter of the same type.
7299 Expr
*InnerArg
= Arg
->IgnoreParenImpCasts();
7300 if (ParamType
->isRecordType() && isa
<DeclRefExpr
>(InnerArg
) &&
7301 Context
.hasSameUnqualifiedType(ParamType
, InnerArg
->getType())) {
7302 NamedDecl
*ND
= cast
<DeclRefExpr
>(InnerArg
)->getDecl();
7303 if (auto *TPO
= dyn_cast
<TemplateParamObjectDecl
>(ND
)) {
7305 SugaredConverted
= TemplateArgument(TPO
, ParamType
);
7306 CanonicalConverted
=
7307 TemplateArgument(TPO
->getCanonicalDecl(), CanonParamType
);
7310 if (isa
<NonTypeTemplateParmDecl
>(ND
)) {
7311 SugaredConverted
= TemplateArgument(Arg
);
7312 CanonicalConverted
=
7313 Context
.getCanonicalTemplateArgument(SugaredConverted
);
7318 // C++17 [temp.arg.nontype]p1:
7319 // A template-argument for a non-type template parameter shall be
7320 // a converted constant expression of the type of the template-parameter.
7322 ExprResult ArgResult
= CheckConvertedConstantExpression(
7323 Arg
, ParamType
, Value
, CCEK_TemplateArg
, Param
);
7324 if (ArgResult
.isInvalid())
7327 // For a value-dependent argument, CheckConvertedConstantExpression is
7328 // permitted (and expected) to be unable to determine a value.
7329 if (ArgResult
.get()->isValueDependent()) {
7330 SugaredConverted
= TemplateArgument(ArgResult
.get());
7331 CanonicalConverted
=
7332 Context
.getCanonicalTemplateArgument(SugaredConverted
);
7336 // Convert the APValue to a TemplateArgument.
7337 switch (Value
.getKind()) {
7339 assert(ParamType
->isNullPtrType());
7340 SugaredConverted
= TemplateArgument(ParamType
, /*isNullPtr=*/true);
7341 CanonicalConverted
= TemplateArgument(CanonParamType
, /*isNullPtr=*/true);
7343 case APValue::Indeterminate
:
7344 llvm_unreachable("result of constant evaluation should be initialized");
7347 assert(ParamType
->isIntegralOrEnumerationType());
7348 SugaredConverted
= TemplateArgument(Context
, Value
.getInt(), ParamType
);
7349 CanonicalConverted
=
7350 TemplateArgument(Context
, Value
.getInt(), CanonParamType
);
7352 case APValue::MemberPointer
: {
7353 assert(ParamType
->isMemberPointerType());
7355 // FIXME: We need TemplateArgument representation and mangling for these.
7356 if (!Value
.getMemberPointerPath().empty()) {
7357 Diag(Arg
->getBeginLoc(),
7358 diag::err_template_arg_member_ptr_base_derived_not_supported
)
7359 << Value
.getMemberPointerDecl() << ParamType
7360 << Arg
->getSourceRange();
7364 auto *VD
= const_cast<ValueDecl
*>(Value
.getMemberPointerDecl());
7365 SugaredConverted
= VD
? TemplateArgument(VD
, ParamType
)
7366 : TemplateArgument(ParamType
, /*isNullPtr=*/true);
7367 CanonicalConverted
=
7368 VD
? TemplateArgument(cast
<ValueDecl
>(VD
->getCanonicalDecl()),
7370 : TemplateArgument(CanonParamType
, /*isNullPtr=*/true);
7373 case APValue::LValue
: {
7374 // For a non-type template-parameter of pointer or reference type,
7375 // the value of the constant expression shall not refer to
7376 assert(ParamType
->isPointerType() || ParamType
->isReferenceType() ||
7377 ParamType
->isNullPtrType());
7378 // -- a temporary object
7379 // -- a string literal
7380 // -- the result of a typeid expression, or
7381 // -- a predefined __func__ variable
7382 APValue::LValueBase Base
= Value
.getLValueBase();
7383 auto *VD
= const_cast<ValueDecl
*>(Base
.dyn_cast
<const ValueDecl
*>());
7386 isa
<LifetimeExtendedTemporaryDecl
, UnnamedGlobalConstantDecl
>(VD
))) {
7387 Diag(Arg
->getBeginLoc(), diag::err_template_arg_not_decl_ref
)
7388 << Arg
->getSourceRange();
7392 // FIXME: Until C++20
7393 if (Value
.hasLValuePath() && Value
.getLValuePath().size() == 1 &&
7394 VD
&& VD
->getType()->isArrayType() &&
7395 Value
.getLValuePath()[0].getAsArrayIndex() == 0 &&
7396 !Value
.isLValueOnePastTheEnd() && ParamType
->isPointerType()) {
7397 // Per defect report (no number yet):
7398 // ... other than a pointer to the first element of a complete array
7400 } else if (!Value
.hasLValuePath() || Value
.getLValuePath().size() ||
7401 Value
.isLValueOnePastTheEnd()) {
7402 Diag(StartLoc
, diag::err_non_type_template_arg_subobject
)
7403 << Value
.getAsString(Context
, ParamType
);
7406 assert((VD
|| !ParamType
->isReferenceType()) &&
7407 "null reference should not be a constant expression");
7408 assert((!VD
|| !ParamType
->isNullPtrType()) &&
7409 "non-null value of type nullptr_t?");
7411 SugaredConverted
= VD
? TemplateArgument(VD
, ParamType
)
7412 : TemplateArgument(ParamType
, /*isNullPtr=*/true);
7413 CanonicalConverted
=
7414 VD
? TemplateArgument(cast
<ValueDecl
>(VD
->getCanonicalDecl()),
7416 : TemplateArgument(CanonParamType
, /*isNullPtr=*/true);
7419 case APValue::Struct
:
7420 case APValue::Union
: {
7421 // Get or create the corresponding template parameter object.
7422 TemplateParamObjectDecl
*D
=
7423 Context
.getTemplateParamObjectDecl(ParamType
, Value
);
7424 SugaredConverted
= TemplateArgument(D
, ParamType
);
7425 CanonicalConverted
=
7426 TemplateArgument(D
->getCanonicalDecl(), CanonParamType
);
7429 case APValue::AddrLabelDiff
:
7430 return Diag(StartLoc
, diag::err_non_type_template_arg_addr_label_diff
);
7431 case APValue::FixedPoint
:
7432 case APValue::Float
:
7433 case APValue::ComplexInt
:
7434 case APValue::ComplexFloat
:
7435 case APValue::Vector
:
7436 case APValue::Array
:
7437 return Diag(StartLoc
, diag::err_non_type_template_arg_unsupported
)
7441 return ArgResult
.get();
7444 // C++ [temp.arg.nontype]p5:
7445 // The following conversions are performed on each expression used
7446 // as a non-type template-argument. If a non-type
7447 // template-argument cannot be converted to the type of the
7448 // corresponding template-parameter then the program is
7450 if (ParamType
->isIntegralOrEnumerationType()) {
7452 // -- for a non-type template-parameter of integral or
7453 // enumeration type, conversions permitted in a converted
7454 // constant expression are applied.
7457 // -- for a non-type template-parameter of integral or
7458 // enumeration type, integral promotions (4.5) and integral
7459 // conversions (4.7) are applied.
7461 if (getLangOpts().CPlusPlus11
) {
7462 // C++ [temp.arg.nontype]p1:
7463 // A template-argument for a non-type, non-template template-parameter
7466 // -- for a non-type template-parameter of integral or enumeration
7467 // type, a converted constant expression of the type of the
7468 // template-parameter; or
7470 ExprResult ArgResult
=
7471 CheckConvertedConstantExpression(Arg
, ParamType
, Value
,
7473 if (ArgResult
.isInvalid())
7476 // We can't check arbitrary value-dependent arguments.
7477 if (ArgResult
.get()->isValueDependent()) {
7478 SugaredConverted
= TemplateArgument(ArgResult
.get());
7479 CanonicalConverted
=
7480 Context
.getCanonicalTemplateArgument(SugaredConverted
);
7484 // Widen the argument value to sizeof(parameter type). This is almost
7485 // always a no-op, except when the parameter type is bool. In
7486 // that case, this may extend the argument from 1 bit to 8 bits.
7487 QualType IntegerType
= ParamType
;
7488 if (const EnumType
*Enum
= IntegerType
->getAs
<EnumType
>())
7489 IntegerType
= Enum
->getDecl()->getIntegerType();
7490 Value
= Value
.extOrTrunc(IntegerType
->isBitIntType()
7491 ? Context
.getIntWidth(IntegerType
)
7492 : Context
.getTypeSize(IntegerType
));
7494 SugaredConverted
= TemplateArgument(Context
, Value
, ParamType
);
7495 CanonicalConverted
=
7496 TemplateArgument(Context
, Value
, Context
.getCanonicalType(ParamType
));
7500 ExprResult ArgResult
= DefaultLvalueConversion(Arg
);
7501 if (ArgResult
.isInvalid())
7503 Arg
= ArgResult
.get();
7505 QualType ArgType
= Arg
->getType();
7507 // C++ [temp.arg.nontype]p1:
7508 // A template-argument for a non-type, non-template
7509 // template-parameter shall be one of:
7511 // -- an integral constant-expression of integral or enumeration
7513 // -- the name of a non-type template-parameter; or
7515 if (!ArgType
->isIntegralOrEnumerationType()) {
7516 Diag(Arg
->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral
)
7517 << ArgType
<< Arg
->getSourceRange();
7518 Diag(Param
->getLocation(), diag::note_template_param_here
);
7520 } else if (!Arg
->isValueDependent()) {
7521 class TmplArgICEDiagnoser
: public VerifyICEDiagnoser
{
7525 TmplArgICEDiagnoser(QualType T
) : T(T
) { }
7527 SemaDiagnosticBuilder
diagnoseNotICE(Sema
&S
,
7528 SourceLocation Loc
) override
{
7529 return S
.Diag(Loc
, diag::err_template_arg_not_ice
) << T
;
7531 } Diagnoser(ArgType
);
7533 Arg
= VerifyIntegerConstantExpression(Arg
, &Value
, Diagnoser
).get();
7538 // From here on out, all we care about is the unqualified form
7539 // of the argument type.
7540 ArgType
= ArgType
.getUnqualifiedType();
7542 // Try to convert the argument to the parameter's type.
7543 if (Context
.hasSameType(ParamType
, ArgType
)) {
7544 // Okay: no conversion necessary
7545 } else if (ParamType
->isBooleanType()) {
7546 // This is an integral-to-boolean conversion.
7547 Arg
= ImpCastExprToType(Arg
, ParamType
, CK_IntegralToBoolean
).get();
7548 } else if (IsIntegralPromotion(Arg
, ArgType
, ParamType
) ||
7549 !ParamType
->isEnumeralType()) {
7550 // This is an integral promotion or conversion.
7551 Arg
= ImpCastExprToType(Arg
, ParamType
, CK_IntegralCast
).get();
7553 // We can't perform this conversion.
7554 Diag(Arg
->getBeginLoc(), diag::err_template_arg_not_convertible
)
7555 << Arg
->getType() << ParamType
<< Arg
->getSourceRange();
7556 Diag(Param
->getLocation(), diag::note_template_param_here
);
7560 // Add the value of this argument to the list of converted
7561 // arguments. We use the bitwidth and signedness of the template
7563 if (Arg
->isValueDependent()) {
7564 // The argument is value-dependent. Create a new
7565 // TemplateArgument with the converted expression.
7566 SugaredConverted
= TemplateArgument(Arg
);
7567 CanonicalConverted
=
7568 Context
.getCanonicalTemplateArgument(SugaredConverted
);
7572 QualType IntegerType
= ParamType
;
7573 if (const EnumType
*Enum
= IntegerType
->getAs
<EnumType
>()) {
7574 IntegerType
= Enum
->getDecl()->getIntegerType();
7577 if (ParamType
->isBooleanType()) {
7578 // Value must be zero or one.
7580 unsigned AllowedBits
= Context
.getTypeSize(IntegerType
);
7581 if (Value
.getBitWidth() != AllowedBits
)
7582 Value
= Value
.extOrTrunc(AllowedBits
);
7583 Value
.setIsSigned(IntegerType
->isSignedIntegerOrEnumerationType());
7585 llvm::APSInt OldValue
= Value
;
7587 // Coerce the template argument's value to the value it will have
7588 // based on the template parameter's type.
7589 unsigned AllowedBits
= IntegerType
->isBitIntType()
7590 ? Context
.getIntWidth(IntegerType
)
7591 : Context
.getTypeSize(IntegerType
);
7592 if (Value
.getBitWidth() != AllowedBits
)
7593 Value
= Value
.extOrTrunc(AllowedBits
);
7594 Value
.setIsSigned(IntegerType
->isSignedIntegerOrEnumerationType());
7596 // Complain if an unsigned parameter received a negative value.
7597 if (IntegerType
->isUnsignedIntegerOrEnumerationType() &&
7598 (OldValue
.isSigned() && OldValue
.isNegative())) {
7599 Diag(Arg
->getBeginLoc(), diag::warn_template_arg_negative
)
7600 << toString(OldValue
, 10) << toString(Value
, 10) << Param
->getType()
7601 << Arg
->getSourceRange();
7602 Diag(Param
->getLocation(), diag::note_template_param_here
);
7605 // Complain if we overflowed the template parameter's type.
7606 unsigned RequiredBits
;
7607 if (IntegerType
->isUnsignedIntegerOrEnumerationType())
7608 RequiredBits
= OldValue
.getActiveBits();
7609 else if (OldValue
.isUnsigned())
7610 RequiredBits
= OldValue
.getActiveBits() + 1;
7612 RequiredBits
= OldValue
.getSignificantBits();
7613 if (RequiredBits
> AllowedBits
) {
7614 Diag(Arg
->getBeginLoc(), diag::warn_template_arg_too_large
)
7615 << toString(OldValue
, 10) << toString(Value
, 10) << Param
->getType()
7616 << Arg
->getSourceRange();
7617 Diag(Param
->getLocation(), diag::note_template_param_here
);
7621 QualType T
= ParamType
->isEnumeralType() ? ParamType
: IntegerType
;
7622 SugaredConverted
= TemplateArgument(Context
, Value
, T
);
7623 CanonicalConverted
=
7624 TemplateArgument(Context
, Value
, Context
.getCanonicalType(T
));
7628 QualType ArgType
= Arg
->getType();
7629 DeclAccessPair FoundResult
; // temporary for ResolveOverloadedFunction
7631 // Handle pointer-to-function, reference-to-function, and
7632 // pointer-to-member-function all in (roughly) the same way.
7633 if (// -- For a non-type template-parameter of type pointer to
7634 // function, only the function-to-pointer conversion (4.3) is
7635 // applied. If the template-argument represents a set of
7636 // overloaded functions (or a pointer to such), the matching
7637 // function is selected from the set (13.4).
7638 (ParamType
->isPointerType() &&
7639 ParamType
->castAs
<PointerType
>()->getPointeeType()->isFunctionType()) ||
7640 // -- For a non-type template-parameter of type reference to
7641 // function, no conversions apply. If the template-argument
7642 // represents a set of overloaded functions, the matching
7643 // function is selected from the set (13.4).
7644 (ParamType
->isReferenceType() &&
7645 ParamType
->castAs
<ReferenceType
>()->getPointeeType()->isFunctionType()) ||
7646 // -- For a non-type template-parameter of type pointer to
7647 // member function, no conversions apply. If the
7648 // template-argument represents a set of overloaded member
7649 // functions, the matching member function is selected from
7651 (ParamType
->isMemberPointerType() &&
7652 ParamType
->castAs
<MemberPointerType
>()->getPointeeType()
7653 ->isFunctionType())) {
7655 if (Arg
->getType() == Context
.OverloadTy
) {
7656 if (FunctionDecl
*Fn
= ResolveAddressOfOverloadedFunction(Arg
, ParamType
,
7659 if (DiagnoseUseOfDecl(Fn
, Arg
->getBeginLoc()))
7662 ExprResult Res
= FixOverloadedFunctionReference(Arg
, FoundResult
, Fn
);
7663 if (Res
.isInvalid())
7666 ArgType
= Arg
->getType();
7671 if (!ParamType
->isMemberPointerType()) {
7672 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7673 *this, Param
, ParamType
, Arg
, SugaredConverted
,
7674 CanonicalConverted
))
7679 if (CheckTemplateArgumentPointerToMember(
7680 *this, Param
, ParamType
, Arg
, SugaredConverted
, CanonicalConverted
))
7685 if (ParamType
->isPointerType()) {
7686 // -- for a non-type template-parameter of type pointer to
7687 // object, qualification conversions (4.4) and the
7688 // array-to-pointer conversion (4.2) are applied.
7689 // C++0x also allows a value of std::nullptr_t.
7690 assert(ParamType
->getPointeeType()->isIncompleteOrObjectType() &&
7691 "Only object pointers allowed here");
7693 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7694 *this, Param
, ParamType
, Arg
, SugaredConverted
, CanonicalConverted
))
7699 if (const ReferenceType
*ParamRefType
= ParamType
->getAs
<ReferenceType
>()) {
7700 // -- For a non-type template-parameter of type reference to
7701 // object, no conversions apply. The type referred to by the
7702 // reference may be more cv-qualified than the (otherwise
7703 // identical) type of the template-argument. The
7704 // template-parameter is bound directly to the
7705 // template-argument, which must be an lvalue.
7706 assert(ParamRefType
->getPointeeType()->isIncompleteOrObjectType() &&
7707 "Only object references allowed here");
7709 if (Arg
->getType() == Context
.OverloadTy
) {
7710 if (FunctionDecl
*Fn
= ResolveAddressOfOverloadedFunction(Arg
,
7711 ParamRefType
->getPointeeType(),
7714 if (DiagnoseUseOfDecl(Fn
, Arg
->getBeginLoc()))
7716 ExprResult Res
= FixOverloadedFunctionReference(Arg
, FoundResult
, Fn
);
7717 if (Res
.isInvalid())
7720 ArgType
= Arg
->getType();
7725 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7726 *this, Param
, ParamType
, Arg
, SugaredConverted
, CanonicalConverted
))
7731 // Deal with parameters of type std::nullptr_t.
7732 if (ParamType
->isNullPtrType()) {
7733 if (Arg
->isTypeDependent() || Arg
->isValueDependent()) {
7734 SugaredConverted
= TemplateArgument(Arg
);
7735 CanonicalConverted
=
7736 Context
.getCanonicalTemplateArgument(SugaredConverted
);
7740 switch (isNullPointerValueTemplateArgument(*this, Param
, ParamType
, Arg
)) {
7741 case NPV_NotNullPointer
:
7742 Diag(Arg
->getExprLoc(), diag::err_template_arg_not_convertible
)
7743 << Arg
->getType() << ParamType
;
7744 Diag(Param
->getLocation(), diag::note_template_param_here
);
7750 case NPV_NullPointer
:
7751 Diag(Arg
->getExprLoc(), diag::warn_cxx98_compat_template_arg_null
);
7752 SugaredConverted
= TemplateArgument(ParamType
,
7753 /*isNullPtr=*/true);
7754 CanonicalConverted
= TemplateArgument(Context
.getCanonicalType(ParamType
),
7755 /*isNullPtr=*/true);
7760 // -- For a non-type template-parameter of type pointer to data
7761 // member, qualification conversions (4.4) are applied.
7762 assert(ParamType
->isMemberPointerType() && "Only pointers to members remain");
7764 if (CheckTemplateArgumentPointerToMember(
7765 *this, Param
, ParamType
, Arg
, SugaredConverted
, CanonicalConverted
))
7770 static void DiagnoseTemplateParameterListArityMismatch(
7771 Sema
&S
, TemplateParameterList
*New
, TemplateParameterList
*Old
,
7772 Sema::TemplateParameterListEqualKind Kind
, SourceLocation TemplateArgLoc
);
7774 /// Check a template argument against its corresponding
7775 /// template template parameter.
7777 /// This routine implements the semantics of C++ [temp.arg.template].
7778 /// It returns true if an error occurred, and false otherwise.
7779 bool Sema::CheckTemplateTemplateArgument(TemplateTemplateParmDecl
*Param
,
7780 TemplateParameterList
*Params
,
7781 TemplateArgumentLoc
&Arg
) {
7782 TemplateName Name
= Arg
.getArgument().getAsTemplateOrTemplatePattern();
7783 TemplateDecl
*Template
= Name
.getAsTemplateDecl();
7785 // Any dependent template name is fine.
7786 assert(Name
.isDependent() && "Non-dependent template isn't a declaration?");
7790 if (Template
->isInvalidDecl())
7793 // C++0x [temp.arg.template]p1:
7794 // A template-argument for a template template-parameter shall be
7795 // the name of a class template or an alias template, expressed as an
7796 // id-expression. When the template-argument names a class template, only
7797 // primary class templates are considered when matching the
7798 // template template argument with the corresponding parameter;
7799 // partial specializations are not considered even if their
7800 // parameter lists match that of the template template parameter.
7802 // Note that we also allow template template parameters here, which
7803 // will happen when we are dealing with, e.g., class template
7804 // partial specializations.
7805 if (!isa
<ClassTemplateDecl
>(Template
) &&
7806 !isa
<TemplateTemplateParmDecl
>(Template
) &&
7807 !isa
<TypeAliasTemplateDecl
>(Template
) &&
7808 !isa
<BuiltinTemplateDecl
>(Template
)) {
7809 assert(isa
<FunctionTemplateDecl
>(Template
) &&
7810 "Only function templates are possible here");
7811 Diag(Arg
.getLocation(), diag::err_template_arg_not_valid_template
);
7812 Diag(Template
->getLocation(), diag::note_template_arg_refers_here_func
)
7816 // C++1z [temp.arg.template]p3: (DR 150)
7817 // A template-argument matches a template template-parameter P when P
7818 // is at least as specialized as the template-argument A.
7819 // FIXME: We should enable RelaxedTemplateTemplateArgs by default as it is a
7820 // defect report resolution from C++17 and shouldn't be introduced by
7822 if (getLangOpts().RelaxedTemplateTemplateArgs
) {
7823 // Quick check for the common case:
7824 // If P contains a parameter pack, then A [...] matches P if each of A's
7825 // template parameters matches the corresponding template parameter in
7826 // the template-parameter-list of P.
7827 if (TemplateParameterListsAreEqual(
7828 Template
->getTemplateParameters(), Params
, false,
7829 TPL_TemplateTemplateArgumentMatch
, Arg
.getLocation()) &&
7830 // If the argument has no associated constraints, then the parameter is
7831 // definitely at least as specialized as the argument.
7832 // Otherwise - we need a more thorough check.
7833 !Template
->hasAssociatedConstraints())
7836 if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params
, Template
,
7837 Arg
.getLocation())) {
7839 // C++20[temp.func.order]p2
7840 // [...] If both deductions succeed, the partial ordering selects the
7841 // more constrained template (if one exists) as determined below.
7842 SmallVector
<const Expr
*, 3> ParamsAC
, TemplateAC
;
7843 Params
->getAssociatedConstraints(ParamsAC
);
7844 // C++2a[temp.arg.template]p3
7845 // [...] In this comparison, if P is unconstrained, the constraints on A
7846 // are not considered.
7847 if (ParamsAC
.empty())
7850 Template
->getAssociatedConstraints(TemplateAC
);
7852 bool IsParamAtLeastAsConstrained
;
7853 if (IsAtLeastAsConstrained(Param
, ParamsAC
, Template
, TemplateAC
,
7854 IsParamAtLeastAsConstrained
))
7856 if (!IsParamAtLeastAsConstrained
) {
7857 Diag(Arg
.getLocation(),
7858 diag::err_template_template_parameter_not_at_least_as_constrained
)
7859 << Template
<< Param
<< Arg
.getSourceRange();
7860 Diag(Param
->getLocation(), diag::note_entity_declared_at
) << Param
;
7861 Diag(Template
->getLocation(), diag::note_entity_declared_at
)
7863 MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Param
, ParamsAC
, Template
,
7869 // FIXME: Produce better diagnostics for deduction failures.
7872 return !TemplateParameterListsAreEqual(Template
->getTemplateParameters(),
7875 TPL_TemplateTemplateArgumentMatch
,
7879 /// Given a non-type template argument that refers to a
7880 /// declaration and the type of its corresponding non-type template
7881 /// parameter, produce an expression that properly refers to that
7884 Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument
&Arg
,
7886 SourceLocation Loc
) {
7887 // C++ [temp.param]p8:
7889 // A non-type template-parameter of type "array of T" or
7890 // "function returning T" is adjusted to be of type "pointer to
7891 // T" or "pointer to function returning T", respectively.
7892 if (ParamType
->isArrayType())
7893 ParamType
= Context
.getArrayDecayedType(ParamType
);
7894 else if (ParamType
->isFunctionType())
7895 ParamType
= Context
.getPointerType(ParamType
);
7897 // For a NULL non-type template argument, return nullptr casted to the
7898 // parameter's type.
7899 if (Arg
.getKind() == TemplateArgument::NullPtr
) {
7900 return ImpCastExprToType(
7901 new (Context
) CXXNullPtrLiteralExpr(Context
.NullPtrTy
, Loc
),
7903 ParamType
->getAs
<MemberPointerType
>()
7904 ? CK_NullToMemberPointer
7905 : CK_NullToPointer
);
7907 assert(Arg
.getKind() == TemplateArgument::Declaration
&&
7908 "Only declaration template arguments permitted here");
7910 ValueDecl
*VD
= Arg
.getAsDecl();
7913 if (ParamType
->isMemberPointerType()) {
7914 // If this is a pointer to member, we need to use a qualified name to
7915 // form a suitable pointer-to-member constant.
7916 assert(VD
->getDeclContext()->isRecord() &&
7917 (isa
<CXXMethodDecl
>(VD
) || isa
<FieldDecl
>(VD
) ||
7918 isa
<IndirectFieldDecl
>(VD
)));
7920 = Context
.getTypeDeclType(cast
<RecordDecl
>(VD
->getDeclContext()));
7921 NestedNameSpecifier
*Qualifier
7922 = NestedNameSpecifier::Create(Context
, nullptr, false,
7923 ClassType
.getTypePtr());
7924 SS
.MakeTrivial(Context
, Qualifier
, Loc
);
7927 ExprResult RefExpr
= BuildDeclarationNameExpr(
7928 SS
, DeclarationNameInfo(VD
->getDeclName(), Loc
), VD
);
7929 if (RefExpr
.isInvalid())
7932 // For a pointer, the argument declaration is the pointee. Take its address.
7933 QualType
ElemT(RefExpr
.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
7934 if (ParamType
->isPointerType() && !ElemT
.isNull() &&
7935 Context
.hasSimilarType(ElemT
, ParamType
->getPointeeType())) {
7936 // Decay an array argument if we want a pointer to its first element.
7937 RefExpr
= DefaultFunctionArrayConversion(RefExpr
.get());
7938 if (RefExpr
.isInvalid())
7940 } else if (ParamType
->isPointerType() || ParamType
->isMemberPointerType()) {
7941 // For any other pointer, take the address (or form a pointer-to-member).
7942 RefExpr
= CreateBuiltinUnaryOp(Loc
, UO_AddrOf
, RefExpr
.get());
7943 if (RefExpr
.isInvalid())
7945 } else if (ParamType
->isRecordType()) {
7946 assert(isa
<TemplateParamObjectDecl
>(VD
) &&
7947 "arg for class template param not a template parameter object");
7948 // No conversions apply in this case.
7951 assert(ParamType
->isReferenceType() &&
7952 "unexpected type for decl template argument");
7955 // At this point we should have the right value category.
7956 assert(ParamType
->isReferenceType() == RefExpr
.get()->isLValue() &&
7957 "value kind mismatch for non-type template argument");
7959 // The type of the template parameter can differ from the type of the
7960 // argument in various ways; convert it now if necessary.
7961 QualType DestExprType
= ParamType
.getNonLValueExprType(Context
);
7962 if (!Context
.hasSameType(RefExpr
.get()->getType(), DestExprType
)) {
7965 if (Context
.hasSimilarType(RefExpr
.get()->getType(), DestExprType
) ||
7966 IsFunctionConversion(RefExpr
.get()->getType(), DestExprType
, Ignored
)) {
7968 } else if (ParamType
->isVoidPointerType() &&
7969 RefExpr
.get()->getType()->isPointerType()) {
7972 // FIXME: Pointers to members can need conversion derived-to-base or
7973 // base-to-derived conversions. We currently don't retain enough
7974 // information to convert properly (we need to track a cast path or
7975 // subobject number in the template argument).
7977 "unexpected conversion required for non-type template argument");
7979 RefExpr
= ImpCastExprToType(RefExpr
.get(), DestExprType
, CK
,
7980 RefExpr
.get()->getValueKind());
7986 /// Construct a new expression that refers to the given
7987 /// integral template argument with the given source-location
7990 /// This routine takes care of the mapping from an integral template
7991 /// argument (which may have any integral type) to the appropriate
7994 Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument
&Arg
,
7995 SourceLocation Loc
) {
7996 assert(Arg
.getKind() == TemplateArgument::Integral
&&
7997 "Operation is only valid for integral template arguments");
7998 QualType OrigT
= Arg
.getIntegralType();
8000 // If this is an enum type that we're instantiating, we need to use an integer
8001 // type the same size as the enumerator. We don't want to build an
8002 // IntegerLiteral with enum type. The integer type of an enum type can be of
8003 // any integral type with C++11 enum classes, make sure we create the right
8004 // type of literal for it.
8006 if (const EnumType
*ET
= OrigT
->getAs
<EnumType
>())
8007 T
= ET
->getDecl()->getIntegerType();
8010 if (T
->isAnyCharacterType()) {
8011 CharacterLiteral::CharacterKind Kind
;
8012 if (T
->isWideCharType())
8013 Kind
= CharacterLiteral::Wide
;
8014 else if (T
->isChar8Type() && getLangOpts().Char8
)
8015 Kind
= CharacterLiteral::UTF8
;
8016 else if (T
->isChar16Type())
8017 Kind
= CharacterLiteral::UTF16
;
8018 else if (T
->isChar32Type())
8019 Kind
= CharacterLiteral::UTF32
;
8021 Kind
= CharacterLiteral::Ascii
;
8023 E
= new (Context
) CharacterLiteral(Arg
.getAsIntegral().getZExtValue(),
8025 } else if (T
->isBooleanType()) {
8026 E
= CXXBoolLiteralExpr::Create(Context
, Arg
.getAsIntegral().getBoolValue(),
8028 } else if (T
->isNullPtrType()) {
8029 E
= new (Context
) CXXNullPtrLiteralExpr(Context
.NullPtrTy
, Loc
);
8031 E
= IntegerLiteral::Create(Context
, Arg
.getAsIntegral(), T
, Loc
);
8034 if (OrigT
->isEnumeralType()) {
8035 // FIXME: This is a hack. We need a better way to handle substituted
8036 // non-type template parameters.
8037 E
= CStyleCastExpr::Create(Context
, OrigT
, VK_PRValue
, CK_IntegralCast
, E
,
8038 nullptr, CurFPFeatureOverrides(),
8039 Context
.getTrivialTypeSourceInfo(OrigT
, Loc
),
8046 /// Match two template parameters within template parameter lists.
8047 static bool MatchTemplateParameterKind(
8048 Sema
&S
, NamedDecl
*New
,
8049 const Sema::TemplateCompareNewDeclInfo
&NewInstFrom
, NamedDecl
*Old
,
8050 const NamedDecl
*OldInstFrom
, bool Complain
,
8051 Sema::TemplateParameterListEqualKind Kind
, SourceLocation TemplateArgLoc
) {
8052 // Check the actual kind (type, non-type, template).
8053 if (Old
->getKind() != New
->getKind()) {
8055 unsigned NextDiag
= diag::err_template_param_different_kind
;
8056 if (TemplateArgLoc
.isValid()) {
8057 S
.Diag(TemplateArgLoc
, diag::err_template_arg_template_params_mismatch
);
8058 NextDiag
= diag::note_template_param_different_kind
;
8060 S
.Diag(New
->getLocation(), NextDiag
)
8061 << (Kind
!= Sema::TPL_TemplateMatch
);
8062 S
.Diag(Old
->getLocation(), diag::note_template_prev_declaration
)
8063 << (Kind
!= Sema::TPL_TemplateMatch
);
8069 // Check that both are parameter packs or neither are parameter packs.
8070 // However, if we are matching a template template argument to a
8071 // template template parameter, the template template parameter can have
8072 // a parameter pack where the template template argument does not.
8073 if (Old
->isTemplateParameterPack() != New
->isTemplateParameterPack() &&
8074 !(Kind
== Sema::TPL_TemplateTemplateArgumentMatch
&&
8075 Old
->isTemplateParameterPack())) {
8077 unsigned NextDiag
= diag::err_template_parameter_pack_non_pack
;
8078 if (TemplateArgLoc
.isValid()) {
8079 S
.Diag(TemplateArgLoc
,
8080 diag::err_template_arg_template_params_mismatch
);
8081 NextDiag
= diag::note_template_parameter_pack_non_pack
;
8084 unsigned ParamKind
= isa
<TemplateTypeParmDecl
>(New
)? 0
8085 : isa
<NonTypeTemplateParmDecl
>(New
)? 1
8087 S
.Diag(New
->getLocation(), NextDiag
)
8088 << ParamKind
<< New
->isParameterPack();
8089 S
.Diag(Old
->getLocation(), diag::note_template_parameter_pack_here
)
8090 << ParamKind
<< Old
->isParameterPack();
8096 // For non-type template parameters, check the type of the parameter.
8097 if (NonTypeTemplateParmDecl
*OldNTTP
8098 = dyn_cast
<NonTypeTemplateParmDecl
>(Old
)) {
8099 NonTypeTemplateParmDecl
*NewNTTP
= cast
<NonTypeTemplateParmDecl
>(New
);
8101 // If we are matching a template template argument to a template
8102 // template parameter and one of the non-type template parameter types
8103 // is dependent, then we must wait until template instantiation time
8104 // to actually compare the arguments.
8105 if (Kind
!= Sema::TPL_TemplateTemplateArgumentMatch
||
8106 (!OldNTTP
->getType()->isDependentType() &&
8107 !NewNTTP
->getType()->isDependentType())) {
8108 // C++20 [temp.over.link]p6:
8109 // Two [non-type] template-parameters are equivalent [if] they have
8110 // equivalent types ignoring the use of type-constraints for
8111 // placeholder types
8112 QualType OldType
= S
.Context
.getUnconstrainedType(OldNTTP
->getType());
8113 QualType NewType
= S
.Context
.getUnconstrainedType(NewNTTP
->getType());
8114 if (!S
.Context
.hasSameType(OldType
, NewType
)) {
8116 unsigned NextDiag
= diag::err_template_nontype_parm_different_type
;
8117 if (TemplateArgLoc
.isValid()) {
8118 S
.Diag(TemplateArgLoc
,
8119 diag::err_template_arg_template_params_mismatch
);
8120 NextDiag
= diag::note_template_nontype_parm_different_type
;
8122 S
.Diag(NewNTTP
->getLocation(), NextDiag
)
8123 << NewNTTP
->getType()
8124 << (Kind
!= Sema::TPL_TemplateMatch
);
8125 S
.Diag(OldNTTP
->getLocation(),
8126 diag::note_template_nontype_parm_prev_declaration
)
8127 << OldNTTP
->getType();
8134 // For template template parameters, check the template parameter types.
8135 // The template parameter lists of template template
8136 // parameters must agree.
8137 else if (TemplateTemplateParmDecl
*OldTTP
=
8138 dyn_cast
<TemplateTemplateParmDecl
>(Old
)) {
8139 TemplateTemplateParmDecl
*NewTTP
= cast
<TemplateTemplateParmDecl
>(New
);
8140 if (!S
.TemplateParameterListsAreEqual(
8141 NewInstFrom
, NewTTP
->getTemplateParameters(), OldInstFrom
,
8142 OldTTP
->getTemplateParameters(), Complain
,
8143 (Kind
== Sema::TPL_TemplateMatch
8144 ? Sema::TPL_TemplateTemplateParmMatch
8150 if (Kind
!= Sema::TPL_TemplateParamsEquivalent
&&
8151 Kind
!= Sema::TPL_TemplateTemplateArgumentMatch
&&
8152 !isa
<TemplateTemplateParmDecl
>(Old
)) {
8153 const Expr
*NewC
= nullptr, *OldC
= nullptr;
8155 if (isa
<TemplateTypeParmDecl
>(New
)) {
8156 if (const auto *TC
= cast
<TemplateTypeParmDecl
>(New
)->getTypeConstraint())
8157 NewC
= TC
->getImmediatelyDeclaredConstraint();
8158 if (const auto *TC
= cast
<TemplateTypeParmDecl
>(Old
)->getTypeConstraint())
8159 OldC
= TC
->getImmediatelyDeclaredConstraint();
8160 } else if (isa
<NonTypeTemplateParmDecl
>(New
)) {
8161 if (const Expr
*E
= cast
<NonTypeTemplateParmDecl
>(New
)
8162 ->getPlaceholderTypeConstraint())
8164 if (const Expr
*E
= cast
<NonTypeTemplateParmDecl
>(Old
)
8165 ->getPlaceholderTypeConstraint())
8168 llvm_unreachable("unexpected template parameter type");
8170 auto Diagnose
= [&] {
8171 S
.Diag(NewC
? NewC
->getBeginLoc() : New
->getBeginLoc(),
8172 diag::err_template_different_type_constraint
);
8173 S
.Diag(OldC
? OldC
->getBeginLoc() : Old
->getBeginLoc(),
8174 diag::note_template_prev_declaration
) << /*declaration*/0;
8177 if (!NewC
!= !OldC
) {
8184 if (!S
.AreConstraintExpressionsEqual(OldInstFrom
, OldC
, NewInstFrom
,
8196 /// Diagnose a known arity mismatch when comparing template argument
8199 void DiagnoseTemplateParameterListArityMismatch(Sema
&S
,
8200 TemplateParameterList
*New
,
8201 TemplateParameterList
*Old
,
8202 Sema::TemplateParameterListEqualKind Kind
,
8203 SourceLocation TemplateArgLoc
) {
8204 unsigned NextDiag
= diag::err_template_param_list_different_arity
;
8205 if (TemplateArgLoc
.isValid()) {
8206 S
.Diag(TemplateArgLoc
, diag::err_template_arg_template_params_mismatch
);
8207 NextDiag
= diag::note_template_param_list_different_arity
;
8209 S
.Diag(New
->getTemplateLoc(), NextDiag
)
8210 << (New
->size() > Old
->size())
8211 << (Kind
!= Sema::TPL_TemplateMatch
)
8212 << SourceRange(New
->getTemplateLoc(), New
->getRAngleLoc());
8213 S
.Diag(Old
->getTemplateLoc(), diag::note_template_prev_declaration
)
8214 << (Kind
!= Sema::TPL_TemplateMatch
)
8215 << SourceRange(Old
->getTemplateLoc(), Old
->getRAngleLoc());
8218 /// Determine whether the given template parameter lists are
8221 /// \param New The new template parameter list, typically written in the
8222 /// source code as part of a new template declaration.
8224 /// \param Old The old template parameter list, typically found via
8225 /// name lookup of the template declared with this template parameter
8228 /// \param Complain If true, this routine will produce a diagnostic if
8229 /// the template parameter lists are not equivalent.
8231 /// \param Kind describes how we are to match the template parameter lists.
8233 /// \param TemplateArgLoc If this source location is valid, then we
8234 /// are actually checking the template parameter list of a template
8235 /// argument (New) against the template parameter list of its
8236 /// corresponding template template parameter (Old). We produce
8237 /// slightly different diagnostics in this scenario.
8239 /// \returns True if the template parameter lists are equal, false
8241 bool Sema::TemplateParameterListsAreEqual(
8242 const TemplateCompareNewDeclInfo
&NewInstFrom
, TemplateParameterList
*New
,
8243 const NamedDecl
*OldInstFrom
, TemplateParameterList
*Old
, bool Complain
,
8244 TemplateParameterListEqualKind Kind
, SourceLocation TemplateArgLoc
) {
8245 if (Old
->size() != New
->size() && Kind
!= TPL_TemplateTemplateArgumentMatch
) {
8247 DiagnoseTemplateParameterListArityMismatch(*this, New
, Old
, Kind
,
8253 // C++0x [temp.arg.template]p3:
8254 // A template-argument matches a template template-parameter (call it P)
8255 // when each of the template parameters in the template-parameter-list of
8256 // the template-argument's corresponding class template or alias template
8257 // (call it A) matches the corresponding template parameter in the
8258 // template-parameter-list of P. [...]
8259 TemplateParameterList::iterator NewParm
= New
->begin();
8260 TemplateParameterList::iterator NewParmEnd
= New
->end();
8261 for (TemplateParameterList::iterator OldParm
= Old
->begin(),
8262 OldParmEnd
= Old
->end();
8263 OldParm
!= OldParmEnd
; ++OldParm
) {
8264 if (Kind
!= TPL_TemplateTemplateArgumentMatch
||
8265 !(*OldParm
)->isTemplateParameterPack()) {
8266 if (NewParm
== NewParmEnd
) {
8268 DiagnoseTemplateParameterListArityMismatch(*this, New
, Old
, Kind
,
8274 if (!MatchTemplateParameterKind(*this, *NewParm
, NewInstFrom
, *OldParm
,
8275 OldInstFrom
, Complain
, Kind
,
8283 // C++0x [temp.arg.template]p3:
8284 // [...] When P's template- parameter-list contains a template parameter
8285 // pack (14.5.3), the template parameter pack will match zero or more
8286 // template parameters or template parameter packs in the
8287 // template-parameter-list of A with the same type and form as the
8288 // template parameter pack in P (ignoring whether those template
8289 // parameters are template parameter packs).
8290 for (; NewParm
!= NewParmEnd
; ++NewParm
) {
8291 if (!MatchTemplateParameterKind(*this, *NewParm
, NewInstFrom
, *OldParm
,
8292 OldInstFrom
, Complain
, Kind
,
8298 // Make sure we exhausted all of the arguments.
8299 if (NewParm
!= NewParmEnd
) {
8301 DiagnoseTemplateParameterListArityMismatch(*this, New
, Old
, Kind
,
8307 if (Kind
!= TPL_TemplateTemplateArgumentMatch
&&
8308 Kind
!= TPL_TemplateParamsEquivalent
) {
8309 const Expr
*NewRC
= New
->getRequiresClause();
8310 const Expr
*OldRC
= Old
->getRequiresClause();
8312 auto Diagnose
= [&] {
8313 Diag(NewRC
? NewRC
->getBeginLoc() : New
->getTemplateLoc(),
8314 diag::err_template_different_requires_clause
);
8315 Diag(OldRC
? OldRC
->getBeginLoc() : Old
->getTemplateLoc(),
8316 diag::note_template_prev_declaration
) << /*declaration*/0;
8319 if (!NewRC
!= !OldRC
) {
8326 if (!AreConstraintExpressionsEqual(OldInstFrom
, OldRC
, NewInstFrom
,
8338 /// Check whether a template can be declared within this scope.
8340 /// If the template declaration is valid in this scope, returns
8341 /// false. Otherwise, issues a diagnostic and returns true.
8343 Sema::CheckTemplateDeclScope(Scope
*S
, TemplateParameterList
*TemplateParams
) {
8347 // Find the nearest enclosing declaration scope.
8348 while ((S
->getFlags() & Scope::DeclScope
) == 0 ||
8349 (S
->getFlags() & Scope::TemplateParamScope
) != 0)
8352 // C++ [temp.pre]p6: [P2096]
8353 // A template, explicit specialization, or partial specialization shall not
8355 DeclContext
*Ctx
= S
->getEntity();
8356 if (Ctx
&& Ctx
->isExternCContext()) {
8357 Diag(TemplateParams
->getTemplateLoc(), diag::err_template_linkage
)
8358 << TemplateParams
->getSourceRange();
8359 if (const LinkageSpecDecl
*LSD
= Ctx
->getExternCContext())
8360 Diag(LSD
->getExternLoc(), diag::note_extern_c_begins_here
);
8363 Ctx
= Ctx
? Ctx
->getRedeclContext() : nullptr;
8366 // A template-declaration can appear only as a namespace scope or
8367 // class scope declaration.
8368 // C++ [temp.expl.spec]p3:
8369 // An explicit specialization may be declared in any scope in which the
8370 // corresponding primary template may be defined.
8371 // C++ [temp.class.spec]p6: [P2096]
8372 // A partial specialization may be declared in any scope in which the
8373 // corresponding primary template may be defined.
8375 if (Ctx
->isFileContext())
8377 if (CXXRecordDecl
*RD
= dyn_cast
<CXXRecordDecl
>(Ctx
)) {
8378 // C++ [temp.mem]p2:
8379 // A local class shall not have member templates.
8380 if (RD
->isLocalClass())
8381 return Diag(TemplateParams
->getTemplateLoc(),
8382 diag::err_template_inside_local_class
)
8383 << TemplateParams
->getSourceRange();
8389 return Diag(TemplateParams
->getTemplateLoc(),
8390 diag::err_template_outside_namespace_or_class_scope
)
8391 << TemplateParams
->getSourceRange();
8394 /// Determine what kind of template specialization the given declaration
8396 static TemplateSpecializationKind
getTemplateSpecializationKind(Decl
*D
) {
8398 return TSK_Undeclared
;
8400 if (CXXRecordDecl
*Record
= dyn_cast
<CXXRecordDecl
>(D
))
8401 return Record
->getTemplateSpecializationKind();
8402 if (FunctionDecl
*Function
= dyn_cast
<FunctionDecl
>(D
))
8403 return Function
->getTemplateSpecializationKind();
8404 if (VarDecl
*Var
= dyn_cast
<VarDecl
>(D
))
8405 return Var
->getTemplateSpecializationKind();
8407 return TSK_Undeclared
;
8410 /// Check whether a specialization is well-formed in the current
8413 /// This routine determines whether a template specialization can be declared
8414 /// in the current context (C++ [temp.expl.spec]p2).
8416 /// \param S the semantic analysis object for which this check is being
8419 /// \param Specialized the entity being specialized or instantiated, which
8420 /// may be a kind of template (class template, function template, etc.) or
8421 /// a member of a class template (member function, static data member,
8424 /// \param PrevDecl the previous declaration of this entity, if any.
8426 /// \param Loc the location of the explicit specialization or instantiation of
8429 /// \param IsPartialSpecialization whether this is a partial specialization of
8430 /// a class template.
8432 /// \returns true if there was an error that we cannot recover from, false
8434 static bool CheckTemplateSpecializationScope(Sema
&S
,
8435 NamedDecl
*Specialized
,
8436 NamedDecl
*PrevDecl
,
8438 bool IsPartialSpecialization
) {
8439 // Keep these "kind" numbers in sync with the %select statements in the
8440 // various diagnostics emitted by this routine.
8442 if (isa
<ClassTemplateDecl
>(Specialized
))
8443 EntityKind
= IsPartialSpecialization
? 1 : 0;
8444 else if (isa
<VarTemplateDecl
>(Specialized
))
8445 EntityKind
= IsPartialSpecialization
? 3 : 2;
8446 else if (isa
<FunctionTemplateDecl
>(Specialized
))
8448 else if (isa
<CXXMethodDecl
>(Specialized
))
8450 else if (isa
<VarDecl
>(Specialized
))
8452 else if (isa
<RecordDecl
>(Specialized
))
8454 else if (isa
<EnumDecl
>(Specialized
) && S
.getLangOpts().CPlusPlus11
)
8457 S
.Diag(Loc
, diag::err_template_spec_unknown_kind
)
8458 << S
.getLangOpts().CPlusPlus11
;
8459 S
.Diag(Specialized
->getLocation(), diag::note_specialized_entity
);
8463 // C++ [temp.expl.spec]p2:
8464 // An explicit specialization may be declared in any scope in which
8465 // the corresponding primary template may be defined.
8466 if (S
.CurContext
->getRedeclContext()->isFunctionOrMethod()) {
8467 S
.Diag(Loc
, diag::err_template_spec_decl_function_scope
)
8472 // C++ [temp.class.spec]p6:
8473 // A class template partial specialization may be declared in any
8474 // scope in which the primary template may be defined.
8475 DeclContext
*SpecializedContext
=
8476 Specialized
->getDeclContext()->getRedeclContext();
8477 DeclContext
*DC
= S
.CurContext
->getRedeclContext();
8479 // Make sure that this redeclaration (or definition) occurs in the same
8480 // scope or an enclosing namespace.
8481 if (!(DC
->isFileContext() ? DC
->Encloses(SpecializedContext
)
8482 : DC
->Equals(SpecializedContext
))) {
8483 if (isa
<TranslationUnitDecl
>(SpecializedContext
))
8484 S
.Diag(Loc
, diag::err_template_spec_redecl_global_scope
)
8485 << EntityKind
<< Specialized
;
8487 auto *ND
= cast
<NamedDecl
>(SpecializedContext
);
8488 int Diag
= diag::err_template_spec_redecl_out_of_scope
;
8489 if (S
.getLangOpts().MicrosoftExt
&& !DC
->isRecord())
8490 Diag
= diag::ext_ms_template_spec_redecl_out_of_scope
;
8491 S
.Diag(Loc
, Diag
) << EntityKind
<< Specialized
8492 << ND
<< isa
<CXXRecordDecl
>(ND
);
8495 S
.Diag(Specialized
->getLocation(), diag::note_specialized_entity
);
8497 // Don't allow specializing in the wrong class during error recovery.
8498 // Otherwise, things can go horribly wrong.
8506 static SourceRange
findTemplateParameterInType(unsigned Depth
, Expr
*E
) {
8507 if (!E
->isTypeDependent())
8508 return SourceLocation();
8509 DependencyChecker
Checker(Depth
, /*IgnoreNonTypeDependent*/true);
8510 Checker
.TraverseStmt(E
);
8511 if (Checker
.MatchLoc
.isInvalid())
8512 return E
->getSourceRange();
8513 return Checker
.MatchLoc
;
8516 static SourceRange
findTemplateParameter(unsigned Depth
, TypeLoc TL
) {
8517 if (!TL
.getType()->isDependentType())
8518 return SourceLocation();
8519 DependencyChecker
Checker(Depth
, /*IgnoreNonTypeDependent*/true);
8520 Checker
.TraverseTypeLoc(TL
);
8521 if (Checker
.MatchLoc
.isInvalid())
8522 return TL
.getSourceRange();
8523 return Checker
.MatchLoc
;
8526 /// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
8527 /// that checks non-type template partial specialization arguments.
8528 static bool CheckNonTypeTemplatePartialSpecializationArgs(
8529 Sema
&S
, SourceLocation TemplateNameLoc
, NonTypeTemplateParmDecl
*Param
,
8530 const TemplateArgument
*Args
, unsigned NumArgs
, bool IsDefaultArgument
) {
8531 for (unsigned I
= 0; I
!= NumArgs
; ++I
) {
8532 if (Args
[I
].getKind() == TemplateArgument::Pack
) {
8533 if (CheckNonTypeTemplatePartialSpecializationArgs(
8534 S
, TemplateNameLoc
, Param
, Args
[I
].pack_begin(),
8535 Args
[I
].pack_size(), IsDefaultArgument
))
8541 if (Args
[I
].getKind() != TemplateArgument::Expression
)
8544 Expr
*ArgExpr
= Args
[I
].getAsExpr();
8546 // We can have a pack expansion of any of the bullets below.
8547 if (PackExpansionExpr
*Expansion
= dyn_cast
<PackExpansionExpr
>(ArgExpr
))
8548 ArgExpr
= Expansion
->getPattern();
8550 // Strip off any implicit casts we added as part of type checking.
8551 while (ImplicitCastExpr
*ICE
= dyn_cast
<ImplicitCastExpr
>(ArgExpr
))
8552 ArgExpr
= ICE
->getSubExpr();
8554 // C++ [temp.class.spec]p8:
8555 // A non-type argument is non-specialized if it is the name of a
8556 // non-type parameter. All other non-type arguments are
8559 // Below, we check the two conditions that only apply to
8560 // specialized non-type arguments, so skip any non-specialized
8562 if (DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(ArgExpr
))
8563 if (isa
<NonTypeTemplateParmDecl
>(DRE
->getDecl()))
8566 // C++ [temp.class.spec]p9:
8567 // Within the argument list of a class template partial
8568 // specialization, the following restrictions apply:
8569 // -- A partially specialized non-type argument expression
8570 // shall not involve a template parameter of the partial
8571 // specialization except when the argument expression is a
8572 // simple identifier.
8573 // -- The type of a template parameter corresponding to a
8574 // specialized non-type argument shall not be dependent on a
8575 // parameter of the specialization.
8576 // DR1315 removes the first bullet, leaving an incoherent set of rules.
8577 // We implement a compromise between the original rules and DR1315:
8578 // -- A specialized non-type template argument shall not be
8579 // type-dependent and the corresponding template parameter
8580 // shall have a non-dependent type.
8581 SourceRange ParamUseRange
=
8582 findTemplateParameterInType(Param
->getDepth(), ArgExpr
);
8583 if (ParamUseRange
.isValid()) {
8584 if (IsDefaultArgument
) {
8585 S
.Diag(TemplateNameLoc
,
8586 diag::err_dependent_non_type_arg_in_partial_spec
);
8587 S
.Diag(ParamUseRange
.getBegin(),
8588 diag::note_dependent_non_type_default_arg_in_partial_spec
)
8591 S
.Diag(ParamUseRange
.getBegin(),
8592 diag::err_dependent_non_type_arg_in_partial_spec
)
8598 ParamUseRange
= findTemplateParameter(
8599 Param
->getDepth(), Param
->getTypeSourceInfo()->getTypeLoc());
8600 if (ParamUseRange
.isValid()) {
8601 S
.Diag(IsDefaultArgument
? TemplateNameLoc
: ArgExpr
->getBeginLoc(),
8602 diag::err_dependent_typed_non_type_arg_in_partial_spec
)
8603 << Param
->getType();
8604 S
.Diag(Param
->getLocation(), diag::note_template_param_here
)
8605 << (IsDefaultArgument
? ParamUseRange
: SourceRange())
8614 /// Check the non-type template arguments of a class template
8615 /// partial specialization according to C++ [temp.class.spec]p9.
8617 /// \param TemplateNameLoc the location of the template name.
8618 /// \param PrimaryTemplate the template parameters of the primary class
8620 /// \param NumExplicit the number of explicitly-specified template arguments.
8621 /// \param TemplateArgs the template arguments of the class template
8622 /// partial specialization.
8624 /// \returns \c true if there was an error, \c false otherwise.
8625 bool Sema::CheckTemplatePartialSpecializationArgs(
8626 SourceLocation TemplateNameLoc
, TemplateDecl
*PrimaryTemplate
,
8627 unsigned NumExplicit
, ArrayRef
<TemplateArgument
> TemplateArgs
) {
8628 // We have to be conservative when checking a template in a dependent
8630 if (PrimaryTemplate
->getDeclContext()->isDependentContext())
8633 TemplateParameterList
*TemplateParams
=
8634 PrimaryTemplate
->getTemplateParameters();
8635 for (unsigned I
= 0, N
= TemplateParams
->size(); I
!= N
; ++I
) {
8636 NonTypeTemplateParmDecl
*Param
8637 = dyn_cast
<NonTypeTemplateParmDecl
>(TemplateParams
->getParam(I
));
8641 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc
,
8642 Param
, &TemplateArgs
[I
],
8643 1, I
>= NumExplicit
))
8650 DeclResult
Sema::ActOnClassTemplateSpecialization(
8651 Scope
*S
, unsigned TagSpec
, TagUseKind TUK
, SourceLocation KWLoc
,
8652 SourceLocation ModulePrivateLoc
, CXXScopeSpec
&SS
,
8653 TemplateIdAnnotation
&TemplateId
, const ParsedAttributesView
&Attr
,
8654 MultiTemplateParamsArg TemplateParameterLists
, SkipBodyInfo
*SkipBody
) {
8655 assert(TUK
!= TUK_Reference
&& "References are not specializations");
8657 // NOTE: KWLoc is the location of the tag keyword. This will instead
8658 // store the location of the outermost template keyword in the declaration.
8659 SourceLocation TemplateKWLoc
= TemplateParameterLists
.size() > 0
8660 ? TemplateParameterLists
[0]->getTemplateLoc() : KWLoc
;
8661 SourceLocation TemplateNameLoc
= TemplateId
.TemplateNameLoc
;
8662 SourceLocation LAngleLoc
= TemplateId
.LAngleLoc
;
8663 SourceLocation RAngleLoc
= TemplateId
.RAngleLoc
;
8665 // Find the class template we're specializing
8666 TemplateName Name
= TemplateId
.Template
.get();
8667 ClassTemplateDecl
*ClassTemplate
8668 = dyn_cast_or_null
<ClassTemplateDecl
>(Name
.getAsTemplateDecl());
8670 if (!ClassTemplate
) {
8671 Diag(TemplateNameLoc
, diag::err_not_class_template_specialization
)
8672 << (Name
.getAsTemplateDecl() &&
8673 isa
<TemplateTemplateParmDecl
>(Name
.getAsTemplateDecl()));
8677 bool isMemberSpecialization
= false;
8678 bool isPartialSpecialization
= false;
8680 // Check the validity of the template headers that introduce this
8682 // FIXME: We probably shouldn't complain about these headers for
8683 // friend declarations.
8684 bool Invalid
= false;
8685 TemplateParameterList
*TemplateParams
=
8686 MatchTemplateParametersToScopeSpecifier(
8687 KWLoc
, TemplateNameLoc
, SS
, &TemplateId
,
8688 TemplateParameterLists
, TUK
== TUK_Friend
, isMemberSpecialization
,
8693 // Check that we can declare a template specialization here.
8694 if (TemplateParams
&& CheckTemplateDeclScope(S
, TemplateParams
))
8697 if (TemplateParams
&& TemplateParams
->size() > 0) {
8698 isPartialSpecialization
= true;
8700 if (TUK
== TUK_Friend
) {
8701 Diag(KWLoc
, diag::err_partial_specialization_friend
)
8702 << SourceRange(LAngleLoc
, RAngleLoc
);
8706 // C++ [temp.class.spec]p10:
8707 // The template parameter list of a specialization shall not
8708 // contain default template argument values.
8709 for (unsigned I
= 0, N
= TemplateParams
->size(); I
!= N
; ++I
) {
8710 Decl
*Param
= TemplateParams
->getParam(I
);
8711 if (TemplateTypeParmDecl
*TTP
= dyn_cast
<TemplateTypeParmDecl
>(Param
)) {
8712 if (TTP
->hasDefaultArgument()) {
8713 Diag(TTP
->getDefaultArgumentLoc(),
8714 diag::err_default_arg_in_partial_spec
);
8715 TTP
->removeDefaultArgument();
8717 } else if (NonTypeTemplateParmDecl
*NTTP
8718 = dyn_cast
<NonTypeTemplateParmDecl
>(Param
)) {
8719 if (Expr
*DefArg
= NTTP
->getDefaultArgument()) {
8720 Diag(NTTP
->getDefaultArgumentLoc(),
8721 diag::err_default_arg_in_partial_spec
)
8722 << DefArg
->getSourceRange();
8723 NTTP
->removeDefaultArgument();
8726 TemplateTemplateParmDecl
*TTP
= cast
<TemplateTemplateParmDecl
>(Param
);
8727 if (TTP
->hasDefaultArgument()) {
8728 Diag(TTP
->getDefaultArgument().getLocation(),
8729 diag::err_default_arg_in_partial_spec
)
8730 << TTP
->getDefaultArgument().getSourceRange();
8731 TTP
->removeDefaultArgument();
8735 } else if (TemplateParams
) {
8736 if (TUK
== TUK_Friend
)
8737 Diag(KWLoc
, diag::err_template_spec_friend
)
8738 << FixItHint::CreateRemoval(
8739 SourceRange(TemplateParams
->getTemplateLoc(),
8740 TemplateParams
->getRAngleLoc()))
8741 << SourceRange(LAngleLoc
, RAngleLoc
);
8743 assert(TUK
== TUK_Friend
&& "should have a 'template<>' for this decl");
8746 // Check that the specialization uses the same tag kind as the
8747 // original template.
8748 TagTypeKind Kind
= TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec
);
8749 assert(Kind
!= TTK_Enum
&& "Invalid enum tag in class template spec!");
8750 if (!isAcceptableTagRedeclaration(ClassTemplate
->getTemplatedDecl(),
8751 Kind
, TUK
== TUK_Definition
, KWLoc
,
8752 ClassTemplate
->getIdentifier())) {
8753 Diag(KWLoc
, diag::err_use_with_wrong_tag
)
8755 << FixItHint::CreateReplacement(KWLoc
,
8756 ClassTemplate
->getTemplatedDecl()->getKindName());
8757 Diag(ClassTemplate
->getTemplatedDecl()->getLocation(),
8758 diag::note_previous_use
);
8759 Kind
= ClassTemplate
->getTemplatedDecl()->getTagKind();
8762 // Translate the parser's template argument list in our AST format.
8763 TemplateArgumentListInfo TemplateArgs
=
8764 makeTemplateArgumentListInfo(*this, TemplateId
);
8766 // Check for unexpanded parameter packs in any of the template arguments.
8767 for (unsigned I
= 0, N
= TemplateArgs
.size(); I
!= N
; ++I
)
8768 if (DiagnoseUnexpandedParameterPack(TemplateArgs
[I
],
8769 UPPC_PartialSpecialization
))
8772 // Check that the template argument list is well-formed for this
8774 SmallVector
<TemplateArgument
, 4> SugaredConverted
, CanonicalConverted
;
8775 if (CheckTemplateArgumentList(ClassTemplate
, TemplateNameLoc
, TemplateArgs
,
8776 false, SugaredConverted
, CanonicalConverted
,
8777 /*UpdateArgsWithConversions=*/true))
8780 // Find the class template (partial) specialization declaration that
8781 // corresponds to these arguments.
8782 if (isPartialSpecialization
) {
8783 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc
, ClassTemplate
,
8784 TemplateArgs
.size(),
8785 CanonicalConverted
))
8788 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8789 // also do it during instantiation.
8790 if (!Name
.isDependent() &&
8791 !TemplateSpecializationType::anyDependentTemplateArguments(
8792 TemplateArgs
, CanonicalConverted
)) {
8793 Diag(TemplateNameLoc
, diag::err_partial_spec_fully_specialized
)
8794 << ClassTemplate
->getDeclName();
8795 isPartialSpecialization
= false;
8799 void *InsertPos
= nullptr;
8800 ClassTemplateSpecializationDecl
*PrevDecl
= nullptr;
8802 if (isPartialSpecialization
)
8803 PrevDecl
= ClassTemplate
->findPartialSpecialization(
8804 CanonicalConverted
, TemplateParams
, InsertPos
);
8806 PrevDecl
= ClassTemplate
->findSpecialization(CanonicalConverted
, InsertPos
);
8808 ClassTemplateSpecializationDecl
*Specialization
= nullptr;
8810 // Check whether we can declare a class template specialization in
8811 // the current scope.
8812 if (TUK
!= TUK_Friend
&&
8813 CheckTemplateSpecializationScope(*this, ClassTemplate
, PrevDecl
,
8815 isPartialSpecialization
))
8818 // The canonical type
8820 if (isPartialSpecialization
) {
8821 // Build the canonical type that describes the converted template
8822 // arguments of the class template partial specialization.
8823 TemplateName CanonTemplate
= Context
.getCanonicalTemplateName(Name
);
8824 CanonType
= Context
.getTemplateSpecializationType(CanonTemplate
,
8825 CanonicalConverted
);
8827 if (Context
.hasSameType(CanonType
,
8828 ClassTemplate
->getInjectedClassNameSpecialization()) &&
8829 (!Context
.getLangOpts().CPlusPlus20
||
8830 !TemplateParams
->hasAssociatedConstraints())) {
8831 // C++ [temp.class.spec]p9b3:
8833 // -- The argument list of the specialization shall not be identical
8834 // to the implicit argument list of the primary template.
8836 // This rule has since been removed, because it's redundant given DR1495,
8837 // but we keep it because it produces better diagnostics and recovery.
8838 Diag(TemplateNameLoc
, diag::err_partial_spec_args_match_primary_template
)
8839 << /*class template*/0 << (TUK
== TUK_Definition
)
8840 << FixItHint::CreateRemoval(SourceRange(LAngleLoc
, RAngleLoc
));
8841 return CheckClassTemplate(S
, TagSpec
, TUK
, KWLoc
, SS
,
8842 ClassTemplate
->getIdentifier(),
8846 AS_none
, /*ModulePrivateLoc=*/SourceLocation(),
8847 /*FriendLoc*/SourceLocation(),
8848 TemplateParameterLists
.size() - 1,
8849 TemplateParameterLists
.data());
8852 // Create a new class template partial specialization declaration node.
8853 ClassTemplatePartialSpecializationDecl
*PrevPartial
8854 = cast_or_null
<ClassTemplatePartialSpecializationDecl
>(PrevDecl
);
8855 ClassTemplatePartialSpecializationDecl
*Partial
=
8856 ClassTemplatePartialSpecializationDecl::Create(
8857 Context
, Kind
, ClassTemplate
->getDeclContext(), KWLoc
,
8858 TemplateNameLoc
, TemplateParams
, ClassTemplate
, CanonicalConverted
,
8859 TemplateArgs
, CanonType
, PrevPartial
);
8860 SetNestedNameSpecifier(*this, Partial
, SS
);
8861 if (TemplateParameterLists
.size() > 1 && SS
.isSet()) {
8862 Partial
->setTemplateParameterListsInfo(
8863 Context
, TemplateParameterLists
.drop_back(1));
8867 ClassTemplate
->AddPartialSpecialization(Partial
, InsertPos
);
8868 Specialization
= Partial
;
8870 // If we are providing an explicit specialization of a member class
8871 // template specialization, make a note of that.
8872 if (PrevPartial
&& PrevPartial
->getInstantiatedFromMember())
8873 PrevPartial
->setMemberSpecialization();
8875 CheckTemplatePartialSpecialization(Partial
);
8877 // Create a new class template specialization declaration node for
8878 // this explicit specialization or friend declaration.
8879 Specialization
= ClassTemplateSpecializationDecl::Create(
8880 Context
, Kind
, ClassTemplate
->getDeclContext(), KWLoc
, TemplateNameLoc
,
8881 ClassTemplate
, CanonicalConverted
, PrevDecl
);
8882 SetNestedNameSpecifier(*this, Specialization
, SS
);
8883 if (TemplateParameterLists
.size() > 0) {
8884 Specialization
->setTemplateParameterListsInfo(Context
,
8885 TemplateParameterLists
);
8889 ClassTemplate
->AddSpecialization(Specialization
, InsertPos
);
8891 if (CurContext
->isDependentContext()) {
8892 TemplateName CanonTemplate
= Context
.getCanonicalTemplateName(Name
);
8893 CanonType
= Context
.getTemplateSpecializationType(CanonTemplate
,
8894 CanonicalConverted
);
8896 CanonType
= Context
.getTypeDeclType(Specialization
);
8900 // C++ [temp.expl.spec]p6:
8901 // If a template, a member template or the member of a class template is
8902 // explicitly specialized then that specialization shall be declared
8903 // before the first use of that specialization that would cause an implicit
8904 // instantiation to take place, in every translation unit in which such a
8905 // use occurs; no diagnostic is required.
8906 if (PrevDecl
&& PrevDecl
->getPointOfInstantiation().isValid()) {
8908 for (Decl
*Prev
= PrevDecl
; Prev
; Prev
= Prev
->getPreviousDecl()) {
8909 // Is there any previous explicit specialization declaration?
8910 if (getTemplateSpecializationKind(Prev
) == TSK_ExplicitSpecialization
) {
8917 SourceRange
Range(TemplateNameLoc
, RAngleLoc
);
8918 Diag(TemplateNameLoc
, diag::err_specialization_after_instantiation
)
8919 << Context
.getTypeDeclType(Specialization
) << Range
;
8921 Diag(PrevDecl
->getPointOfInstantiation(),
8922 diag::note_instantiation_required_here
)
8923 << (PrevDecl
->getTemplateSpecializationKind()
8924 != TSK_ImplicitInstantiation
);
8929 // If this is not a friend, note that this is an explicit specialization.
8930 if (TUK
!= TUK_Friend
)
8931 Specialization
->setSpecializationKind(TSK_ExplicitSpecialization
);
8933 // Check that this isn't a redefinition of this specialization.
8934 if (TUK
== TUK_Definition
) {
8935 RecordDecl
*Def
= Specialization
->getDefinition();
8936 NamedDecl
*Hidden
= nullptr;
8937 if (Def
&& SkipBody
&& !hasVisibleDefinition(Def
, &Hidden
)) {
8938 SkipBody
->ShouldSkip
= true;
8939 SkipBody
->Previous
= Def
;
8940 makeMergedDefinitionVisible(Hidden
);
8942 SourceRange
Range(TemplateNameLoc
, RAngleLoc
);
8943 Diag(TemplateNameLoc
, diag::err_redefinition
) << Specialization
<< Range
;
8944 Diag(Def
->getLocation(), diag::note_previous_definition
);
8945 Specialization
->setInvalidDecl();
8950 ProcessDeclAttributeList(S
, Specialization
, Attr
);
8952 // Add alignment attributes if necessary; these attributes are checked when
8953 // the ASTContext lays out the structure.
8954 if (TUK
== TUK_Definition
&& (!SkipBody
|| !SkipBody
->ShouldSkip
)) {
8955 AddAlignmentAttributesForRecord(Specialization
);
8956 AddMsStructLayoutForRecord(Specialization
);
8959 if (ModulePrivateLoc
.isValid())
8960 Diag(Specialization
->getLocation(), diag::err_module_private_specialization
)
8961 << (isPartialSpecialization
? 1 : 0)
8962 << FixItHint::CreateRemoval(ModulePrivateLoc
);
8964 // Build the fully-sugared type for this class template
8965 // specialization as the user wrote in the specialization
8966 // itself. This means that we'll pretty-print the type retrieved
8967 // from the specialization's declaration the way that the user
8968 // actually wrote the specialization, rather than formatting the
8969 // name based on the "canonical" representation used to store the
8970 // template arguments in the specialization.
8971 TypeSourceInfo
*WrittenTy
8972 = Context
.getTemplateSpecializationTypeInfo(Name
, TemplateNameLoc
,
8973 TemplateArgs
, CanonType
);
8974 if (TUK
!= TUK_Friend
) {
8975 Specialization
->setTypeAsWritten(WrittenTy
);
8976 Specialization
->setTemplateKeywordLoc(TemplateKWLoc
);
8979 // C++ [temp.expl.spec]p9:
8980 // A template explicit specialization is in the scope of the
8981 // namespace in which the template was defined.
8983 // We actually implement this paragraph where we set the semantic
8984 // context (in the creation of the ClassTemplateSpecializationDecl),
8985 // but we also maintain the lexical context where the actual
8986 // definition occurs.
8987 Specialization
->setLexicalDeclContext(CurContext
);
8989 // We may be starting the definition of this specialization.
8990 if (TUK
== TUK_Definition
&& (!SkipBody
|| !SkipBody
->ShouldSkip
))
8991 Specialization
->startDefinition();
8993 if (TUK
== TUK_Friend
) {
8994 FriendDecl
*Friend
= FriendDecl::Create(Context
, CurContext
,
8998 Friend
->setAccess(AS_public
);
8999 CurContext
->addDecl(Friend
);
9001 // Add the specialization into its lexical context, so that it can
9002 // be seen when iterating through the list of declarations in that
9003 // context. However, specializations are not found by name lookup.
9004 CurContext
->addDecl(Specialization
);
9007 if (SkipBody
&& SkipBody
->ShouldSkip
)
9008 return SkipBody
->Previous
;
9010 return Specialization
;
9013 Decl
*Sema::ActOnTemplateDeclarator(Scope
*S
,
9014 MultiTemplateParamsArg TemplateParameterLists
,
9016 Decl
*NewDecl
= HandleDeclarator(S
, D
, TemplateParameterLists
);
9017 ActOnDocumentableDecl(NewDecl
);
9021 Decl
*Sema::ActOnConceptDefinition(Scope
*S
,
9022 MultiTemplateParamsArg TemplateParameterLists
,
9023 IdentifierInfo
*Name
, SourceLocation NameLoc
,
9024 Expr
*ConstraintExpr
) {
9025 DeclContext
*DC
= CurContext
;
9027 if (!DC
->getRedeclContext()->isFileContext()) {
9029 diag::err_concept_decls_may_only_appear_in_global_namespace_scope
);
9033 if (TemplateParameterLists
.size() > 1) {
9034 Diag(NameLoc
, diag::err_concept_extra_headers
);
9038 TemplateParameterList
*Params
= TemplateParameterLists
.front();
9040 if (Params
->size() == 0) {
9041 Diag(NameLoc
, diag::err_concept_no_parameters
);
9045 // Ensure that the parameter pack, if present, is the last parameter in the
9047 for (TemplateParameterList::const_iterator ParamIt
= Params
->begin(),
9048 ParamEnd
= Params
->end();
9049 ParamIt
!= ParamEnd
; ++ParamIt
) {
9050 Decl
const *Param
= *ParamIt
;
9051 if (Param
->isParameterPack()) {
9052 if (++ParamIt
== ParamEnd
)
9054 Diag(Param
->getLocation(),
9055 diag::err_template_param_pack_must_be_last_template_parameter
);
9060 if (DiagnoseUnexpandedParameterPack(ConstraintExpr
))
9063 ConceptDecl
*NewDecl
=
9064 ConceptDecl::Create(Context
, DC
, NameLoc
, Name
, Params
, ConstraintExpr
);
9066 if (NewDecl
->hasAssociatedConstraints()) {
9067 // C++2a [temp.concept]p4:
9068 // A concept shall not have associated constraints.
9069 Diag(NameLoc
, diag::err_concept_no_associated_constraints
);
9070 NewDecl
->setInvalidDecl();
9073 // Check for conflicting previous declaration.
9074 DeclarationNameInfo
NameInfo(NewDecl
->getDeclName(), NameLoc
);
9075 LookupResult
Previous(*this, NameInfo
, LookupOrdinaryName
,
9076 forRedeclarationInCurContext());
9077 LookupName(Previous
, S
);
9078 FilterLookupForScope(Previous
, DC
, S
, /*ConsiderLinkage=*/false,
9079 /*AllowInlineNamespace*/false);
9080 bool AddToScope
= true;
9081 CheckConceptRedefinition(NewDecl
, Previous
, AddToScope
);
9083 ActOnDocumentableDecl(NewDecl
);
9085 PushOnScopeChains(NewDecl
, S
);
9089 void Sema::CheckConceptRedefinition(ConceptDecl
*NewDecl
,
9090 LookupResult
&Previous
, bool &AddToScope
) {
9093 if (Previous
.empty())
9096 auto *OldConcept
= dyn_cast
<ConceptDecl
>(Previous
.getRepresentativeDecl()->getUnderlyingDecl());
9098 auto *Old
= Previous
.getRepresentativeDecl();
9099 Diag(NewDecl
->getLocation(), diag::err_redefinition_different_kind
)
9100 << NewDecl
->getDeclName();
9101 notePreviousDefinition(Old
, NewDecl
->getLocation());
9105 // Check if we can merge with a concept declaration.
9106 bool IsSame
= Context
.isSameEntity(NewDecl
, OldConcept
);
9108 Diag(NewDecl
->getLocation(), diag::err_redefinition_different_concept
)
9109 << NewDecl
->getDeclName();
9110 notePreviousDefinition(OldConcept
, NewDecl
->getLocation());
9114 if (hasReachableDefinition(OldConcept
) &&
9115 IsRedefinitionInModule(NewDecl
, OldConcept
)) {
9116 Diag(NewDecl
->getLocation(), diag::err_redefinition
)
9117 << NewDecl
->getDeclName();
9118 notePreviousDefinition(OldConcept
, NewDecl
->getLocation());
9122 if (!Previous
.isSingleResult()) {
9123 // FIXME: we should produce an error in case of ambig and failed lookups.
9124 // Other decls (e.g. namespaces) also have this shortcoming.
9127 // We unwrap canonical decl late to check for module visibility.
9128 Context
.setPrimaryMergedDecl(NewDecl
, OldConcept
->getCanonicalDecl());
9131 /// \brief Strips various properties off an implicit instantiation
9132 /// that has just been explicitly specialized.
9133 static void StripImplicitInstantiation(NamedDecl
*D
, bool MinGW
) {
9134 if (MinGW
|| (isa
<FunctionDecl
>(D
) &&
9135 cast
<FunctionDecl
>(D
)->isFunctionTemplateSpecialization())) {
9136 D
->dropAttr
<DLLImportAttr
>();
9137 D
->dropAttr
<DLLExportAttr
>();
9140 if (FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(D
))
9141 FD
->setInlineSpecified(false);
9144 /// Compute the diagnostic location for an explicit instantiation
9145 // declaration or definition.
9146 static SourceLocation
DiagLocForExplicitInstantiation(
9147 NamedDecl
* D
, SourceLocation PointOfInstantiation
) {
9148 // Explicit instantiations following a specialization have no effect and
9149 // hence no PointOfInstantiation. In that case, walk decl backwards
9150 // until a valid name loc is found.
9151 SourceLocation PrevDiagLoc
= PointOfInstantiation
;
9152 for (Decl
*Prev
= D
; Prev
&& !PrevDiagLoc
.isValid();
9153 Prev
= Prev
->getPreviousDecl()) {
9154 PrevDiagLoc
= Prev
->getLocation();
9156 assert(PrevDiagLoc
.isValid() &&
9157 "Explicit instantiation without point of instantiation?");
9161 /// Diagnose cases where we have an explicit template specialization
9162 /// before/after an explicit template instantiation, producing diagnostics
9163 /// for those cases where they are required and determining whether the
9164 /// new specialization/instantiation will have any effect.
9166 /// \param NewLoc the location of the new explicit specialization or
9169 /// \param NewTSK the kind of the new explicit specialization or instantiation.
9171 /// \param PrevDecl the previous declaration of the entity.
9173 /// \param PrevTSK the kind of the old explicit specialization or instantiatin.
9175 /// \param PrevPointOfInstantiation if valid, indicates where the previous
9176 /// declaration was instantiated (either implicitly or explicitly).
9178 /// \param HasNoEffect will be set to true to indicate that the new
9179 /// specialization or instantiation has no effect and should be ignored.
9181 /// \returns true if there was an error that should prevent the introduction of
9182 /// the new declaration into the AST, false otherwise.
9184 Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc
,
9185 TemplateSpecializationKind NewTSK
,
9186 NamedDecl
*PrevDecl
,
9187 TemplateSpecializationKind PrevTSK
,
9188 SourceLocation PrevPointOfInstantiation
,
9189 bool &HasNoEffect
) {
9190 HasNoEffect
= false;
9193 case TSK_Undeclared
:
9194 case TSK_ImplicitInstantiation
:
9196 (PrevTSK
== TSK_Undeclared
|| PrevTSK
== TSK_ImplicitInstantiation
) &&
9197 "previous declaration must be implicit!");
9200 case TSK_ExplicitSpecialization
:
9202 case TSK_Undeclared
:
9203 case TSK_ExplicitSpecialization
:
9204 // Okay, we're just specializing something that is either already
9205 // explicitly specialized or has merely been mentioned without any
9209 case TSK_ImplicitInstantiation
:
9210 if (PrevPointOfInstantiation
.isInvalid()) {
9211 // The declaration itself has not actually been instantiated, so it is
9212 // still okay to specialize it.
9213 StripImplicitInstantiation(
9215 Context
.getTargetInfo().getTriple().isWindowsGNUEnvironment());
9221 case TSK_ExplicitInstantiationDeclaration
:
9222 case TSK_ExplicitInstantiationDefinition
:
9223 assert((PrevTSK
== TSK_ImplicitInstantiation
||
9224 PrevPointOfInstantiation
.isValid()) &&
9225 "Explicit instantiation without point of instantiation?");
9227 // C++ [temp.expl.spec]p6:
9228 // If a template, a member template or the member of a class template
9229 // is explicitly specialized then that specialization shall be declared
9230 // before the first use of that specialization that would cause an
9231 // implicit instantiation to take place, in every translation unit in
9232 // which such a use occurs; no diagnostic is required.
9233 for (Decl
*Prev
= PrevDecl
; Prev
; Prev
= Prev
->getPreviousDecl()) {
9234 // Is there any previous explicit specialization declaration?
9235 if (getTemplateSpecializationKind(Prev
) == TSK_ExplicitSpecialization
)
9239 Diag(NewLoc
, diag::err_specialization_after_instantiation
)
9241 Diag(PrevPointOfInstantiation
, diag::note_instantiation_required_here
)
9242 << (PrevTSK
!= TSK_ImplicitInstantiation
);
9246 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
9248 case TSK_ExplicitInstantiationDeclaration
:
9250 case TSK_ExplicitInstantiationDeclaration
:
9251 // This explicit instantiation declaration is redundant (that's okay).
9255 case TSK_Undeclared
:
9256 case TSK_ImplicitInstantiation
:
9257 // We're explicitly instantiating something that may have already been
9258 // implicitly instantiated; that's fine.
9261 case TSK_ExplicitSpecialization
:
9262 // C++0x [temp.explicit]p4:
9263 // For a given set of template parameters, if an explicit instantiation
9264 // of a template appears after a declaration of an explicit
9265 // specialization for that template, the explicit instantiation has no
9270 case TSK_ExplicitInstantiationDefinition
:
9271 // C++0x [temp.explicit]p10:
9272 // If an entity is the subject of both an explicit instantiation
9273 // declaration and an explicit instantiation definition in the same
9274 // translation unit, the definition shall follow the declaration.
9276 diag::err_explicit_instantiation_declaration_after_definition
);
9278 // Explicit instantiations following a specialization have no effect and
9279 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
9280 // until a valid name loc is found.
9281 Diag(DiagLocForExplicitInstantiation(PrevDecl
, PrevPointOfInstantiation
),
9282 diag::note_explicit_instantiation_definition_here
);
9286 llvm_unreachable("Unexpected TemplateSpecializationKind!");
9288 case TSK_ExplicitInstantiationDefinition
:
9290 case TSK_Undeclared
:
9291 case TSK_ImplicitInstantiation
:
9292 // We're explicitly instantiating something that may have already been
9293 // implicitly instantiated; that's fine.
9296 case TSK_ExplicitSpecialization
:
9297 // C++ DR 259, C++0x [temp.explicit]p4:
9298 // For a given set of template parameters, if an explicit
9299 // instantiation of a template appears after a declaration of
9300 // an explicit specialization for that template, the explicit
9301 // instantiation has no effect.
9302 Diag(NewLoc
, diag::warn_explicit_instantiation_after_specialization
)
9304 Diag(PrevDecl
->getLocation(),
9305 diag::note_previous_template_specialization
);
9309 case TSK_ExplicitInstantiationDeclaration
:
9310 // We're explicitly instantiating a definition for something for which we
9311 // were previously asked to suppress instantiations. That's fine.
9313 // C++0x [temp.explicit]p4:
9314 // For a given set of template parameters, if an explicit instantiation
9315 // of a template appears after a declaration of an explicit
9316 // specialization for that template, the explicit instantiation has no
9318 for (Decl
*Prev
= PrevDecl
; Prev
; Prev
= Prev
->getPreviousDecl()) {
9319 // Is there any previous explicit specialization declaration?
9320 if (getTemplateSpecializationKind(Prev
) == TSK_ExplicitSpecialization
) {
9328 case TSK_ExplicitInstantiationDefinition
:
9329 // C++0x [temp.spec]p5:
9330 // For a given template and a given set of template-arguments,
9331 // - an explicit instantiation definition shall appear at most once
9334 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
9335 Diag(NewLoc
, (getLangOpts().MSVCCompat
)
9336 ? diag::ext_explicit_instantiation_duplicate
9337 : diag::err_explicit_instantiation_duplicate
)
9339 Diag(DiagLocForExplicitInstantiation(PrevDecl
, PrevPointOfInstantiation
),
9340 diag::note_previous_explicit_instantiation
);
9346 llvm_unreachable("Missing specialization/instantiation case?");
9349 /// Perform semantic analysis for the given dependent function
9350 /// template specialization.
9352 /// The only possible way to get a dependent function template specialization
9353 /// is with a friend declaration, like so:
9356 /// template \<class T> void foo(T);
9357 /// template \<class T> class A {
9358 /// friend void foo<>(T);
9362 /// There really isn't any useful analysis we can do here, so we
9363 /// just store the information.
9364 bool Sema::CheckDependentFunctionTemplateSpecialization(
9365 FunctionDecl
*FD
, const TemplateArgumentListInfo
*ExplicitTemplateArgs
,
9366 LookupResult
&Previous
) {
9367 // Remove anything from Previous that isn't a function template in
9368 // the correct context.
9369 DeclContext
*FDLookupContext
= FD
->getDeclContext()->getRedeclContext();
9370 LookupResult::Filter F
= Previous
.makeFilter();
9371 enum DiscardReason
{ NotAFunctionTemplate
, NotAMemberOfEnclosing
};
9372 SmallVector
<std::pair
<DiscardReason
, Decl
*>, 8> DiscardedCandidates
;
9373 while (F
.hasNext()) {
9374 NamedDecl
*D
= F
.next()->getUnderlyingDecl();
9375 if (!isa
<FunctionTemplateDecl
>(D
)) {
9377 DiscardedCandidates
.push_back(std::make_pair(NotAFunctionTemplate
, D
));
9381 if (!FDLookupContext
->InEnclosingNamespaceSetOf(
9382 D
->getDeclContext()->getRedeclContext())) {
9384 DiscardedCandidates
.push_back(std::make_pair(NotAMemberOfEnclosing
, D
));
9390 bool IsFriend
= FD
->getFriendObjectKind() != Decl::FOK_None
;
9391 if (Previous
.empty()) {
9392 Diag(FD
->getLocation(), diag::err_dependent_function_template_spec_no_match
)
9394 for (auto &P
: DiscardedCandidates
)
9395 Diag(P
.second
->getLocation(),
9396 diag::note_dependent_function_template_spec_discard_reason
)
9397 << P
.first
<< IsFriend
;
9401 FD
->setDependentTemplateSpecialization(Context
, Previous
.asUnresolvedSet(),
9402 ExplicitTemplateArgs
);
9406 /// Perform semantic analysis for the given function template
9409 /// This routine performs all of the semantic analysis required for an
9410 /// explicit function template specialization. On successful completion,
9411 /// the function declaration \p FD will become a function template
9414 /// \param FD the function declaration, which will be updated to become a
9415 /// function template specialization.
9417 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
9418 /// if any. Note that this may be valid info even when 0 arguments are
9419 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
9420 /// as it anyway contains info on the angle brackets locations.
9422 /// \param Previous the set of declarations that may be specialized by
9423 /// this function specialization.
9425 /// \param QualifiedFriend whether this is a lookup for a qualified friend
9426 /// declaration with no explicit template argument list that might be
9427 /// befriending a function template specialization.
9428 bool Sema::CheckFunctionTemplateSpecialization(
9429 FunctionDecl
*FD
, TemplateArgumentListInfo
*ExplicitTemplateArgs
,
9430 LookupResult
&Previous
, bool QualifiedFriend
) {
9431 // The set of function template specializations that could match this
9432 // explicit function template specialization.
9433 UnresolvedSet
<8> Candidates
;
9434 TemplateSpecCandidateSet
FailedCandidates(FD
->getLocation(),
9435 /*ForTakingAddress=*/false);
9437 llvm::SmallDenseMap
<FunctionDecl
*, TemplateArgumentListInfo
, 8>
9438 ConvertedTemplateArgs
;
9440 DeclContext
*FDLookupContext
= FD
->getDeclContext()->getRedeclContext();
9441 for (LookupResult::iterator I
= Previous
.begin(), E
= Previous
.end();
9443 NamedDecl
*Ovl
= (*I
)->getUnderlyingDecl();
9444 if (FunctionTemplateDecl
*FunTmpl
= dyn_cast
<FunctionTemplateDecl
>(Ovl
)) {
9445 // Only consider templates found within the same semantic lookup scope as
9447 if (!FDLookupContext
->InEnclosingNamespaceSetOf(
9448 Ovl
->getDeclContext()->getRedeclContext()))
9451 // When matching a constexpr member function template specialization
9452 // against the primary template, we don't yet know whether the
9453 // specialization has an implicit 'const' (because we don't know whether
9454 // it will be a static member function until we know which template it
9455 // specializes), so adjust it now assuming it specializes this template.
9456 QualType FT
= FD
->getType();
9457 if (FD
->isConstexpr()) {
9458 CXXMethodDecl
*OldMD
=
9459 dyn_cast
<CXXMethodDecl
>(FunTmpl
->getTemplatedDecl());
9460 if (OldMD
&& OldMD
->isConst()) {
9461 const FunctionProtoType
*FPT
= FT
->castAs
<FunctionProtoType
>();
9462 FunctionProtoType::ExtProtoInfo EPI
= FPT
->getExtProtoInfo();
9463 EPI
.TypeQuals
.addConst();
9464 FT
= Context
.getFunctionType(FPT
->getReturnType(),
9465 FPT
->getParamTypes(), EPI
);
9469 TemplateArgumentListInfo Args
;
9470 if (ExplicitTemplateArgs
)
9471 Args
= *ExplicitTemplateArgs
;
9473 // C++ [temp.expl.spec]p11:
9474 // A trailing template-argument can be left unspecified in the
9475 // template-id naming an explicit function template specialization
9476 // provided it can be deduced from the function argument type.
9477 // Perform template argument deduction to determine whether we may be
9478 // specializing this template.
9479 // FIXME: It is somewhat wasteful to build
9480 TemplateDeductionInfo
Info(FailedCandidates
.getLocation());
9481 FunctionDecl
*Specialization
= nullptr;
9482 if (TemplateDeductionResult TDK
= DeduceTemplateArguments(
9483 cast
<FunctionTemplateDecl
>(FunTmpl
->getFirstDecl()),
9484 ExplicitTemplateArgs
? &Args
: nullptr, FT
, Specialization
,
9486 // Template argument deduction failed; record why it failed, so
9487 // that we can provide nifty diagnostics.
9488 FailedCandidates
.addCandidate().set(
9489 I
.getPair(), FunTmpl
->getTemplatedDecl(),
9490 MakeDeductionFailureInfo(Context
, TDK
, Info
));
9495 // Target attributes are part of the cuda function signature, so
9496 // the deduced template's cuda target must match that of the
9497 // specialization. Given that C++ template deduction does not
9498 // take target attributes into account, we reject candidates
9499 // here that have a different target.
9500 if (LangOpts
.CUDA
&&
9501 IdentifyCUDATarget(Specialization
,
9502 /* IgnoreImplicitHDAttr = */ true) !=
9503 IdentifyCUDATarget(FD
, /* IgnoreImplicitHDAttr = */ true)) {
9504 FailedCandidates
.addCandidate().set(
9505 I
.getPair(), FunTmpl
->getTemplatedDecl(),
9506 MakeDeductionFailureInfo(Context
, TDK_CUDATargetMismatch
, Info
));
9510 // Record this candidate.
9511 if (ExplicitTemplateArgs
)
9512 ConvertedTemplateArgs
[Specialization
] = std::move(Args
);
9513 Candidates
.addDecl(Specialization
, I
.getAccess());
9517 // For a qualified friend declaration (with no explicit marker to indicate
9518 // that a template specialization was intended), note all (template and
9519 // non-template) candidates.
9520 if (QualifiedFriend
&& Candidates
.empty()) {
9521 Diag(FD
->getLocation(), diag::err_qualified_friend_no_match
)
9522 << FD
->getDeclName() << FDLookupContext
;
9523 // FIXME: We should form a single candidate list and diagnose all
9524 // candidates at once, to get proper sorting and limiting.
9525 for (auto *OldND
: Previous
) {
9526 if (auto *OldFD
= dyn_cast
<FunctionDecl
>(OldND
->getUnderlyingDecl()))
9527 NoteOverloadCandidate(OldND
, OldFD
, CRK_None
, FD
->getType(), false);
9529 FailedCandidates
.NoteCandidates(*this, FD
->getLocation());
9533 // Find the most specialized function template.
9534 UnresolvedSetIterator Result
= getMostSpecialized(
9535 Candidates
.begin(), Candidates
.end(), FailedCandidates
, FD
->getLocation(),
9536 PDiag(diag::err_function_template_spec_no_match
) << FD
->getDeclName(),
9537 PDiag(diag::err_function_template_spec_ambiguous
)
9538 << FD
->getDeclName() << (ExplicitTemplateArgs
!= nullptr),
9539 PDiag(diag::note_function_template_spec_matched
));
9541 if (Result
== Candidates
.end())
9544 // Ignore access information; it doesn't figure into redeclaration checking.
9545 FunctionDecl
*Specialization
= cast
<FunctionDecl
>(*Result
);
9547 FunctionTemplateSpecializationInfo
*SpecInfo
9548 = Specialization
->getTemplateSpecializationInfo();
9549 assert(SpecInfo
&& "Function template specialization info missing?");
9551 // Note: do not overwrite location info if previous template
9552 // specialization kind was explicit.
9553 TemplateSpecializationKind TSK
= SpecInfo
->getTemplateSpecializationKind();
9554 if (TSK
== TSK_Undeclared
|| TSK
== TSK_ImplicitInstantiation
) {
9555 Specialization
->setLocation(FD
->getLocation());
9556 Specialization
->setLexicalDeclContext(FD
->getLexicalDeclContext());
9557 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9558 // function can differ from the template declaration with respect to
9559 // the constexpr specifier.
9560 // FIXME: We need an update record for this AST mutation.
9561 // FIXME: What if there are multiple such prior declarations (for instance,
9562 // from different modules)?
9563 Specialization
->setConstexprKind(FD
->getConstexprKind());
9566 // FIXME: Check if the prior specialization has a point of instantiation.
9567 // If so, we have run afoul of .
9569 // If this is a friend declaration, then we're not really declaring
9570 // an explicit specialization.
9571 bool isFriend
= (FD
->getFriendObjectKind() != Decl::FOK_None
);
9573 // Check the scope of this explicit specialization.
9575 CheckTemplateSpecializationScope(*this,
9576 Specialization
->getPrimaryTemplate(),
9577 Specialization
, FD
->getLocation(),
9581 // C++ [temp.expl.spec]p6:
9582 // If a template, a member template or the member of a class template is
9583 // explicitly specialized then that specialization shall be declared
9584 // before the first use of that specialization that would cause an implicit
9585 // instantiation to take place, in every translation unit in which such a
9586 // use occurs; no diagnostic is required.
9587 bool HasNoEffect
= false;
9589 CheckSpecializationInstantiationRedecl(FD
->getLocation(),
9590 TSK_ExplicitSpecialization
,
9592 SpecInfo
->getTemplateSpecializationKind(),
9593 SpecInfo
->getPointOfInstantiation(),
9597 // Mark the prior declaration as an explicit specialization, so that later
9598 // clients know that this is an explicit specialization.
9600 // Since explicit specializations do not inherit '=delete' from their
9601 // primary function template - check if the 'specialization' that was
9602 // implicitly generated (during template argument deduction for partial
9603 // ordering) from the most specialized of all the function templates that
9604 // 'FD' could have been specializing, has a 'deleted' definition. If so,
9605 // first check that it was implicitly generated during template argument
9606 // deduction by making sure it wasn't referenced, and then reset the deleted
9607 // flag to not-deleted, so that we can inherit that information from 'FD'.
9608 if (Specialization
->isDeleted() && !SpecInfo
->isExplicitSpecialization() &&
9609 !Specialization
->getCanonicalDecl()->isReferenced()) {
9610 // FIXME: This assert will not hold in the presence of modules.
9612 Specialization
->getCanonicalDecl() == Specialization
&&
9613 "This must be the only existing declaration of this specialization");
9614 // FIXME: We need an update record for this AST mutation.
9615 Specialization
->setDeletedAsWritten(false);
9617 // FIXME: We need an update record for this AST mutation.
9618 SpecInfo
->setTemplateSpecializationKind(TSK_ExplicitSpecialization
);
9619 MarkUnusedFileScopedDecl(Specialization
);
9622 // Turn the given function declaration into a function template
9623 // specialization, with the template arguments from the previous
9625 // Take copies of (semantic and syntactic) template argument lists.
9626 const TemplateArgumentList
* TemplArgs
= new (Context
)
9627 TemplateArgumentList(Specialization
->getTemplateSpecializationArgs());
9628 FD
->setFunctionTemplateSpecialization(
9629 Specialization
->getPrimaryTemplate(), TemplArgs
, /*InsertPos=*/nullptr,
9630 SpecInfo
->getTemplateSpecializationKind(),
9631 ExplicitTemplateArgs
? &ConvertedTemplateArgs
[Specialization
] : nullptr);
9633 // A function template specialization inherits the target attributes
9634 // of its template. (We require the attributes explicitly in the
9635 // code to match, but a template may have implicit attributes by
9636 // virtue e.g. of being constexpr, and it passes these implicit
9637 // attributes on to its specializations.)
9639 inheritCUDATargetAttrs(FD
, *Specialization
->getPrimaryTemplate());
9641 // The "previous declaration" for this function template specialization is
9642 // the prior function template specialization.
9644 Previous
.addDecl(Specialization
);
9648 /// Perform semantic analysis for the given non-template member
9651 /// This routine performs all of the semantic analysis required for an
9652 /// explicit member function specialization. On successful completion,
9653 /// the function declaration \p FD will become a member function
9656 /// \param Member the member declaration, which will be updated to become a
9659 /// \param Previous the set of declarations, one of which may be specialized
9660 /// by this function specialization; the set will be modified to contain the
9661 /// redeclared member.
9663 Sema::CheckMemberSpecialization(NamedDecl
*Member
, LookupResult
&Previous
) {
9664 assert(!isa
<TemplateDecl
>(Member
) && "Only for non-template members");
9666 // Try to find the member we are instantiating.
9667 NamedDecl
*FoundInstantiation
= nullptr;
9668 NamedDecl
*Instantiation
= nullptr;
9669 NamedDecl
*InstantiatedFrom
= nullptr;
9670 MemberSpecializationInfo
*MSInfo
= nullptr;
9672 if (Previous
.empty()) {
9673 // Nowhere to look anyway.
9674 } else if (FunctionDecl
*Function
= dyn_cast
<FunctionDecl
>(Member
)) {
9675 for (LookupResult::iterator I
= Previous
.begin(), E
= Previous
.end();
9677 NamedDecl
*D
= (*I
)->getUnderlyingDecl();
9678 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(D
)) {
9679 QualType Adjusted
= Function
->getType();
9680 if (!hasExplicitCallingConv(Adjusted
))
9681 Adjusted
= adjustCCAndNoReturn(Adjusted
, Method
->getType());
9682 // This doesn't handle deduced return types, but both function
9683 // declarations should be undeduced at this point.
9684 if (Context
.hasSameType(Adjusted
, Method
->getType())) {
9685 FoundInstantiation
= *I
;
9686 Instantiation
= Method
;
9687 InstantiatedFrom
= Method
->getInstantiatedFromMemberFunction();
9688 MSInfo
= Method
->getMemberSpecializationInfo();
9693 } else if (isa
<VarDecl
>(Member
)) {
9695 if (Previous
.isSingleResult() &&
9696 (PrevVar
= dyn_cast
<VarDecl
>(Previous
.getFoundDecl())))
9697 if (PrevVar
->isStaticDataMember()) {
9698 FoundInstantiation
= Previous
.getRepresentativeDecl();
9699 Instantiation
= PrevVar
;
9700 InstantiatedFrom
= PrevVar
->getInstantiatedFromStaticDataMember();
9701 MSInfo
= PrevVar
->getMemberSpecializationInfo();
9703 } else if (isa
<RecordDecl
>(Member
)) {
9704 CXXRecordDecl
*PrevRecord
;
9705 if (Previous
.isSingleResult() &&
9706 (PrevRecord
= dyn_cast
<CXXRecordDecl
>(Previous
.getFoundDecl()))) {
9707 FoundInstantiation
= Previous
.getRepresentativeDecl();
9708 Instantiation
= PrevRecord
;
9709 InstantiatedFrom
= PrevRecord
->getInstantiatedFromMemberClass();
9710 MSInfo
= PrevRecord
->getMemberSpecializationInfo();
9712 } else if (isa
<EnumDecl
>(Member
)) {
9714 if (Previous
.isSingleResult() &&
9715 (PrevEnum
= dyn_cast
<EnumDecl
>(Previous
.getFoundDecl()))) {
9716 FoundInstantiation
= Previous
.getRepresentativeDecl();
9717 Instantiation
= PrevEnum
;
9718 InstantiatedFrom
= PrevEnum
->getInstantiatedFromMemberEnum();
9719 MSInfo
= PrevEnum
->getMemberSpecializationInfo();
9723 if (!Instantiation
) {
9724 // There is no previous declaration that matches. Since member
9725 // specializations are always out-of-line, the caller will complain about
9726 // this mismatch later.
9730 // A member specialization in a friend declaration isn't really declaring
9731 // an explicit specialization, just identifying a specific (possibly implicit)
9732 // specialization. Don't change the template specialization kind.
9734 // FIXME: Is this really valid? Other compilers reject.
9735 if (Member
->getFriendObjectKind() != Decl::FOK_None
) {
9736 // Preserve instantiation information.
9737 if (InstantiatedFrom
&& isa
<CXXMethodDecl
>(Member
)) {
9738 cast
<CXXMethodDecl
>(Member
)->setInstantiationOfMemberFunction(
9739 cast
<CXXMethodDecl
>(InstantiatedFrom
),
9740 cast
<CXXMethodDecl
>(Instantiation
)->getTemplateSpecializationKind());
9741 } else if (InstantiatedFrom
&& isa
<CXXRecordDecl
>(Member
)) {
9742 cast
<CXXRecordDecl
>(Member
)->setInstantiationOfMemberClass(
9743 cast
<CXXRecordDecl
>(InstantiatedFrom
),
9744 cast
<CXXRecordDecl
>(Instantiation
)->getTemplateSpecializationKind());
9748 Previous
.addDecl(FoundInstantiation
);
9752 // Make sure that this is a specialization of a member.
9753 if (!InstantiatedFrom
) {
9754 Diag(Member
->getLocation(), diag::err_spec_member_not_instantiated
)
9756 Diag(Instantiation
->getLocation(), diag::note_specialized_decl
);
9760 // C++ [temp.expl.spec]p6:
9761 // If a template, a member template or the member of a class template is
9762 // explicitly specialized then that specialization shall be declared
9763 // before the first use of that specialization that would cause an implicit
9764 // instantiation to take place, in every translation unit in which such a
9765 // use occurs; no diagnostic is required.
9766 assert(MSInfo
&& "Member specialization info missing?");
9768 bool HasNoEffect
= false;
9769 if (CheckSpecializationInstantiationRedecl(Member
->getLocation(),
9770 TSK_ExplicitSpecialization
,
9772 MSInfo
->getTemplateSpecializationKind(),
9773 MSInfo
->getPointOfInstantiation(),
9777 // Check the scope of this explicit specialization.
9778 if (CheckTemplateSpecializationScope(*this,
9780 Instantiation
, Member
->getLocation(),
9784 // Note that this member specialization is an "instantiation of" the
9785 // corresponding member of the original template.
9786 if (auto *MemberFunction
= dyn_cast
<FunctionDecl
>(Member
)) {
9787 FunctionDecl
*InstantiationFunction
= cast
<FunctionDecl
>(Instantiation
);
9788 if (InstantiationFunction
->getTemplateSpecializationKind() ==
9789 TSK_ImplicitInstantiation
) {
9790 // Explicit specializations of member functions of class templates do not
9791 // inherit '=delete' from the member function they are specializing.
9792 if (InstantiationFunction
->isDeleted()) {
9793 // FIXME: This assert will not hold in the presence of modules.
9794 assert(InstantiationFunction
->getCanonicalDecl() ==
9795 InstantiationFunction
);
9796 // FIXME: We need an update record for this AST mutation.
9797 InstantiationFunction
->setDeletedAsWritten(false);
9801 MemberFunction
->setInstantiationOfMemberFunction(
9802 cast
<CXXMethodDecl
>(InstantiatedFrom
), TSK_ExplicitSpecialization
);
9803 } else if (auto *MemberVar
= dyn_cast
<VarDecl
>(Member
)) {
9804 MemberVar
->setInstantiationOfStaticDataMember(
9805 cast
<VarDecl
>(InstantiatedFrom
), TSK_ExplicitSpecialization
);
9806 } else if (auto *MemberClass
= dyn_cast
<CXXRecordDecl
>(Member
)) {
9807 MemberClass
->setInstantiationOfMemberClass(
9808 cast
<CXXRecordDecl
>(InstantiatedFrom
), TSK_ExplicitSpecialization
);
9809 } else if (auto *MemberEnum
= dyn_cast
<EnumDecl
>(Member
)) {
9810 MemberEnum
->setInstantiationOfMemberEnum(
9811 cast
<EnumDecl
>(InstantiatedFrom
), TSK_ExplicitSpecialization
);
9813 llvm_unreachable("unknown member specialization kind");
9816 // Save the caller the trouble of having to figure out which declaration
9817 // this specialization matches.
9819 Previous
.addDecl(FoundInstantiation
);
9823 /// Complete the explicit specialization of a member of a class template by
9824 /// updating the instantiated member to be marked as an explicit specialization.
9826 /// \param OrigD The member declaration instantiated from the template.
9827 /// \param Loc The location of the explicit specialization of the member.
9828 template<typename DeclT
>
9829 static void completeMemberSpecializationImpl(Sema
&S
, DeclT
*OrigD
,
9830 SourceLocation Loc
) {
9831 if (OrigD
->getTemplateSpecializationKind() != TSK_ImplicitInstantiation
)
9834 // FIXME: Inform AST mutation listeners of this AST mutation.
9835 // FIXME: If there are multiple in-class declarations of the member (from
9836 // multiple modules, or a declaration and later definition of a member type),
9837 // should we update all of them?
9838 OrigD
->setTemplateSpecializationKind(TSK_ExplicitSpecialization
);
9839 OrigD
->setLocation(Loc
);
9842 void Sema::CompleteMemberSpecialization(NamedDecl
*Member
,
9843 LookupResult
&Previous
) {
9844 NamedDecl
*Instantiation
= cast
<NamedDecl
>(Member
->getCanonicalDecl());
9845 if (Instantiation
== Member
)
9848 if (auto *Function
= dyn_cast
<CXXMethodDecl
>(Instantiation
))
9849 completeMemberSpecializationImpl(*this, Function
, Member
->getLocation());
9850 else if (auto *Var
= dyn_cast
<VarDecl
>(Instantiation
))
9851 completeMemberSpecializationImpl(*this, Var
, Member
->getLocation());
9852 else if (auto *Record
= dyn_cast
<CXXRecordDecl
>(Instantiation
))
9853 completeMemberSpecializationImpl(*this, Record
, Member
->getLocation());
9854 else if (auto *Enum
= dyn_cast
<EnumDecl
>(Instantiation
))
9855 completeMemberSpecializationImpl(*this, Enum
, Member
->getLocation());
9857 llvm_unreachable("unknown member specialization kind");
9860 /// Check the scope of an explicit instantiation.
9862 /// \returns true if a serious error occurs, false otherwise.
9863 static bool CheckExplicitInstantiationScope(Sema
&S
, NamedDecl
*D
,
9864 SourceLocation InstLoc
,
9865 bool WasQualifiedName
) {
9866 DeclContext
*OrigContext
= D
->getDeclContext()->getEnclosingNamespaceContext();
9867 DeclContext
*CurContext
= S
.CurContext
->getRedeclContext();
9869 if (CurContext
->isRecord()) {
9870 S
.Diag(InstLoc
, diag::err_explicit_instantiation_in_class
)
9875 // C++11 [temp.explicit]p3:
9876 // An explicit instantiation shall appear in an enclosing namespace of its
9877 // template. If the name declared in the explicit instantiation is an
9878 // unqualified name, the explicit instantiation shall appear in the
9879 // namespace where its template is declared or, if that namespace is inline
9880 // (7.3.1), any namespace from its enclosing namespace set.
9882 // This is DR275, which we do not retroactively apply to C++98/03.
9883 if (WasQualifiedName
) {
9884 if (CurContext
->Encloses(OrigContext
))
9887 if (CurContext
->InEnclosingNamespaceSetOf(OrigContext
))
9891 if (NamespaceDecl
*NS
= dyn_cast
<NamespaceDecl
>(OrigContext
)) {
9892 if (WasQualifiedName
)
9894 S
.getLangOpts().CPlusPlus11
?
9895 diag::err_explicit_instantiation_out_of_scope
:
9896 diag::warn_explicit_instantiation_out_of_scope_0x
)
9900 S
.getLangOpts().CPlusPlus11
?
9901 diag::err_explicit_instantiation_unqualified_wrong_namespace
:
9902 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x
)
9906 S
.getLangOpts().CPlusPlus11
?
9907 diag::err_explicit_instantiation_must_be_global
:
9908 diag::warn_explicit_instantiation_must_be_global_0x
)
9910 S
.Diag(D
->getLocation(), diag::note_explicit_instantiation_here
);
9914 /// Common checks for whether an explicit instantiation of \p D is valid.
9915 static bool CheckExplicitInstantiation(Sema
&S
, NamedDecl
*D
,
9916 SourceLocation InstLoc
,
9917 bool WasQualifiedName
,
9918 TemplateSpecializationKind TSK
) {
9919 // C++ [temp.explicit]p13:
9920 // An explicit instantiation declaration shall not name a specialization of
9921 // a template with internal linkage.
9922 if (TSK
== TSK_ExplicitInstantiationDeclaration
&&
9923 D
->getFormalLinkage() == InternalLinkage
) {
9924 S
.Diag(InstLoc
, diag::err_explicit_instantiation_internal_linkage
) << D
;
9928 // C++11 [temp.explicit]p3: [DR 275]
9929 // An explicit instantiation shall appear in an enclosing namespace of its
9931 if (CheckExplicitInstantiationScope(S
, D
, InstLoc
, WasQualifiedName
))
9937 /// Determine whether the given scope specifier has a template-id in it.
9938 static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec
&SS
) {
9942 // C++11 [temp.explicit]p3:
9943 // If the explicit instantiation is for a member function, a member class
9944 // or a static data member of a class template specialization, the name of
9945 // the class template specialization in the qualified-id for the member
9946 // name shall be a simple-template-id.
9948 // C++98 has the same restriction, just worded differently.
9949 for (NestedNameSpecifier
*NNS
= SS
.getScopeRep(); NNS
;
9950 NNS
= NNS
->getPrefix())
9951 if (const Type
*T
= NNS
->getAsType())
9952 if (isa
<TemplateSpecializationType
>(T
))
9958 /// Make a dllexport or dllimport attr on a class template specialization take
9960 static void dllExportImportClassTemplateSpecialization(
9961 Sema
&S
, ClassTemplateSpecializationDecl
*Def
) {
9962 auto *A
= cast_or_null
<InheritableAttr
>(getDLLAttr(Def
));
9963 assert(A
&& "dllExportImportClassTemplateSpecialization called "
9964 "on Def without dllexport or dllimport");
9966 // We reject explicit instantiations in class scope, so there should
9967 // never be any delayed exported classes to worry about.
9968 assert(S
.DelayedDllExportClasses
.empty() &&
9969 "delayed exports present at explicit instantiation");
9970 S
.checkClassLevelDLLAttribute(Def
);
9972 // Propagate attribute to base class templates.
9973 for (auto &B
: Def
->bases()) {
9974 if (auto *BT
= dyn_cast_or_null
<ClassTemplateSpecializationDecl
>(
9975 B
.getType()->getAsCXXRecordDecl()))
9976 S
.propagateDLLAttrToBaseClassTemplate(Def
, A
, BT
, B
.getBeginLoc());
9979 S
.referenceDLLExportedClassMethods();
9982 // Explicit instantiation of a class template specialization
9983 DeclResult
Sema::ActOnExplicitInstantiation(
9984 Scope
*S
, SourceLocation ExternLoc
, SourceLocation TemplateLoc
,
9985 unsigned TagSpec
, SourceLocation KWLoc
, const CXXScopeSpec
&SS
,
9986 TemplateTy TemplateD
, SourceLocation TemplateNameLoc
,
9987 SourceLocation LAngleLoc
, ASTTemplateArgsPtr TemplateArgsIn
,
9988 SourceLocation RAngleLoc
, const ParsedAttributesView
&Attr
) {
9989 // Find the class template we're specializing
9990 TemplateName Name
= TemplateD
.get();
9991 TemplateDecl
*TD
= Name
.getAsTemplateDecl();
9992 // Check that the specialization uses the same tag kind as the
9993 // original template.
9994 TagTypeKind Kind
= TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec
);
9995 assert(Kind
!= TTK_Enum
&&
9996 "Invalid enum tag in class template explicit instantiation!");
9998 ClassTemplateDecl
*ClassTemplate
= dyn_cast
<ClassTemplateDecl
>(TD
);
10000 if (!ClassTemplate
) {
10001 NonTagKind NTK
= getNonTagTypeDeclKind(TD
, Kind
);
10002 Diag(TemplateNameLoc
, diag::err_tag_reference_non_tag
) << TD
<< NTK
<< Kind
;
10003 Diag(TD
->getLocation(), diag::note_previous_use
);
10007 if (!isAcceptableTagRedeclaration(ClassTemplate
->getTemplatedDecl(),
10008 Kind
, /*isDefinition*/false, KWLoc
,
10009 ClassTemplate
->getIdentifier())) {
10010 Diag(KWLoc
, diag::err_use_with_wrong_tag
)
10012 << FixItHint::CreateReplacement(KWLoc
,
10013 ClassTemplate
->getTemplatedDecl()->getKindName());
10014 Diag(ClassTemplate
->getTemplatedDecl()->getLocation(),
10015 diag::note_previous_use
);
10016 Kind
= ClassTemplate
->getTemplatedDecl()->getTagKind();
10019 // C++0x [temp.explicit]p2:
10020 // There are two forms of explicit instantiation: an explicit instantiation
10021 // definition and an explicit instantiation declaration. An explicit
10022 // instantiation declaration begins with the extern keyword. [...]
10023 TemplateSpecializationKind TSK
= ExternLoc
.isInvalid()
10024 ? TSK_ExplicitInstantiationDefinition
10025 : TSK_ExplicitInstantiationDeclaration
;
10027 if (TSK
== TSK_ExplicitInstantiationDeclaration
&&
10028 !Context
.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
10029 // Check for dllexport class template instantiation declarations,
10030 // except for MinGW mode.
10031 for (const ParsedAttr
&AL
: Attr
) {
10032 if (AL
.getKind() == ParsedAttr::AT_DLLExport
) {
10034 diag::warn_attribute_dllexport_explicit_instantiation_decl
);
10035 Diag(AL
.getLoc(), diag::note_attribute
);
10040 if (auto *A
= ClassTemplate
->getTemplatedDecl()->getAttr
<DLLExportAttr
>()) {
10042 diag::warn_attribute_dllexport_explicit_instantiation_decl
);
10043 Diag(A
->getLocation(), diag::note_attribute
);
10047 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10048 // instantiation declarations for most purposes.
10049 bool DLLImportExplicitInstantiationDef
= false;
10050 if (TSK
== TSK_ExplicitInstantiationDefinition
&&
10051 Context
.getTargetInfo().getCXXABI().isMicrosoft()) {
10052 // Check for dllimport class template instantiation definitions.
10054 ClassTemplate
->getTemplatedDecl()->getAttr
<DLLImportAttr
>();
10055 for (const ParsedAttr
&AL
: Attr
) {
10056 if (AL
.getKind() == ParsedAttr::AT_DLLImport
)
10058 if (AL
.getKind() == ParsedAttr::AT_DLLExport
) {
10059 // dllexport trumps dllimport here.
10065 TSK
= TSK_ExplicitInstantiationDeclaration
;
10066 DLLImportExplicitInstantiationDef
= true;
10070 // Translate the parser's template argument list in our AST format.
10071 TemplateArgumentListInfo
TemplateArgs(LAngleLoc
, RAngleLoc
);
10072 translateTemplateArguments(TemplateArgsIn
, TemplateArgs
);
10074 // Check that the template argument list is well-formed for this
10076 SmallVector
<TemplateArgument
, 4> SugaredConverted
, CanonicalConverted
;
10077 if (CheckTemplateArgumentList(ClassTemplate
, TemplateNameLoc
, TemplateArgs
,
10078 false, SugaredConverted
, CanonicalConverted
,
10079 /*UpdateArgsWithConversions=*/true))
10082 // Find the class template specialization declaration that
10083 // corresponds to these arguments.
10084 void *InsertPos
= nullptr;
10085 ClassTemplateSpecializationDecl
*PrevDecl
=
10086 ClassTemplate
->findSpecialization(CanonicalConverted
, InsertPos
);
10088 TemplateSpecializationKind PrevDecl_TSK
10089 = PrevDecl
? PrevDecl
->getTemplateSpecializationKind() : TSK_Undeclared
;
10091 if (TSK
== TSK_ExplicitInstantiationDefinition
&& PrevDecl
!= nullptr &&
10092 Context
.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
10093 // Check for dllexport class template instantiation definitions in MinGW
10094 // mode, if a previous declaration of the instantiation was seen.
10095 for (const ParsedAttr
&AL
: Attr
) {
10096 if (AL
.getKind() == ParsedAttr::AT_DLLExport
) {
10098 diag::warn_attribute_dllexport_explicit_instantiation_def
);
10104 if (CheckExplicitInstantiation(*this, ClassTemplate
, TemplateNameLoc
,
10108 ClassTemplateSpecializationDecl
*Specialization
= nullptr;
10110 bool HasNoEffect
= false;
10112 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc
, TSK
,
10113 PrevDecl
, PrevDecl_TSK
,
10114 PrevDecl
->getPointOfInstantiation(),
10118 // Even though HasNoEffect == true means that this explicit instantiation
10119 // has no effect on semantics, we go on to put its syntax in the AST.
10121 if (PrevDecl_TSK
== TSK_ImplicitInstantiation
||
10122 PrevDecl_TSK
== TSK_Undeclared
) {
10123 // Since the only prior class template specialization with these
10124 // arguments was referenced but not declared, reuse that
10125 // declaration node as our own, updating the source location
10126 // for the template name to reflect our new declaration.
10127 // (Other source locations will be updated later.)
10128 Specialization
= PrevDecl
;
10129 Specialization
->setLocation(TemplateNameLoc
);
10130 PrevDecl
= nullptr;
10133 if (PrevDecl_TSK
== TSK_ExplicitInstantiationDeclaration
&&
10134 DLLImportExplicitInstantiationDef
) {
10135 // The new specialization might add a dllimport attribute.
10136 HasNoEffect
= false;
10140 if (!Specialization
) {
10141 // Create a new class template specialization declaration node for
10142 // this explicit specialization.
10143 Specialization
= ClassTemplateSpecializationDecl::Create(
10144 Context
, Kind
, ClassTemplate
->getDeclContext(), KWLoc
, TemplateNameLoc
,
10145 ClassTemplate
, CanonicalConverted
, PrevDecl
);
10146 SetNestedNameSpecifier(*this, Specialization
, SS
);
10148 // A MSInheritanceAttr attached to the previous declaration must be
10149 // propagated to the new node prior to instantiation.
10151 if (const auto *A
= PrevDecl
->getAttr
<MSInheritanceAttr
>()) {
10152 auto *Clone
= A
->clone(getASTContext());
10153 Clone
->setInherited(true);
10154 Specialization
->addAttr(Clone
);
10155 Consumer
.AssignInheritanceModel(Specialization
);
10159 if (!HasNoEffect
&& !PrevDecl
) {
10160 // Insert the new specialization.
10161 ClassTemplate
->AddSpecialization(Specialization
, InsertPos
);
10165 // Build the fully-sugared type for this explicit instantiation as
10166 // the user wrote in the explicit instantiation itself. This means
10167 // that we'll pretty-print the type retrieved from the
10168 // specialization's declaration the way that the user actually wrote
10169 // the explicit instantiation, rather than formatting the name based
10170 // on the "canonical" representation used to store the template
10171 // arguments in the specialization.
10172 TypeSourceInfo
*WrittenTy
10173 = Context
.getTemplateSpecializationTypeInfo(Name
, TemplateNameLoc
,
10175 Context
.getTypeDeclType(Specialization
));
10176 Specialization
->setTypeAsWritten(WrittenTy
);
10178 // Set source locations for keywords.
10179 Specialization
->setExternLoc(ExternLoc
);
10180 Specialization
->setTemplateKeywordLoc(TemplateLoc
);
10181 Specialization
->setBraceRange(SourceRange());
10183 bool PreviouslyDLLExported
= Specialization
->hasAttr
<DLLExportAttr
>();
10184 ProcessDeclAttributeList(S
, Specialization
, Attr
);
10186 // Add the explicit instantiation into its lexical context. However,
10187 // since explicit instantiations are never found by name lookup, we
10188 // just put it into the declaration context directly.
10189 Specialization
->setLexicalDeclContext(CurContext
);
10190 CurContext
->addDecl(Specialization
);
10192 // Syntax is now OK, so return if it has no other effect on semantics.
10194 // Set the template specialization kind.
10195 Specialization
->setTemplateSpecializationKind(TSK
);
10196 return Specialization
;
10199 // C++ [temp.explicit]p3:
10200 // A definition of a class template or class member template
10201 // shall be in scope at the point of the explicit instantiation of
10202 // the class template or class member template.
10204 // This check comes when we actually try to perform the
10206 ClassTemplateSpecializationDecl
*Def
10207 = cast_or_null
<ClassTemplateSpecializationDecl
>(
10208 Specialization
->getDefinition());
10210 InstantiateClassTemplateSpecialization(TemplateNameLoc
, Specialization
, TSK
);
10211 else if (TSK
== TSK_ExplicitInstantiationDefinition
) {
10212 MarkVTableUsed(TemplateNameLoc
, Specialization
, true);
10213 Specialization
->setPointOfInstantiation(Def
->getPointOfInstantiation());
10216 // Instantiate the members of this class template specialization.
10217 Def
= cast_or_null
<ClassTemplateSpecializationDecl
>(
10218 Specialization
->getDefinition());
10220 TemplateSpecializationKind Old_TSK
= Def
->getTemplateSpecializationKind();
10221 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
10222 // TSK_ExplicitInstantiationDefinition
10223 if (Old_TSK
== TSK_ExplicitInstantiationDeclaration
&&
10224 (TSK
== TSK_ExplicitInstantiationDefinition
||
10225 DLLImportExplicitInstantiationDef
)) {
10226 // FIXME: Need to notify the ASTMutationListener that we did this.
10227 Def
->setTemplateSpecializationKind(TSK
);
10229 if (!getDLLAttr(Def
) && getDLLAttr(Specialization
) &&
10230 (Context
.getTargetInfo().shouldDLLImportComdatSymbols() &&
10231 !Context
.getTargetInfo().getTriple().isPS())) {
10232 // An explicit instantiation definition can add a dll attribute to a
10233 // template with a previous instantiation declaration. MinGW doesn't
10235 auto *A
= cast
<InheritableAttr
>(
10236 getDLLAttr(Specialization
)->clone(getASTContext()));
10237 A
->setInherited(true);
10239 dllExportImportClassTemplateSpecialization(*this, Def
);
10243 // Fix a TSK_ImplicitInstantiation followed by a
10244 // TSK_ExplicitInstantiationDefinition
10245 bool NewlyDLLExported
=
10246 !PreviouslyDLLExported
&& Specialization
->hasAttr
<DLLExportAttr
>();
10247 if (Old_TSK
== TSK_ImplicitInstantiation
&& NewlyDLLExported
&&
10248 (Context
.getTargetInfo().shouldDLLImportComdatSymbols() &&
10249 !Context
.getTargetInfo().getTriple().isPS())) {
10250 // An explicit instantiation definition can add a dll attribute to a
10251 // template with a previous implicit instantiation. MinGW doesn't allow
10252 // this. We limit clang to only adding dllexport, to avoid potentially
10253 // strange codegen behavior. For example, if we extend this conditional
10254 // to dllimport, and we have a source file calling a method on an
10255 // implicitly instantiated template class instance and then declaring a
10256 // dllimport explicit instantiation definition for the same template
10257 // class, the codegen for the method call will not respect the dllimport,
10258 // while it will with cl. The Def will already have the DLL attribute,
10259 // since the Def and Specialization will be the same in the case of
10260 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
10261 // attribute to the Specialization; we just need to make it take effect.
10262 assert(Def
== Specialization
&&
10263 "Def and Specialization should match for implicit instantiation");
10264 dllExportImportClassTemplateSpecialization(*this, Def
);
10267 // In MinGW mode, export the template instantiation if the declaration
10268 // was marked dllexport.
10269 if (PrevDecl_TSK
== TSK_ExplicitInstantiationDeclaration
&&
10270 Context
.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
10271 PrevDecl
->hasAttr
<DLLExportAttr
>()) {
10272 dllExportImportClassTemplateSpecialization(*this, Def
);
10275 // Set the template specialization kind. Make sure it is set before
10276 // instantiating the members which will trigger ASTConsumer callbacks.
10277 Specialization
->setTemplateSpecializationKind(TSK
);
10278 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc
, Def
, TSK
);
10281 // Set the template specialization kind.
10282 Specialization
->setTemplateSpecializationKind(TSK
);
10285 return Specialization
;
10288 // Explicit instantiation of a member class of a class template.
10290 Sema::ActOnExplicitInstantiation(Scope
*S
, SourceLocation ExternLoc
,
10291 SourceLocation TemplateLoc
, unsigned TagSpec
,
10292 SourceLocation KWLoc
, CXXScopeSpec
&SS
,
10293 IdentifierInfo
*Name
, SourceLocation NameLoc
,
10294 const ParsedAttributesView
&Attr
) {
10296 bool Owned
= false;
10297 bool IsDependent
= false;
10298 Decl
*TagD
= ActOnTag(S
, TagSpec
, Sema::TUK_Reference
, KWLoc
, SS
, Name
,
10299 NameLoc
, Attr
, AS_none
, /*ModulePrivateLoc=*/SourceLocation(),
10300 MultiTemplateParamsArg(), Owned
, IsDependent
, SourceLocation(),
10301 false, TypeResult(), /*IsTypeSpecifier*/ false,
10302 /*IsTemplateParamOrArg*/ false, /*OOK=*/OOK_Outside
).get();
10303 assert(!IsDependent
&& "explicit instantiation of dependent name not yet handled");
10308 TagDecl
*Tag
= cast
<TagDecl
>(TagD
);
10309 assert(!Tag
->isEnum() && "shouldn't see enumerations here");
10311 if (Tag
->isInvalidDecl())
10314 CXXRecordDecl
*Record
= cast
<CXXRecordDecl
>(Tag
);
10315 CXXRecordDecl
*Pattern
= Record
->getInstantiatedFromMemberClass();
10317 Diag(TemplateLoc
, diag::err_explicit_instantiation_nontemplate_type
)
10318 << Context
.getTypeDeclType(Record
);
10319 Diag(Record
->getLocation(), diag::note_nontemplate_decl_here
);
10323 // C++0x [temp.explicit]p2:
10324 // If the explicit instantiation is for a class or member class, the
10325 // elaborated-type-specifier in the declaration shall include a
10326 // simple-template-id.
10328 // C++98 has the same restriction, just worded differently.
10329 if (!ScopeSpecifierHasTemplateId(SS
))
10330 Diag(TemplateLoc
, diag::ext_explicit_instantiation_without_qualified_id
)
10331 << Record
<< SS
.getRange();
10333 // C++0x [temp.explicit]p2:
10334 // There are two forms of explicit instantiation: an explicit instantiation
10335 // definition and an explicit instantiation declaration. An explicit
10336 // instantiation declaration begins with the extern keyword. [...]
10337 TemplateSpecializationKind TSK
10338 = ExternLoc
.isInvalid()? TSK_ExplicitInstantiationDefinition
10339 : TSK_ExplicitInstantiationDeclaration
;
10341 CheckExplicitInstantiation(*this, Record
, NameLoc
, true, TSK
);
10343 // Verify that it is okay to explicitly instantiate here.
10344 CXXRecordDecl
*PrevDecl
10345 = cast_or_null
<CXXRecordDecl
>(Record
->getPreviousDecl());
10346 if (!PrevDecl
&& Record
->getDefinition())
10349 MemberSpecializationInfo
*MSInfo
= PrevDecl
->getMemberSpecializationInfo();
10350 bool HasNoEffect
= false;
10351 assert(MSInfo
&& "No member specialization information?");
10352 if (CheckSpecializationInstantiationRedecl(TemplateLoc
, TSK
,
10354 MSInfo
->getTemplateSpecializationKind(),
10355 MSInfo
->getPointOfInstantiation(),
10362 CXXRecordDecl
*RecordDef
10363 = cast_or_null
<CXXRecordDecl
>(Record
->getDefinition());
10365 // C++ [temp.explicit]p3:
10366 // A definition of a member class of a class template shall be in scope
10367 // at the point of an explicit instantiation of the member class.
10369 = cast_or_null
<CXXRecordDecl
>(Pattern
->getDefinition());
10371 Diag(TemplateLoc
, diag::err_explicit_instantiation_undefined_member
)
10372 << 0 << Record
->getDeclName() << Record
->getDeclContext();
10373 Diag(Pattern
->getLocation(), diag::note_forward_declaration
)
10377 if (InstantiateClass(NameLoc
, Record
, Def
,
10378 getTemplateInstantiationArgs(Record
),
10382 RecordDef
= cast_or_null
<CXXRecordDecl
>(Record
->getDefinition());
10388 // Instantiate all of the members of the class.
10389 InstantiateClassMembers(NameLoc
, RecordDef
,
10390 getTemplateInstantiationArgs(Record
), TSK
);
10392 if (TSK
== TSK_ExplicitInstantiationDefinition
)
10393 MarkVTableUsed(NameLoc
, RecordDef
, true);
10395 // FIXME: We don't have any representation for explicit instantiations of
10396 // member classes. Such a representation is not needed for compilation, but it
10397 // should be available for clients that want to see all of the declarations in
10398 // the source code.
10402 DeclResult
Sema::ActOnExplicitInstantiation(Scope
*S
,
10403 SourceLocation ExternLoc
,
10404 SourceLocation TemplateLoc
,
10406 // Explicit instantiations always require a name.
10407 // TODO: check if/when DNInfo should replace Name.
10408 DeclarationNameInfo NameInfo
= GetNameForDeclarator(D
);
10409 DeclarationName Name
= NameInfo
.getName();
10411 if (!D
.isInvalidType())
10412 Diag(D
.getDeclSpec().getBeginLoc(),
10413 diag::err_explicit_instantiation_requires_name
)
10414 << D
.getDeclSpec().getSourceRange() << D
.getSourceRange();
10419 // The scope passed in may not be a decl scope. Zip up the scope tree until
10420 // we find one that is.
10421 while ((S
->getFlags() & Scope::DeclScope
) == 0 ||
10422 (S
->getFlags() & Scope::TemplateParamScope
) != 0)
10423 S
= S
->getParent();
10425 // Determine the type of the declaration.
10426 TypeSourceInfo
*T
= GetTypeForDeclarator(D
, S
);
10427 QualType R
= T
->getType();
10431 // C++ [dcl.stc]p1:
10432 // A storage-class-specifier shall not be specified in [...] an explicit
10433 // instantiation (14.7.2) directive.
10434 if (D
.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef
) {
10435 Diag(D
.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef
)
10438 } else if (D
.getDeclSpec().getStorageClassSpec()
10439 != DeclSpec::SCS_unspecified
) {
10440 // Complain about then remove the storage class specifier.
10441 Diag(D
.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class
)
10442 << FixItHint::CreateRemoval(D
.getDeclSpec().getStorageClassSpecLoc());
10444 D
.getMutableDeclSpec().ClearStorageClassSpecs();
10447 // C++0x [temp.explicit]p1:
10448 // [...] An explicit instantiation of a function template shall not use the
10449 // inline or constexpr specifiers.
10450 // Presumably, this also applies to member functions of class templates as
10452 if (D
.getDeclSpec().isInlineSpecified())
10453 Diag(D
.getDeclSpec().getInlineSpecLoc(),
10454 getLangOpts().CPlusPlus11
?
10455 diag::err_explicit_instantiation_inline
:
10456 diag::warn_explicit_instantiation_inline_0x
)
10457 << FixItHint::CreateRemoval(D
.getDeclSpec().getInlineSpecLoc());
10458 if (D
.getDeclSpec().hasConstexprSpecifier() && R
->isFunctionType())
10459 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
10460 // not already specified.
10461 Diag(D
.getDeclSpec().getConstexprSpecLoc(),
10462 diag::err_explicit_instantiation_constexpr
);
10464 // A deduction guide is not on the list of entities that can be explicitly
10466 if (Name
.getNameKind() == DeclarationName::CXXDeductionGuideName
) {
10467 Diag(D
.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized
)
10468 << /*explicit instantiation*/ 0;
10472 // C++0x [temp.explicit]p2:
10473 // There are two forms of explicit instantiation: an explicit instantiation
10474 // definition and an explicit instantiation declaration. An explicit
10475 // instantiation declaration begins with the extern keyword. [...]
10476 TemplateSpecializationKind TSK
10477 = ExternLoc
.isInvalid()? TSK_ExplicitInstantiationDefinition
10478 : TSK_ExplicitInstantiationDeclaration
;
10480 LookupResult
Previous(*this, NameInfo
, LookupOrdinaryName
);
10481 LookupParsedName(Previous
, S
, &D
.getCXXScopeSpec());
10483 if (!R
->isFunctionType()) {
10484 // C++ [temp.explicit]p1:
10485 // A [...] static data member of a class template can be explicitly
10486 // instantiated from the member definition associated with its class
10488 // C++1y [temp.explicit]p1:
10489 // A [...] variable [...] template specialization can be explicitly
10490 // instantiated from its template.
10491 if (Previous
.isAmbiguous())
10494 VarDecl
*Prev
= Previous
.getAsSingle
<VarDecl
>();
10495 VarTemplateDecl
*PrevTemplate
= Previous
.getAsSingle
<VarTemplateDecl
>();
10497 if (!PrevTemplate
) {
10498 if (!Prev
|| !Prev
->isStaticDataMember()) {
10499 // We expect to see a static data member here.
10500 Diag(D
.getIdentifierLoc(), diag::err_explicit_instantiation_not_known
)
10502 for (LookupResult::iterator P
= Previous
.begin(), PEnd
= Previous
.end();
10504 Diag((*P
)->getLocation(), diag::note_explicit_instantiation_here
);
10508 if (!Prev
->getInstantiatedFromStaticDataMember()) {
10509 // FIXME: Check for explicit specialization?
10510 Diag(D
.getIdentifierLoc(),
10511 diag::err_explicit_instantiation_data_member_not_instantiated
)
10513 Diag(Prev
->getLocation(), diag::note_explicit_instantiation_here
);
10514 // FIXME: Can we provide a note showing where this was declared?
10518 // Explicitly instantiate a variable template.
10520 // C++1y [dcl.spec.auto]p6:
10521 // ... A program that uses auto or decltype(auto) in a context not
10522 // explicitly allowed in this section is ill-formed.
10524 // This includes auto-typed variable template instantiations.
10525 if (R
->isUndeducedType()) {
10526 Diag(T
->getTypeLoc().getBeginLoc(),
10527 diag::err_auto_not_allowed_var_inst
);
10531 if (D
.getName().getKind() != UnqualifiedIdKind::IK_TemplateId
) {
10532 // C++1y [temp.explicit]p3:
10533 // If the explicit instantiation is for a variable, the unqualified-id
10534 // in the declaration shall be a template-id.
10535 Diag(D
.getIdentifierLoc(),
10536 diag::err_explicit_instantiation_without_template_id
)
10538 Diag(PrevTemplate
->getLocation(),
10539 diag::note_explicit_instantiation_here
);
10543 // Translate the parser's template argument list into our AST format.
10544 TemplateArgumentListInfo TemplateArgs
=
10545 makeTemplateArgumentListInfo(*this, *D
.getName().TemplateId
);
10547 DeclResult Res
= CheckVarTemplateId(PrevTemplate
, TemplateLoc
,
10548 D
.getIdentifierLoc(), TemplateArgs
);
10549 if (Res
.isInvalid())
10552 if (!Res
.isUsable()) {
10553 // We somehow specified dependent template arguments in an explicit
10554 // instantiation. This should probably only happen during error
10556 Diag(D
.getIdentifierLoc(), diag::err_explicit_instantiation_dependent
);
10560 // Ignore access control bits, we don't need them for redeclaration
10562 Prev
= cast
<VarDecl
>(Res
.get());
10565 // C++0x [temp.explicit]p2:
10566 // If the explicit instantiation is for a member function, a member class
10567 // or a static data member of a class template specialization, the name of
10568 // the class template specialization in the qualified-id for the member
10569 // name shall be a simple-template-id.
10571 // C++98 has the same restriction, just worded differently.
10573 // This does not apply to variable template specializations, where the
10574 // template-id is in the unqualified-id instead.
10575 if (!ScopeSpecifierHasTemplateId(D
.getCXXScopeSpec()) && !PrevTemplate
)
10576 Diag(D
.getIdentifierLoc(),
10577 diag::ext_explicit_instantiation_without_qualified_id
)
10578 << Prev
<< D
.getCXXScopeSpec().getRange();
10580 CheckExplicitInstantiation(*this, Prev
, D
.getIdentifierLoc(), true, TSK
);
10582 // Verify that it is okay to explicitly instantiate here.
10583 TemplateSpecializationKind PrevTSK
= Prev
->getTemplateSpecializationKind();
10584 SourceLocation POI
= Prev
->getPointOfInstantiation();
10585 bool HasNoEffect
= false;
10586 if (CheckSpecializationInstantiationRedecl(D
.getIdentifierLoc(), TSK
, Prev
,
10587 PrevTSK
, POI
, HasNoEffect
))
10590 if (!HasNoEffect
) {
10591 // Instantiate static data member or variable template.
10592 Prev
->setTemplateSpecializationKind(TSK
, D
.getIdentifierLoc());
10593 // Merge attributes.
10594 ProcessDeclAttributeList(S
, Prev
, D
.getDeclSpec().getAttributes());
10595 if (TSK
== TSK_ExplicitInstantiationDefinition
)
10596 InstantiateVariableDefinition(D
.getIdentifierLoc(), Prev
);
10599 // Check the new variable specialization against the parsed input.
10600 if (PrevTemplate
&& !Context
.hasSameType(Prev
->getType(), R
)) {
10601 Diag(T
->getTypeLoc().getBeginLoc(),
10602 diag::err_invalid_var_template_spec_type
)
10603 << 0 << PrevTemplate
<< R
<< Prev
->getType();
10604 Diag(PrevTemplate
->getLocation(), diag::note_template_declared_here
)
10605 << 2 << PrevTemplate
->getDeclName();
10609 // FIXME: Create an ExplicitInstantiation node?
10610 return (Decl
*) nullptr;
10613 // If the declarator is a template-id, translate the parser's template
10614 // argument list into our AST format.
10615 bool HasExplicitTemplateArgs
= false;
10616 TemplateArgumentListInfo TemplateArgs
;
10617 if (D
.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
) {
10618 TemplateArgs
= makeTemplateArgumentListInfo(*this, *D
.getName().TemplateId
);
10619 HasExplicitTemplateArgs
= true;
10622 // C++ [temp.explicit]p1:
10623 // A [...] function [...] can be explicitly instantiated from its template.
10624 // A member function [...] of a class template can be explicitly
10625 // instantiated from the member definition associated with its class
10627 UnresolvedSet
<8> TemplateMatches
;
10628 FunctionDecl
*NonTemplateMatch
= nullptr;
10629 TemplateSpecCandidateSet
FailedCandidates(D
.getIdentifierLoc());
10630 for (LookupResult::iterator P
= Previous
.begin(), PEnd
= Previous
.end();
10632 NamedDecl
*Prev
= *P
;
10633 if (!HasExplicitTemplateArgs
) {
10634 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(Prev
)) {
10635 QualType Adjusted
= adjustCCAndNoReturn(R
, Method
->getType(),
10636 /*AdjustExceptionSpec*/true);
10637 if (Context
.hasSameUnqualifiedType(Method
->getType(), Adjusted
)) {
10638 if (Method
->getPrimaryTemplate()) {
10639 TemplateMatches
.addDecl(Method
, P
.getAccess());
10641 // FIXME: Can this assert ever happen? Needs a test.
10642 assert(!NonTemplateMatch
&& "Multiple NonTemplateMatches");
10643 NonTemplateMatch
= Method
;
10649 FunctionTemplateDecl
*FunTmpl
= dyn_cast
<FunctionTemplateDecl
>(Prev
);
10653 TemplateDeductionInfo
Info(FailedCandidates
.getLocation());
10654 FunctionDecl
*Specialization
= nullptr;
10655 if (TemplateDeductionResult TDK
10656 = DeduceTemplateArguments(FunTmpl
,
10657 (HasExplicitTemplateArgs
? &TemplateArgs
10659 R
, Specialization
, Info
)) {
10660 // Keep track of almost-matches.
10661 FailedCandidates
.addCandidate()
10662 .set(P
.getPair(), FunTmpl
->getTemplatedDecl(),
10663 MakeDeductionFailureInfo(Context
, TDK
, Info
));
10668 // Target attributes are part of the cuda function signature, so
10669 // the cuda target of the instantiated function must match that of its
10670 // template. Given that C++ template deduction does not take
10671 // target attributes into account, we reject candidates here that
10672 // have a different target.
10673 if (LangOpts
.CUDA
&&
10674 IdentifyCUDATarget(Specialization
,
10675 /* IgnoreImplicitHDAttr = */ true) !=
10676 IdentifyCUDATarget(D
.getDeclSpec().getAttributes())) {
10677 FailedCandidates
.addCandidate().set(
10678 P
.getPair(), FunTmpl
->getTemplatedDecl(),
10679 MakeDeductionFailureInfo(Context
, TDK_CUDATargetMismatch
, Info
));
10683 TemplateMatches
.addDecl(Specialization
, P
.getAccess());
10686 FunctionDecl
*Specialization
= NonTemplateMatch
;
10687 if (!Specialization
) {
10688 // Find the most specialized function template specialization.
10689 UnresolvedSetIterator Result
= getMostSpecialized(
10690 TemplateMatches
.begin(), TemplateMatches
.end(), FailedCandidates
,
10691 D
.getIdentifierLoc(),
10692 PDiag(diag::err_explicit_instantiation_not_known
) << Name
,
10693 PDiag(diag::err_explicit_instantiation_ambiguous
) << Name
,
10694 PDiag(diag::note_explicit_instantiation_candidate
));
10696 if (Result
== TemplateMatches
.end())
10699 // Ignore access control bits, we don't need them for redeclaration checking.
10700 Specialization
= cast
<FunctionDecl
>(*Result
);
10703 // C++11 [except.spec]p4
10704 // In an explicit instantiation an exception-specification may be specified,
10705 // but is not required.
10706 // If an exception-specification is specified in an explicit instantiation
10707 // directive, it shall be compatible with the exception-specifications of
10708 // other declarations of that function.
10709 if (auto *FPT
= R
->getAs
<FunctionProtoType
>())
10710 if (FPT
->hasExceptionSpec()) {
10712 diag::err_mismatched_exception_spec_explicit_instantiation
;
10713 if (getLangOpts().MicrosoftExt
)
10714 DiagID
= diag::ext_mismatched_exception_spec_explicit_instantiation
;
10715 bool Result
= CheckEquivalentExceptionSpec(
10716 PDiag(DiagID
) << Specialization
->getType(),
10717 PDiag(diag::note_explicit_instantiation_here
),
10718 Specialization
->getType()->getAs
<FunctionProtoType
>(),
10719 Specialization
->getLocation(), FPT
, D
.getBeginLoc());
10720 // In Microsoft mode, mismatching exception specifications just cause a
10722 if (!getLangOpts().MicrosoftExt
&& Result
)
10726 if (Specialization
->getTemplateSpecializationKind() == TSK_Undeclared
) {
10727 Diag(D
.getIdentifierLoc(),
10728 diag::err_explicit_instantiation_member_function_not_instantiated
)
10730 << (Specialization
->getTemplateSpecializationKind() ==
10731 TSK_ExplicitSpecialization
);
10732 Diag(Specialization
->getLocation(), diag::note_explicit_instantiation_here
);
10736 FunctionDecl
*PrevDecl
= Specialization
->getPreviousDecl();
10737 if (!PrevDecl
&& Specialization
->isThisDeclarationADefinition())
10738 PrevDecl
= Specialization
;
10741 bool HasNoEffect
= false;
10742 if (CheckSpecializationInstantiationRedecl(D
.getIdentifierLoc(), TSK
,
10744 PrevDecl
->getTemplateSpecializationKind(),
10745 PrevDecl
->getPointOfInstantiation(),
10749 // FIXME: We may still want to build some representation of this
10750 // explicit specialization.
10752 return (Decl
*) nullptr;
10755 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
10757 // valarray<size_t>::valarray(size_t) and
10758 // valarray<size_t>::~valarray()
10759 // that it declared to have internal linkage with the internal_linkage
10760 // attribute. Ignore the explicit instantiation declaration in this case.
10761 if (Specialization
->hasAttr
<InternalLinkageAttr
>() &&
10762 TSK
== TSK_ExplicitInstantiationDeclaration
) {
10763 if (auto *RD
= dyn_cast
<CXXRecordDecl
>(Specialization
->getDeclContext()))
10764 if (RD
->getIdentifier() && RD
->getIdentifier()->isStr("valarray") &&
10765 RD
->isInStdNamespace())
10766 return (Decl
*) nullptr;
10769 ProcessDeclAttributeList(S
, Specialization
, D
.getDeclSpec().getAttributes());
10771 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10772 // instantiation declarations.
10773 if (TSK
== TSK_ExplicitInstantiationDefinition
&&
10774 Specialization
->hasAttr
<DLLImportAttr
>() &&
10775 Context
.getTargetInfo().getCXXABI().isMicrosoft())
10776 TSK
= TSK_ExplicitInstantiationDeclaration
;
10778 Specialization
->setTemplateSpecializationKind(TSK
, D
.getIdentifierLoc());
10780 if (Specialization
->isDefined()) {
10781 // Let the ASTConsumer know that this function has been explicitly
10782 // instantiated now, and its linkage might have changed.
10783 Consumer
.HandleTopLevelDecl(DeclGroupRef(Specialization
));
10784 } else if (TSK
== TSK_ExplicitInstantiationDefinition
)
10785 InstantiateFunctionDefinition(D
.getIdentifierLoc(), Specialization
);
10787 // C++0x [temp.explicit]p2:
10788 // If the explicit instantiation is for a member function, a member class
10789 // or a static data member of a class template specialization, the name of
10790 // the class template specialization in the qualified-id for the member
10791 // name shall be a simple-template-id.
10793 // C++98 has the same restriction, just worded differently.
10794 FunctionTemplateDecl
*FunTmpl
= Specialization
->getPrimaryTemplate();
10795 if (D
.getName().getKind() != UnqualifiedIdKind::IK_TemplateId
&& !FunTmpl
&&
10796 D
.getCXXScopeSpec().isSet() &&
10797 !ScopeSpecifierHasTemplateId(D
.getCXXScopeSpec()))
10798 Diag(D
.getIdentifierLoc(),
10799 diag::ext_explicit_instantiation_without_qualified_id
)
10800 << Specialization
<< D
.getCXXScopeSpec().getRange();
10802 CheckExplicitInstantiation(
10804 FunTmpl
? (NamedDecl
*)FunTmpl
10805 : Specialization
->getInstantiatedFromMemberFunction(),
10806 D
.getIdentifierLoc(), D
.getCXXScopeSpec().isSet(), TSK
);
10808 // FIXME: Create some kind of ExplicitInstantiationDecl here.
10809 return (Decl
*) nullptr;
10813 Sema::ActOnDependentTag(Scope
*S
, unsigned TagSpec
, TagUseKind TUK
,
10814 const CXXScopeSpec
&SS
, IdentifierInfo
*Name
,
10815 SourceLocation TagLoc
, SourceLocation NameLoc
) {
10816 // This has to hold, because SS is expected to be defined.
10817 assert(Name
&& "Expected a name in a dependent tag");
10819 NestedNameSpecifier
*NNS
= SS
.getScopeRep();
10823 TagTypeKind Kind
= TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec
);
10825 if (TUK
== TUK_Declaration
|| TUK
== TUK_Definition
) {
10826 Diag(NameLoc
, diag::err_dependent_tag_decl
)
10827 << (TUK
== TUK_Definition
) << Kind
<< SS
.getRange();
10831 // Create the resulting type.
10832 ElaboratedTypeKeyword Kwd
= TypeWithKeyword::getKeywordForTagTypeKind(Kind
);
10833 QualType Result
= Context
.getDependentNameType(Kwd
, NNS
, Name
);
10835 // Create type-source location information for this type.
10836 TypeLocBuilder TLB
;
10837 DependentNameTypeLoc TL
= TLB
.push
<DependentNameTypeLoc
>(Result
);
10838 TL
.setElaboratedKeywordLoc(TagLoc
);
10839 TL
.setQualifierLoc(SS
.getWithLocInContext(Context
));
10840 TL
.setNameLoc(NameLoc
);
10841 return CreateParsedType(Result
, TLB
.getTypeSourceInfo(Context
, Result
));
10844 TypeResult
Sema::ActOnTypenameType(Scope
*S
, SourceLocation TypenameLoc
,
10845 const CXXScopeSpec
&SS
,
10846 const IdentifierInfo
&II
,
10847 SourceLocation IdLoc
,
10848 ImplicitTypenameContext IsImplicitTypename
) {
10849 if (SS
.isInvalid())
10852 if (TypenameLoc
.isValid() && S
&& !S
->getTemplateParamParent())
10854 getLangOpts().CPlusPlus11
?
10855 diag::warn_cxx98_compat_typename_outside_of_template
:
10856 diag::ext_typename_outside_of_template
)
10857 << FixItHint::CreateRemoval(TypenameLoc
);
10859 NestedNameSpecifierLoc QualifierLoc
= SS
.getWithLocInContext(Context
);
10860 TypeSourceInfo
*TSI
= nullptr;
10862 CheckTypenameType((TypenameLoc
.isValid() ||
10863 IsImplicitTypename
== ImplicitTypenameContext::Yes
)
10864 ? ElaboratedTypeKeyword::Typename
10865 : ElaboratedTypeKeyword::None
,
10866 TypenameLoc
, QualifierLoc
, II
, IdLoc
, &TSI
,
10867 /*DeducedTSTContext=*/true);
10870 return CreateParsedType(T
, TSI
);
10874 Sema::ActOnTypenameType(Scope
*S
,
10875 SourceLocation TypenameLoc
,
10876 const CXXScopeSpec
&SS
,
10877 SourceLocation TemplateKWLoc
,
10878 TemplateTy TemplateIn
,
10879 IdentifierInfo
*TemplateII
,
10880 SourceLocation TemplateIILoc
,
10881 SourceLocation LAngleLoc
,
10882 ASTTemplateArgsPtr TemplateArgsIn
,
10883 SourceLocation RAngleLoc
) {
10884 if (TypenameLoc
.isValid() && S
&& !S
->getTemplateParamParent())
10886 getLangOpts().CPlusPlus11
?
10887 diag::warn_cxx98_compat_typename_outside_of_template
:
10888 diag::ext_typename_outside_of_template
)
10889 << FixItHint::CreateRemoval(TypenameLoc
);
10891 // Strangely, non-type results are not ignored by this lookup, so the
10892 // program is ill-formed if it finds an injected-class-name.
10893 if (TypenameLoc
.isValid()) {
10895 dyn_cast_or_null
<CXXRecordDecl
>(computeDeclContext(SS
, false));
10896 if (LookupRD
&& LookupRD
->getIdentifier() == TemplateII
) {
10897 Diag(TemplateIILoc
,
10898 diag::ext_out_of_line_qualified_id_type_names_constructor
)
10899 << TemplateII
<< 0 /*injected-class-name used as template name*/
10900 << (TemplateKWLoc
.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
10904 // Translate the parser's template argument list in our AST format.
10905 TemplateArgumentListInfo
TemplateArgs(LAngleLoc
, RAngleLoc
);
10906 translateTemplateArguments(TemplateArgsIn
, TemplateArgs
);
10908 TemplateName Template
= TemplateIn
.get();
10909 if (DependentTemplateName
*DTN
= Template
.getAsDependentTemplateName()) {
10910 // Construct a dependent template specialization type.
10911 assert(DTN
&& "dependent template has non-dependent name?");
10912 assert(DTN
->getQualifier() == SS
.getScopeRep());
10913 QualType T
= Context
.getDependentTemplateSpecializationType(
10914 ElaboratedTypeKeyword::Typename
, DTN
->getQualifier(),
10915 DTN
->getIdentifier(), TemplateArgs
.arguments());
10917 // Create source-location information for this type.
10918 TypeLocBuilder Builder
;
10919 DependentTemplateSpecializationTypeLoc SpecTL
10920 = Builder
.push
<DependentTemplateSpecializationTypeLoc
>(T
);
10921 SpecTL
.setElaboratedKeywordLoc(TypenameLoc
);
10922 SpecTL
.setQualifierLoc(SS
.getWithLocInContext(Context
));
10923 SpecTL
.setTemplateKeywordLoc(TemplateKWLoc
);
10924 SpecTL
.setTemplateNameLoc(TemplateIILoc
);
10925 SpecTL
.setLAngleLoc(LAngleLoc
);
10926 SpecTL
.setRAngleLoc(RAngleLoc
);
10927 for (unsigned I
= 0, N
= TemplateArgs
.size(); I
!= N
; ++I
)
10928 SpecTL
.setArgLocInfo(I
, TemplateArgs
[I
].getLocInfo());
10929 return CreateParsedType(T
, Builder
.getTypeSourceInfo(Context
, T
));
10932 QualType T
= CheckTemplateIdType(Template
, TemplateIILoc
, TemplateArgs
);
10936 // Provide source-location information for the template specialization type.
10937 TypeLocBuilder Builder
;
10938 TemplateSpecializationTypeLoc SpecTL
10939 = Builder
.push
<TemplateSpecializationTypeLoc
>(T
);
10940 SpecTL
.setTemplateKeywordLoc(TemplateKWLoc
);
10941 SpecTL
.setTemplateNameLoc(TemplateIILoc
);
10942 SpecTL
.setLAngleLoc(LAngleLoc
);
10943 SpecTL
.setRAngleLoc(RAngleLoc
);
10944 for (unsigned I
= 0, N
= TemplateArgs
.size(); I
!= N
; ++I
)
10945 SpecTL
.setArgLocInfo(I
, TemplateArgs
[I
].getLocInfo());
10947 T
= Context
.getElaboratedType(ElaboratedTypeKeyword::Typename
,
10948 SS
.getScopeRep(), T
);
10949 ElaboratedTypeLoc TL
= Builder
.push
<ElaboratedTypeLoc
>(T
);
10950 TL
.setElaboratedKeywordLoc(TypenameLoc
);
10951 TL
.setQualifierLoc(SS
.getWithLocInContext(Context
));
10953 TypeSourceInfo
*TSI
= Builder
.getTypeSourceInfo(Context
, T
);
10954 return CreateParsedType(T
, TSI
);
10958 /// Determine whether this failed name lookup should be treated as being
10959 /// disabled by a usage of std::enable_if.
10960 static bool isEnableIf(NestedNameSpecifierLoc NNS
, const IdentifierInfo
&II
,
10961 SourceRange
&CondRange
, Expr
*&Cond
) {
10962 // We must be looking for a ::type...
10963 if (!II
.isStr("type"))
10966 // ... within an explicitly-written template specialization...
10967 if (!NNS
|| !NNS
.getNestedNameSpecifier()->getAsType())
10969 TypeLoc EnableIfTy
= NNS
.getTypeLoc();
10970 TemplateSpecializationTypeLoc EnableIfTSTLoc
=
10971 EnableIfTy
.getAs
<TemplateSpecializationTypeLoc
>();
10972 if (!EnableIfTSTLoc
|| EnableIfTSTLoc
.getNumArgs() == 0)
10974 const TemplateSpecializationType
*EnableIfTST
= EnableIfTSTLoc
.getTypePtr();
10976 // ... which names a complete class template declaration...
10977 const TemplateDecl
*EnableIfDecl
=
10978 EnableIfTST
->getTemplateName().getAsTemplateDecl();
10979 if (!EnableIfDecl
|| EnableIfTST
->isIncompleteType())
10982 // ... called "enable_if".
10983 const IdentifierInfo
*EnableIfII
=
10984 EnableIfDecl
->getDeclName().getAsIdentifierInfo();
10985 if (!EnableIfII
|| !EnableIfII
->isStr("enable_if"))
10988 // Assume the first template argument is the condition.
10989 CondRange
= EnableIfTSTLoc
.getArgLoc(0).getSourceRange();
10991 // Dig out the condition.
10993 if (EnableIfTSTLoc
.getArgLoc(0).getArgument().getKind()
10994 != TemplateArgument::Expression
)
10997 Cond
= EnableIfTSTLoc
.getArgLoc(0).getSourceExpression();
10999 // Ignore Boolean literals; they add no value.
11000 if (isa
<CXXBoolLiteralExpr
>(Cond
->IgnoreParenCasts()))
11007 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword
,
11008 SourceLocation KeywordLoc
,
11009 NestedNameSpecifierLoc QualifierLoc
,
11010 const IdentifierInfo
&II
,
11011 SourceLocation IILoc
,
11012 TypeSourceInfo
**TSI
,
11013 bool DeducedTSTContext
) {
11014 QualType T
= CheckTypenameType(Keyword
, KeywordLoc
, QualifierLoc
, II
, IILoc
,
11015 DeducedTSTContext
);
11019 *TSI
= Context
.CreateTypeSourceInfo(T
);
11020 if (isa
<DependentNameType
>(T
)) {
11021 DependentNameTypeLoc TL
=
11022 (*TSI
)->getTypeLoc().castAs
<DependentNameTypeLoc
>();
11023 TL
.setElaboratedKeywordLoc(KeywordLoc
);
11024 TL
.setQualifierLoc(QualifierLoc
);
11025 TL
.setNameLoc(IILoc
);
11027 ElaboratedTypeLoc TL
= (*TSI
)->getTypeLoc().castAs
<ElaboratedTypeLoc
>();
11028 TL
.setElaboratedKeywordLoc(KeywordLoc
);
11029 TL
.setQualifierLoc(QualifierLoc
);
11030 TL
.getNamedTypeLoc().castAs
<TypeSpecTypeLoc
>().setNameLoc(IILoc
);
11035 /// Build the type that describes a C++ typename specifier,
11036 /// e.g., "typename T::type".
11038 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword
,
11039 SourceLocation KeywordLoc
,
11040 NestedNameSpecifierLoc QualifierLoc
,
11041 const IdentifierInfo
&II
,
11042 SourceLocation IILoc
, bool DeducedTSTContext
) {
11044 SS
.Adopt(QualifierLoc
);
11046 DeclContext
*Ctx
= nullptr;
11047 if (QualifierLoc
) {
11048 Ctx
= computeDeclContext(SS
);
11050 // If the nested-name-specifier is dependent and couldn't be
11051 // resolved to a type, build a typename type.
11052 assert(QualifierLoc
.getNestedNameSpecifier()->isDependent());
11053 return Context
.getDependentNameType(Keyword
,
11054 QualifierLoc
.getNestedNameSpecifier(),
11058 // If the nested-name-specifier refers to the current instantiation,
11059 // the "typename" keyword itself is superfluous. In C++03, the
11060 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
11061 // allows such extraneous "typename" keywords, and we retroactively
11062 // apply this DR to C++03 code with only a warning. In any case we continue.
11064 if (RequireCompleteDeclContext(SS
, Ctx
))
11068 DeclarationName
Name(&II
);
11069 LookupResult
Result(*this, Name
, IILoc
, LookupOrdinaryName
);
11071 LookupQualifiedName(Result
, Ctx
, SS
);
11073 LookupName(Result
, CurScope
);
11074 unsigned DiagID
= 0;
11075 Decl
*Referenced
= nullptr;
11076 switch (Result
.getResultKind()) {
11077 case LookupResult::NotFound
: {
11078 // If we're looking up 'type' within a template named 'enable_if', produce
11079 // a more specific diagnostic.
11080 SourceRange CondRange
;
11081 Expr
*Cond
= nullptr;
11082 if (Ctx
&& isEnableIf(QualifierLoc
, II
, CondRange
, Cond
)) {
11083 // If we have a condition, narrow it down to the specific failed
11087 std::string FailedDescription
;
11088 std::tie(FailedCond
, FailedDescription
) =
11089 findFailedBooleanCondition(Cond
);
11091 Diag(FailedCond
->getExprLoc(),
11092 diag::err_typename_nested_not_found_requirement
)
11093 << FailedDescription
11094 << FailedCond
->getSourceRange();
11098 Diag(CondRange
.getBegin(),
11099 diag::err_typename_nested_not_found_enable_if
)
11100 << Ctx
<< CondRange
;
11104 DiagID
= Ctx
? diag::err_typename_nested_not_found
11105 : diag::err_unknown_typename
;
11109 case LookupResult::FoundUnresolvedValue
: {
11110 // We found a using declaration that is a value. Most likely, the using
11111 // declaration itself is meant to have the 'typename' keyword.
11112 SourceRange
FullRange(KeywordLoc
.isValid() ? KeywordLoc
: SS
.getBeginLoc(),
11114 Diag(IILoc
, diag::err_typename_refers_to_using_value_decl
)
11115 << Name
<< Ctx
<< FullRange
;
11116 if (UnresolvedUsingValueDecl
*Using
11117 = dyn_cast
<UnresolvedUsingValueDecl
>(Result
.getRepresentativeDecl())){
11118 SourceLocation Loc
= Using
->getQualifierLoc().getBeginLoc();
11119 Diag(Loc
, diag::note_using_value_decl_missing_typename
)
11120 << FixItHint::CreateInsertion(Loc
, "typename ");
11123 // Fall through to create a dependent typename type, from which we can recover
11127 case LookupResult::NotFoundInCurrentInstantiation
:
11128 // Okay, it's a member of an unknown instantiation.
11129 return Context
.getDependentNameType(Keyword
,
11130 QualifierLoc
.getNestedNameSpecifier(),
11133 case LookupResult::Found
:
11134 if (TypeDecl
*Type
= dyn_cast
<TypeDecl
>(Result
.getFoundDecl())) {
11135 // C++ [class.qual]p2:
11136 // In a lookup in which function names are not ignored and the
11137 // nested-name-specifier nominates a class C, if the name specified
11138 // after the nested-name-specifier, when looked up in C, is the
11139 // injected-class-name of C [...] then the name is instead considered
11140 // to name the constructor of class C.
11142 // Unlike in an elaborated-type-specifier, function names are not ignored
11143 // in typename-specifier lookup. However, they are ignored in all the
11144 // contexts where we form a typename type with no keyword (that is, in
11145 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
11147 // FIXME: That's not strictly true: mem-initializer-id lookup does not
11148 // ignore functions, but that appears to be an oversight.
11149 auto *LookupRD
= dyn_cast_or_null
<CXXRecordDecl
>(Ctx
);
11150 auto *FoundRD
= dyn_cast
<CXXRecordDecl
>(Type
);
11151 if (Keyword
== ElaboratedTypeKeyword::Typename
&& LookupRD
&& FoundRD
&&
11152 FoundRD
->isInjectedClassName() &&
11153 declaresSameEntity(LookupRD
, cast
<Decl
>(FoundRD
->getParent())))
11154 Diag(IILoc
, diag::ext_out_of_line_qualified_id_type_names_constructor
)
11155 << &II
<< 1 << 0 /*'typename' keyword used*/;
11157 // We found a type. Build an ElaboratedType, since the
11158 // typename-specifier was just sugar.
11159 MarkAnyDeclReferenced(Type
->getLocation(), Type
, /*OdrUse=*/false);
11160 return Context
.getElaboratedType(Keyword
,
11161 QualifierLoc
.getNestedNameSpecifier(),
11162 Context
.getTypeDeclType(Type
));
11165 // C++ [dcl.type.simple]p2:
11166 // A type-specifier of the form
11167 // typename[opt] nested-name-specifier[opt] template-name
11168 // is a placeholder for a deduced class type [...].
11169 if (getLangOpts().CPlusPlus17
) {
11170 if (auto *TD
= getAsTypeTemplateDecl(Result
.getFoundDecl())) {
11171 if (!DeducedTSTContext
) {
11172 QualType
T(QualifierLoc
11173 ? QualifierLoc
.getNestedNameSpecifier()->getAsType()
11176 Diag(IILoc
, diag::err_dependent_deduced_tst
)
11177 << (int)getTemplateNameKindForDiagnostics(TemplateName(TD
)) << T
;
11179 Diag(IILoc
, diag::err_deduced_tst
)
11180 << (int)getTemplateNameKindForDiagnostics(TemplateName(TD
));
11181 Diag(TD
->getLocation(), diag::note_template_decl_here
);
11184 return Context
.getElaboratedType(
11185 Keyword
, QualifierLoc
.getNestedNameSpecifier(),
11186 Context
.getDeducedTemplateSpecializationType(TemplateName(TD
),
11187 QualType(), false));
11191 DiagID
= Ctx
? diag::err_typename_nested_not_type
11192 : diag::err_typename_not_type
;
11193 Referenced
= Result
.getFoundDecl();
11196 case LookupResult::FoundOverloaded
:
11197 DiagID
= Ctx
? diag::err_typename_nested_not_type
11198 : diag::err_typename_not_type
;
11199 Referenced
= *Result
.begin();
11202 case LookupResult::Ambiguous
:
11206 // If we get here, it's because name lookup did not find a
11207 // type. Emit an appropriate diagnostic and return an error.
11208 SourceRange
FullRange(KeywordLoc
.isValid() ? KeywordLoc
: SS
.getBeginLoc(),
11211 Diag(IILoc
, DiagID
) << FullRange
<< Name
<< Ctx
;
11213 Diag(IILoc
, DiagID
) << FullRange
<< Name
;
11215 Diag(Referenced
->getLocation(),
11216 Ctx
? diag::note_typename_member_refers_here
11217 : diag::note_typename_refers_here
)
11223 // See Sema::RebuildTypeInCurrentInstantiation
11224 class CurrentInstantiationRebuilder
11225 : public TreeTransform
<CurrentInstantiationRebuilder
> {
11226 SourceLocation Loc
;
11227 DeclarationName Entity
;
11230 typedef TreeTransform
<CurrentInstantiationRebuilder
> inherited
;
11232 CurrentInstantiationRebuilder(Sema
&SemaRef
,
11233 SourceLocation Loc
,
11234 DeclarationName Entity
)
11235 : TreeTransform
<CurrentInstantiationRebuilder
>(SemaRef
),
11236 Loc(Loc
), Entity(Entity
) { }
11238 /// Determine whether the given type \p T has already been
11241 /// For the purposes of type reconstruction, a type has already been
11242 /// transformed if it is NULL or if it is not dependent.
11243 bool AlreadyTransformed(QualType T
) {
11244 return T
.isNull() || !T
->isInstantiationDependentType();
11247 /// Returns the location of the entity whose type is being
11249 SourceLocation
getBaseLocation() { return Loc
; }
11251 /// Returns the name of the entity whose type is being rebuilt.
11252 DeclarationName
getBaseEntity() { return Entity
; }
11254 /// Sets the "base" location and entity when that
11255 /// information is known based on another transformation.
11256 void setBase(SourceLocation Loc
, DeclarationName Entity
) {
11258 this->Entity
= Entity
;
11261 ExprResult
TransformLambdaExpr(LambdaExpr
*E
) {
11262 // Lambdas never need to be transformed.
11266 } // end anonymous namespace
11268 /// Rebuilds a type within the context of the current instantiation.
11270 /// The type \p T is part of the type of an out-of-line member definition of
11271 /// a class template (or class template partial specialization) that was parsed
11272 /// and constructed before we entered the scope of the class template (or
11273 /// partial specialization thereof). This routine will rebuild that type now
11274 /// that we have entered the declarator's scope, which may produce different
11275 /// canonical types, e.g.,
11278 /// template<typename T>
11280 /// typedef T* pointer;
11281 /// pointer data();
11284 /// template<typename T>
11285 /// typename X<T>::pointer X<T>::data() { ... }
11288 /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
11289 /// since we do not know that we can look into X<T> when we parsed the type.
11290 /// This function will rebuild the type, performing the lookup of "pointer"
11291 /// in X<T> and returning an ElaboratedType whose canonical type is the same
11292 /// as the canonical type of T*, allowing the return types of the out-of-line
11293 /// definition and the declaration to match.
11294 TypeSourceInfo
*Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo
*T
,
11295 SourceLocation Loc
,
11296 DeclarationName Name
) {
11297 if (!T
|| !T
->getType()->isInstantiationDependentType())
11300 CurrentInstantiationRebuilder
Rebuilder(*this, Loc
, Name
);
11301 return Rebuilder
.TransformType(T
);
11304 ExprResult
Sema::RebuildExprInCurrentInstantiation(Expr
*E
) {
11305 CurrentInstantiationRebuilder
Rebuilder(*this, E
->getExprLoc(),
11306 DeclarationName());
11307 return Rebuilder
.TransformExpr(E
);
11310 bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec
&SS
) {
11311 if (SS
.isInvalid())
11314 NestedNameSpecifierLoc QualifierLoc
= SS
.getWithLocInContext(Context
);
11315 CurrentInstantiationRebuilder
Rebuilder(*this, SS
.getRange().getBegin(),
11316 DeclarationName());
11317 NestedNameSpecifierLoc Rebuilt
11318 = Rebuilder
.TransformNestedNameSpecifierLoc(QualifierLoc
);
11326 /// Rebuild the template parameters now that we know we're in a current
11328 bool Sema::RebuildTemplateParamsInCurrentInstantiation(
11329 TemplateParameterList
*Params
) {
11330 for (unsigned I
= 0, N
= Params
->size(); I
!= N
; ++I
) {
11331 Decl
*Param
= Params
->getParam(I
);
11333 // There is nothing to rebuild in a type parameter.
11334 if (isa
<TemplateTypeParmDecl
>(Param
))
11337 // Rebuild the template parameter list of a template template parameter.
11338 if (TemplateTemplateParmDecl
*TTP
11339 = dyn_cast
<TemplateTemplateParmDecl
>(Param
)) {
11340 if (RebuildTemplateParamsInCurrentInstantiation(
11341 TTP
->getTemplateParameters()))
11347 // Rebuild the type of a non-type template parameter.
11348 NonTypeTemplateParmDecl
*NTTP
= cast
<NonTypeTemplateParmDecl
>(Param
);
11349 TypeSourceInfo
*NewTSI
11350 = RebuildTypeInCurrentInstantiation(NTTP
->getTypeSourceInfo(),
11351 NTTP
->getLocation(),
11352 NTTP
->getDeclName());
11356 if (NewTSI
->getType()->isUndeducedType()) {
11357 // C++17 [temp.dep.expr]p3:
11358 // An id-expression is type-dependent if it contains
11359 // - an identifier associated by name lookup with a non-type
11360 // template-parameter declared with a type that contains a
11361 // placeholder type (7.1.7.4),
11362 NewTSI
= SubstAutoTypeSourceInfoDependent(NewTSI
);
11365 if (NewTSI
!= NTTP
->getTypeSourceInfo()) {
11366 NTTP
->setTypeSourceInfo(NewTSI
);
11367 NTTP
->setType(NewTSI
->getType());
11374 /// Produces a formatted string that describes the binding of
11375 /// template parameters to template arguments.
11377 Sema::getTemplateArgumentBindingsText(const TemplateParameterList
*Params
,
11378 const TemplateArgumentList
&Args
) {
11379 return getTemplateArgumentBindingsText(Params
, Args
.data(), Args
.size());
11383 Sema::getTemplateArgumentBindingsText(const TemplateParameterList
*Params
,
11384 const TemplateArgument
*Args
,
11385 unsigned NumArgs
) {
11386 SmallString
<128> Str
;
11387 llvm::raw_svector_ostream
Out(Str
);
11389 if (!Params
|| Params
->size() == 0 || NumArgs
== 0)
11390 return std::string();
11392 for (unsigned I
= 0, N
= Params
->size(); I
!= N
; ++I
) {
11401 if (const IdentifierInfo
*Id
= Params
->getParam(I
)->getIdentifier()) {
11402 Out
<< Id
->getName();
11408 Args
[I
].print(getPrintingPolicy(), Out
,
11409 TemplateParameterList::shouldIncludeTypeForArgument(
11410 getPrintingPolicy(), Params
, I
));
11414 return std::string(Out
.str());
11417 void Sema::MarkAsLateParsedTemplate(FunctionDecl
*FD
, Decl
*FnD
,
11418 CachedTokens
&Toks
) {
11422 auto LPT
= std::make_unique
<LateParsedTemplate
>();
11424 // Take tokens to avoid allocations
11425 LPT
->Toks
.swap(Toks
);
11427 LPT
->FPO
= getCurFPFeatures();
11428 LateParsedTemplateMap
.insert(std::make_pair(FD
, std::move(LPT
)));
11430 FD
->setLateTemplateParsed(true);
11433 void Sema::UnmarkAsLateParsedTemplate(FunctionDecl
*FD
) {
11436 FD
->setLateTemplateParsed(false);
11439 bool Sema::IsInsideALocalClassWithinATemplateFunction() {
11440 DeclContext
*DC
= CurContext
;
11443 if (CXXRecordDecl
*RD
= dyn_cast
<CXXRecordDecl
>(CurContext
)) {
11444 const FunctionDecl
*FD
= RD
->isLocalClass();
11445 return (FD
&& FD
->getTemplatedKind() != FunctionDecl::TK_NonTemplate
);
11446 } else if (DC
->isTranslationUnit() || DC
->isNamespace())
11449 DC
= DC
->getParent();
11455 /// Walk the path from which a declaration was instantiated, and check
11456 /// that every explicit specialization along that path is visible. This enforces
11457 /// C++ [temp.expl.spec]/6:
11459 /// If a template, a member template or a member of a class template is
11460 /// explicitly specialized then that specialization shall be declared before
11461 /// the first use of that specialization that would cause an implicit
11462 /// instantiation to take place, in every translation unit in which such a
11463 /// use occurs; no diagnostic is required.
11465 /// and also C++ [temp.class.spec]/1:
11467 /// A partial specialization shall be declared before the first use of a
11468 /// class template specialization that would make use of the partial
11469 /// specialization as the result of an implicit or explicit instantiation
11470 /// in every translation unit in which such a use occurs; no diagnostic is
11472 class ExplicitSpecializationVisibilityChecker
{
11474 SourceLocation Loc
;
11475 llvm::SmallVector
<Module
*, 8> Modules
;
11476 Sema::AcceptableKind Kind
;
11479 ExplicitSpecializationVisibilityChecker(Sema
&S
, SourceLocation Loc
,
11480 Sema::AcceptableKind Kind
)
11481 : S(S
), Loc(Loc
), Kind(Kind
) {}
11483 void check(NamedDecl
*ND
) {
11484 if (auto *FD
= dyn_cast
<FunctionDecl
>(ND
))
11485 return checkImpl(FD
);
11486 if (auto *RD
= dyn_cast
<CXXRecordDecl
>(ND
))
11487 return checkImpl(RD
);
11488 if (auto *VD
= dyn_cast
<VarDecl
>(ND
))
11489 return checkImpl(VD
);
11490 if (auto *ED
= dyn_cast
<EnumDecl
>(ND
))
11491 return checkImpl(ED
);
11495 void diagnose(NamedDecl
*D
, bool IsPartialSpec
) {
11496 auto Kind
= IsPartialSpec
? Sema::MissingImportKind::PartialSpecialization
11497 : Sema::MissingImportKind::ExplicitSpecialization
;
11498 const bool Recover
= true;
11500 // If we got a custom set of modules (because only a subset of the
11501 // declarations are interesting), use them, otherwise let
11502 // diagnoseMissingImport intelligently pick some.
11503 if (Modules
.empty())
11504 S
.diagnoseMissingImport(Loc
, D
, Kind
, Recover
);
11506 S
.diagnoseMissingImport(Loc
, D
, D
->getLocation(), Modules
, Kind
, Recover
);
11509 bool CheckMemberSpecialization(const NamedDecl
*D
) {
11510 return Kind
== Sema::AcceptableKind::Visible
11511 ? S
.hasVisibleMemberSpecialization(D
)
11512 : S
.hasReachableMemberSpecialization(D
);
11515 bool CheckExplicitSpecialization(const NamedDecl
*D
) {
11516 return Kind
== Sema::AcceptableKind::Visible
11517 ? S
.hasVisibleExplicitSpecialization(D
)
11518 : S
.hasReachableExplicitSpecialization(D
);
11521 bool CheckDeclaration(const NamedDecl
*D
) {
11522 return Kind
== Sema::AcceptableKind::Visible
? S
.hasVisibleDeclaration(D
)
11523 : S
.hasReachableDeclaration(D
);
11526 // Check a specific declaration. There are three problematic cases:
11528 // 1) The declaration is an explicit specialization of a template
11530 // 2) The declaration is an explicit specialization of a member of an
11531 // templated class.
11532 // 3) The declaration is an instantiation of a template, and that template
11533 // is an explicit specialization of a member of a templated class.
11535 // We don't need to go any deeper than that, as the instantiation of the
11536 // surrounding class / etc is not triggered by whatever triggered this
11537 // instantiation, and thus should be checked elsewhere.
11538 template<typename SpecDecl
>
11539 void checkImpl(SpecDecl
*Spec
) {
11540 bool IsHiddenExplicitSpecialization
= false;
11541 if (Spec
->getTemplateSpecializationKind() == TSK_ExplicitSpecialization
) {
11542 IsHiddenExplicitSpecialization
= Spec
->getMemberSpecializationInfo()
11543 ? !CheckMemberSpecialization(Spec
)
11544 : !CheckExplicitSpecialization(Spec
);
11546 checkInstantiated(Spec
);
11549 if (IsHiddenExplicitSpecialization
)
11550 diagnose(Spec
->getMostRecentDecl(), false);
11553 void checkInstantiated(FunctionDecl
*FD
) {
11554 if (auto *TD
= FD
->getPrimaryTemplate())
11558 void checkInstantiated(CXXRecordDecl
*RD
) {
11559 auto *SD
= dyn_cast
<ClassTemplateSpecializationDecl
>(RD
);
11563 auto From
= SD
->getSpecializedTemplateOrPartial();
11564 if (auto *TD
= From
.dyn_cast
<ClassTemplateDecl
*>())
11566 else if (auto *TD
=
11567 From
.dyn_cast
<ClassTemplatePartialSpecializationDecl
*>()) {
11568 if (!CheckDeclaration(TD
))
11569 diagnose(TD
, true);
11574 void checkInstantiated(VarDecl
*RD
) {
11575 auto *SD
= dyn_cast
<VarTemplateSpecializationDecl
>(RD
);
11579 auto From
= SD
->getSpecializedTemplateOrPartial();
11580 if (auto *TD
= From
.dyn_cast
<VarTemplateDecl
*>())
11582 else if (auto *TD
=
11583 From
.dyn_cast
<VarTemplatePartialSpecializationDecl
*>()) {
11584 if (!CheckDeclaration(TD
))
11585 diagnose(TD
, true);
11590 void checkInstantiated(EnumDecl
*FD
) {}
11592 template<typename TemplDecl
>
11593 void checkTemplate(TemplDecl
*TD
) {
11594 if (TD
->isMemberSpecialization()) {
11595 if (!CheckMemberSpecialization(TD
))
11596 diagnose(TD
->getMostRecentDecl(), false);
11600 } // end anonymous namespace
11602 void Sema::checkSpecializationVisibility(SourceLocation Loc
, NamedDecl
*Spec
) {
11603 if (!getLangOpts().Modules
)
11606 ExplicitSpecializationVisibilityChecker(*this, Loc
,
11607 Sema::AcceptableKind::Visible
)
11611 void Sema::checkSpecializationReachability(SourceLocation Loc
,
11613 if (!getLangOpts().CPlusPlusModules
)
11614 return checkSpecializationVisibility(Loc
, Spec
);
11616 ExplicitSpecializationVisibilityChecker(*this, Loc
,
11617 Sema::AcceptableKind::Reachable
)