1 //===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //===----------------------------------------------------------------------===//
9 // This file implements semantic analysis for C++ templates.
10 //===----------------------------------------------------------------------===//
12 #include "TreeTransform.h"
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.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/TypeVisitor.h"
21 #include "clang/Basic/Builtins.h"
22 #include "clang/Basic/LangOptions.h"
23 #include "clang/Basic/PartialDiagnostic.h"
24 #include "clang/Basic/TargetInfo.h"
25 #include "clang/Sema/DeclSpec.h"
26 #include "clang/Sema/Lookup.h"
27 #include "clang/Sema/ParsedTemplate.h"
28 #include "clang/Sema/Scope.h"
29 #include "clang/Sema/SemaInternal.h"
30 #include "clang/Sema/Template.h"
31 #include "clang/Sema/TemplateDeduction.h"
32 #include "llvm/ADT/SmallBitVector.h"
33 #include "llvm/ADT/SmallString.h"
34 #include "llvm/ADT/StringExtras.h"
36 using namespace clang;
39 // Exported for use by Parser.
41 clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
43 if (!N) return SourceRange();
44 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
47 /// \brief Determine whether the declaration found is acceptable as the name
48 /// of a template and, if so, return that template declaration. Otherwise,
50 static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
52 bool AllowFunctionTemplates) {
53 NamedDecl *D = Orig->getUnderlyingDecl();
55 if (isa<TemplateDecl>(D)) {
56 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
62 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
63 // C++ [temp.local]p1:
64 // Like normal (non-template) classes, class templates have an
65 // injected-class-name (Clause 9). The injected-class-name
66 // can be used with or without a template-argument-list. When
67 // it is used without a template-argument-list, it is
68 // equivalent to the injected-class-name followed by the
69 // template-parameters of the class template enclosed in
70 // <>. When it is used with a template-argument-list, it
71 // refers to the specified class template specialization,
72 // which could be the current specialization or another
74 if (Record->isInjectedClassName()) {
75 Record = cast<CXXRecordDecl>(Record->getDeclContext());
76 if (Record->getDescribedClassTemplate())
77 return Record->getDescribedClassTemplate();
79 if (ClassTemplateSpecializationDecl *Spec
80 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
81 return Spec->getSpecializedTemplate();
90 void Sema::FilterAcceptableTemplateNames(LookupResult &R,
91 bool AllowFunctionTemplates) {
92 // The set of class templates we've already seen.
93 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
94 LookupResult::Filter filter = R.makeFilter();
95 while (filter.hasNext()) {
96 NamedDecl *Orig = filter.next();
97 NamedDecl *Repl = isAcceptableTemplateName(Context, Orig,
98 AllowFunctionTemplates);
101 else if (Repl != Orig) {
103 // C++ [temp.local]p3:
104 // A lookup that finds an injected-class-name (10.2) can result in an
105 // ambiguity in certain cases (for example, if it is found in more than
106 // one base class). If all of the injected-class-names that are found
107 // refer to specializations of the same class template, and if the name
108 // is used as a template-name, the reference refers to the class
109 // template itself and not a specialization thereof, and is not
111 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
112 if (!ClassTemplates.insert(ClassTmpl).second) {
117 // FIXME: we promote access to public here as a workaround to
118 // the fact that LookupResult doesn't let us remember that we
119 // found this template through a particular injected class name,
120 // which means we end up doing nasty things to the invariants.
121 // Pretending that access is public is *much* safer.
122 filter.replace(Repl, AS_public);
128 bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
129 bool AllowFunctionTemplates) {
130 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
131 if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
137 TemplateNameKind Sema::isTemplateName(Scope *S,
139 bool hasTemplateKeyword,
141 ParsedType ObjectTypePtr,
142 bool EnteringContext,
143 TemplateTy &TemplateResult,
144 bool &MemberOfUnknownSpecialization) {
145 assert(getLangOpts().CPlusPlus && "No template names in C!");
147 DeclarationName TName;
148 MemberOfUnknownSpecialization = false;
150 switch (Name.getKind()) {
151 case UnqualifiedId::IK_Identifier:
152 TName = DeclarationName(Name.Identifier);
155 case UnqualifiedId::IK_OperatorFunctionId:
156 TName = Context.DeclarationNames.getCXXOperatorName(
157 Name.OperatorFunctionId.Operator);
160 case UnqualifiedId::IK_LiteralOperatorId:
161 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
165 return TNK_Non_template;
168 QualType ObjectType = ObjectTypePtr.get();
170 LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
171 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
172 MemberOfUnknownSpecialization);
173 if (R.empty()) return TNK_Non_template;
174 if (R.isAmbiguous()) {
175 // Suppress diagnostics; we'll redo this lookup later.
176 R.suppressDiagnostics();
178 // FIXME: we might have ambiguous templates, in which case we
179 // should at least parse them properly!
180 return TNK_Non_template;
183 TemplateName Template;
184 TemplateNameKind TemplateKind;
186 unsigned ResultCount = R.end() - R.begin();
187 if (ResultCount > 1) {
188 // We assume that we'll preserve the qualifier from a function
189 // template name in other ways.
190 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
191 TemplateKind = TNK_Function_template;
193 // We'll do this lookup again later.
194 R.suppressDiagnostics();
196 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
198 if (SS.isSet() && !SS.isInvalid()) {
199 NestedNameSpecifier *Qualifier = SS.getScopeRep();
200 Template = Context.getQualifiedTemplateName(Qualifier,
201 hasTemplateKeyword, TD);
203 Template = TemplateName(TD);
206 if (isa<FunctionTemplateDecl>(TD)) {
207 TemplateKind = TNK_Function_template;
209 // We'll do this lookup again later.
210 R.suppressDiagnostics();
212 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
213 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
214 isa<BuiltinTemplateDecl>(TD));
216 isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template;
220 TemplateResult = TemplateTy::make(Template);
224 bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
225 SourceLocation IILoc,
227 const CXXScopeSpec *SS,
228 TemplateTy &SuggestedTemplate,
229 TemplateNameKind &SuggestedKind) {
230 // We can't recover unless there's a dependent scope specifier preceding the
232 // FIXME: Typo correction?
233 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
234 computeDeclContext(*SS))
237 // The code is missing a 'template' keyword prior to the dependent template
239 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
240 Diag(IILoc, diag::err_template_kw_missing)
241 << Qualifier << II.getName()
242 << FixItHint::CreateInsertion(IILoc, "template ");
244 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
245 SuggestedKind = TNK_Dependent_template_name;
249 void Sema::LookupTemplateName(LookupResult &Found,
250 Scope *S, CXXScopeSpec &SS,
252 bool EnteringContext,
253 bool &MemberOfUnknownSpecialization) {
254 // Determine where to perform name lookup
255 MemberOfUnknownSpecialization = false;
256 DeclContext *LookupCtx = nullptr;
257 bool isDependent = false;
258 if (!ObjectType.isNull()) {
259 // This nested-name-specifier occurs in a member access expression, e.g.,
260 // x->B::f, and we are looking into the type of the object.
261 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
262 LookupCtx = computeDeclContext(ObjectType);
263 isDependent = ObjectType->isDependentType();
264 assert((isDependent || !ObjectType->isIncompleteType() ||
265 ObjectType->castAs<TagType>()->isBeingDefined()) &&
266 "Caller should have completed object type");
268 // Template names cannot appear inside an Objective-C class or object type.
269 if (ObjectType->isObjCObjectOrInterfaceType()) {
273 } else if (SS.isSet()) {
274 // This nested-name-specifier occurs after another nested-name-specifier,
275 // so long into the context associated with the prior nested-name-specifier.
276 LookupCtx = computeDeclContext(SS, EnteringContext);
277 isDependent = isDependentScopeSpecifier(SS);
279 // The declaration context must be complete.
280 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
284 bool ObjectTypeSearchedInScope = false;
285 bool AllowFunctionTemplatesInLookup = true;
287 // Perform "qualified" name lookup into the declaration context we
288 // computed, which is either the type of the base of a member access
289 // expression or the declaration context associated with a prior
290 // nested-name-specifier.
291 LookupQualifiedName(Found, LookupCtx);
292 if (!ObjectType.isNull() && Found.empty()) {
293 // C++ [basic.lookup.classref]p1:
294 // In a class member access expression (5.2.5), if the . or -> token is
295 // immediately followed by an identifier followed by a <, the
296 // identifier must be looked up to determine whether the < is the
297 // beginning of a template argument list (14.2) or a less-than operator.
298 // The identifier is first looked up in the class of the object
299 // expression. If the identifier is not found, it is then looked up in
300 // the context of the entire postfix-expression and shall name a class
301 // or function template.
302 if (S) LookupName(Found, S);
303 ObjectTypeSearchedInScope = true;
304 AllowFunctionTemplatesInLookup = false;
306 } else if (isDependent && (!S || ObjectType.isNull())) {
307 // We cannot look into a dependent object type or nested nme
309 MemberOfUnknownSpecialization = true;
312 // Perform unqualified name lookup in the current scope.
313 LookupName(Found, S);
315 if (!ObjectType.isNull())
316 AllowFunctionTemplatesInLookup = false;
319 if (Found.empty() && !isDependent) {
320 // If we did not find any names, attempt to correct any typos.
321 DeclarationName Name = Found.getLookupName();
323 // Simple filter callback that, for keywords, only accepts the C++ *_cast
324 auto FilterCCC = llvm::make_unique<CorrectionCandidateCallback>();
325 FilterCCC->WantTypeSpecifiers = false;
326 FilterCCC->WantExpressionKeywords = false;
327 FilterCCC->WantRemainingKeywords = false;
328 FilterCCC->WantCXXNamedCasts = true;
329 if (TypoCorrection Corrected = CorrectTypo(
330 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS,
331 std::move(FilterCCC), CTK_ErrorRecovery, LookupCtx)) {
332 Found.setLookupName(Corrected.getCorrection());
333 if (auto *ND = Corrected.getFoundDecl())
335 FilterAcceptableTemplateNames(Found);
336 if (!Found.empty()) {
338 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
339 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
340 Name.getAsString() == CorrectedStr;
341 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
342 << Name << LookupCtx << DroppedSpecifier
345 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
349 Found.setLookupName(Name);
353 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
356 MemberOfUnknownSpecialization = true;
360 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
361 !getLangOpts().CPlusPlus11) {
362 // C++03 [basic.lookup.classref]p1:
363 // [...] If the lookup in the class of the object expression finds a
364 // template, the name is also looked up in the context of the entire
365 // postfix-expression and [...]
367 // Note: C++11 does not perform this second lookup.
368 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
370 LookupName(FoundOuter, S);
371 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
373 if (FoundOuter.empty()) {
374 // - if the name is not found, the name found in the class of the
375 // object expression is used, otherwise
376 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
377 FoundOuter.isAmbiguous()) {
378 // - if the name is found in the context of the entire
379 // postfix-expression and does not name a class template, the name
380 // found in the class of the object expression is used, otherwise
382 } else if (!Found.isSuppressingDiagnostics()) {
383 // - if the name found is a class template, it must refer to the same
384 // entity as the one found in the class of the object expression,
385 // otherwise the program is ill-formed.
386 if (!Found.isSingleResult() ||
387 Found.getFoundDecl()->getCanonicalDecl()
388 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
389 Diag(Found.getNameLoc(),
390 diag::ext_nested_name_member_ref_lookup_ambiguous)
391 << Found.getLookupName()
393 Diag(Found.getRepresentativeDecl()->getLocation(),
394 diag::note_ambig_member_ref_object_type)
396 Diag(FoundOuter.getFoundDecl()->getLocation(),
397 diag::note_ambig_member_ref_scope);
399 // Recover by taking the template that we found in the object
400 // expression's type.
406 /// ActOnDependentIdExpression - Handle a dependent id-expression that
407 /// was just parsed. This is only possible with an explicit scope
408 /// specifier naming a dependent type.
410 Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
411 SourceLocation TemplateKWLoc,
412 const DeclarationNameInfo &NameInfo,
413 bool isAddressOfOperand,
414 const TemplateArgumentListInfo *TemplateArgs) {
415 DeclContext *DC = getFunctionLevelDeclContext();
417 // C++11 [expr.prim.general]p12:
418 // An id-expression that denotes a non-static data member or non-static
419 // member function of a class can only be used:
421 // - if that id-expression denotes a non-static data member and it
422 // appears in an unevaluated operand.
424 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
425 // CXXDependentScopeMemberExpr. The former can instantiate to either
426 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
427 // always a MemberExpr.
428 bool MightBeCxx11UnevalField =
429 getLangOpts().CPlusPlus11 && isUnevaluatedContext();
431 if (!MightBeCxx11UnevalField && !isAddressOfOperand &&
432 isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
433 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
435 // Since the 'this' expression is synthesized, we don't need to
436 // perform the double-lookup check.
437 NamedDecl *FirstQualifierInScope = nullptr;
439 return CXXDependentScopeMemberExpr::Create(
440 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
441 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
442 FirstQualifierInScope, NameInfo, TemplateArgs);
445 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
449 Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
450 SourceLocation TemplateKWLoc,
451 const DeclarationNameInfo &NameInfo,
452 const TemplateArgumentListInfo *TemplateArgs) {
453 return DependentScopeDeclRefExpr::Create(
454 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
458 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
459 /// that the template parameter 'PrevDecl' is being shadowed by a new
460 /// declaration at location Loc. Returns true to indicate that this is
461 /// an error, and false otherwise.
462 void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
463 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
465 // Microsoft Visual C++ permits template parameters to be shadowed.
466 if (getLangOpts().MicrosoftExt)
469 // C++ [temp.local]p4:
470 // A template-parameter shall not be redeclared within its
471 // scope (including nested scopes).
472 Diag(Loc, diag::err_template_param_shadow)
473 << cast<NamedDecl>(PrevDecl)->getDeclName();
474 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
477 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
478 /// the parameter D to reference the templated declaration and return a pointer
479 /// to the template declaration. Otherwise, do nothing to D and return null.
480 TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
481 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
482 D = Temp->getTemplatedDecl();
488 ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
489 SourceLocation EllipsisLoc) const {
490 assert(Kind == Template &&
491 "Only template template arguments can be pack expansions here");
492 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
493 "Template template argument pack expansion without packs");
494 ParsedTemplateArgument Result(*this);
495 Result.EllipsisLoc = EllipsisLoc;
499 static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
500 const ParsedTemplateArgument &Arg) {
502 switch (Arg.getKind()) {
503 case ParsedTemplateArgument::Type: {
505 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
507 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
508 return TemplateArgumentLoc(TemplateArgument(T), DI);
511 case ParsedTemplateArgument::NonType: {
512 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
513 return TemplateArgumentLoc(TemplateArgument(E), E);
516 case ParsedTemplateArgument::Template: {
517 TemplateName Template = Arg.getAsTemplate().get();
518 TemplateArgument TArg;
519 if (Arg.getEllipsisLoc().isValid())
520 TArg = TemplateArgument(Template, Optional<unsigned int>());
523 return TemplateArgumentLoc(TArg,
524 Arg.getScopeSpec().getWithLocInContext(
527 Arg.getEllipsisLoc());
531 llvm_unreachable("Unhandled parsed template argument");
534 /// \brief Translates template arguments as provided by the parser
535 /// into template arguments used by semantic analysis.
536 void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
537 TemplateArgumentListInfo &TemplateArgs) {
538 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
539 TemplateArgs.addArgument(translateTemplateArgument(*this,
543 static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
545 IdentifierInfo *Name) {
546 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
547 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration);
548 if (PrevDecl && PrevDecl->isTemplateParameter())
549 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
552 /// ActOnTypeParameter - Called when a C++ template type parameter
553 /// (e.g., "typename T") has been parsed. Typename specifies whether
554 /// the keyword "typename" was used to declare the type parameter
555 /// (otherwise, "class" was used), and KeyLoc is the location of the
556 /// "class" or "typename" keyword. ParamName is the name of the
557 /// parameter (NULL indicates an unnamed template parameter) and
558 /// ParamNameLoc is the location of the parameter name (if any).
559 /// If the type parameter has a default argument, it will be added
560 /// later via ActOnTypeParameterDefault.
561 Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
562 SourceLocation EllipsisLoc,
563 SourceLocation KeyLoc,
564 IdentifierInfo *ParamName,
565 SourceLocation ParamNameLoc,
566 unsigned Depth, unsigned Position,
567 SourceLocation EqualLoc,
568 ParsedType DefaultArg) {
569 assert(S->isTemplateParamScope() &&
570 "Template type parameter not in template parameter scope!");
572 SourceLocation Loc = ParamNameLoc;
576 bool IsParameterPack = EllipsisLoc.isValid();
577 TemplateTypeParmDecl *Param
578 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
579 KeyLoc, Loc, Depth, Position, ParamName,
580 Typename, IsParameterPack);
581 Param->setAccess(AS_public);
584 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
586 // Add the template parameter into the current scope.
588 IdResolver.AddDecl(Param);
591 // C++0x [temp.param]p9:
592 // A default template-argument may be specified for any kind of
593 // template-parameter that is not a template parameter pack.
594 if (DefaultArg && IsParameterPack) {
595 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
596 DefaultArg = nullptr;
599 // Handle the default argument, if provided.
601 TypeSourceInfo *DefaultTInfo;
602 GetTypeFromParser(DefaultArg, &DefaultTInfo);
604 assert(DefaultTInfo && "expected source information for type");
606 // Check for unexpanded parameter packs.
607 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
608 UPPC_DefaultArgument))
611 // Check the template argument itself.
612 if (CheckTemplateArgument(Param, DefaultTInfo)) {
613 Param->setInvalidDecl();
617 Param->setDefaultArgument(DefaultTInfo);
623 /// \brief Check that the type of a non-type template parameter is
626 /// \returns the (possibly-promoted) parameter type if valid;
627 /// otherwise, produces a diagnostic and returns a NULL type.
629 Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
630 // We don't allow variably-modified types as the type of non-type template
632 if (T->isVariablyModifiedType()) {
633 Diag(Loc, diag::err_variably_modified_nontype_template_param)
638 // C++ [temp.param]p4:
640 // A non-type template-parameter shall have one of the following
641 // (optionally cv-qualified) types:
643 // -- integral or enumeration type,
644 if (T->isIntegralOrEnumerationType() ||
645 // -- pointer to object or pointer to function,
646 T->isPointerType() ||
647 // -- reference to object or reference to function,
648 T->isReferenceType() ||
649 // -- pointer to member,
650 T->isMemberPointerType() ||
651 // -- std::nullptr_t.
652 T->isNullPtrType() ||
653 // If T is a dependent type, we can't do the check now, so we
654 // assume that it is well-formed.
655 T->isDependentType()) {
656 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
657 // are ignored when determining its type.
658 return T.getUnqualifiedType();
661 // C++ [temp.param]p8:
663 // A non-type template-parameter of type "array of T" or
664 // "function returning T" is adjusted to be of type "pointer to
665 // T" or "pointer to function returning T", respectively.
666 else if (T->isArrayType() || T->isFunctionType())
667 return Context.getDecayedType(T);
669 Diag(Loc, diag::err_template_nontype_parm_bad_type)
675 Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
678 SourceLocation EqualLoc,
680 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
681 QualType T = TInfo->getType();
683 assert(S->isTemplateParamScope() &&
684 "Non-type template parameter not in template parameter scope!");
685 bool Invalid = false;
687 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
689 T = Context.IntTy; // Recover with an 'int' type.
693 IdentifierInfo *ParamName = D.getIdentifier();
694 bool IsParameterPack = D.hasEllipsis();
695 NonTypeTemplateParmDecl *Param
696 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
698 D.getIdentifierLoc(),
699 Depth, Position, ParamName, T,
700 IsParameterPack, TInfo);
701 Param->setAccess(AS_public);
704 Param->setInvalidDecl();
707 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
710 // Add the template parameter into the current scope.
712 IdResolver.AddDecl(Param);
715 // C++0x [temp.param]p9:
716 // A default template-argument may be specified for any kind of
717 // template-parameter that is not a template parameter pack.
718 if (Default && IsParameterPack) {
719 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
723 // Check the well-formedness of the default template argument, if provided.
725 // Check for unexpanded parameter packs.
726 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
729 TemplateArgument Converted;
730 ExprResult DefaultRes =
731 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
732 if (DefaultRes.isInvalid()) {
733 Param->setInvalidDecl();
736 Default = DefaultRes.get();
738 Param->setDefaultArgument(Default);
744 /// ActOnTemplateTemplateParameter - Called when a C++ template template
745 /// parameter (e.g. T in template <template \<typename> class T> class array)
746 /// has been parsed. S is the current scope.
747 Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
748 SourceLocation TmpLoc,
749 TemplateParameterList *Params,
750 SourceLocation EllipsisLoc,
751 IdentifierInfo *Name,
752 SourceLocation NameLoc,
755 SourceLocation EqualLoc,
756 ParsedTemplateArgument Default) {
757 assert(S->isTemplateParamScope() &&
758 "Template template parameter not in template parameter scope!");
760 // Construct the parameter object.
761 bool IsParameterPack = EllipsisLoc.isValid();
762 TemplateTemplateParmDecl *Param =
763 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
764 NameLoc.isInvalid()? TmpLoc : NameLoc,
765 Depth, Position, IsParameterPack,
767 Param->setAccess(AS_public);
769 // If the template template parameter has a name, then link the identifier
770 // into the scope and lookup mechanisms.
772 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
775 IdResolver.AddDecl(Param);
778 if (Params->size() == 0) {
779 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
780 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
781 Param->setInvalidDecl();
784 // C++0x [temp.param]p9:
785 // A default template-argument may be specified for any kind of
786 // template-parameter that is not a template parameter pack.
787 if (IsParameterPack && !Default.isInvalid()) {
788 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
789 Default = ParsedTemplateArgument();
792 if (!Default.isInvalid()) {
793 // Check only that we have a template template argument. We don't want to
794 // try to check well-formedness now, because our template template parameter
795 // might have dependent types in its template parameters, which we wouldn't
796 // be able to match now.
798 // If none of the template template parameter's template arguments mention
799 // other template parameters, we could actually perform more checking here.
800 // However, it isn't worth doing.
801 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
802 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
803 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
804 << DefaultArg.getSourceRange();
808 // Check for unexpanded parameter packs.
809 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
810 DefaultArg.getArgument().getAsTemplate(),
811 UPPC_DefaultArgument))
814 Param->setDefaultArgument(Context, DefaultArg);
820 /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
821 /// constrained by RequiresClause, that contains the template parameters in
823 TemplateParameterList *
824 Sema::ActOnTemplateParameterList(unsigned Depth,
825 SourceLocation ExportLoc,
826 SourceLocation TemplateLoc,
827 SourceLocation LAngleLoc,
828 ArrayRef<Decl *> Params,
829 SourceLocation RAngleLoc,
830 Expr *RequiresClause) {
831 if (ExportLoc.isValid())
832 Diag(ExportLoc, diag::warn_template_export_unsupported);
834 // FIXME: store RequiresClause
835 return TemplateParameterList::Create(
836 Context, TemplateLoc, LAngleLoc,
837 llvm::makeArrayRef((NamedDecl *const *)Params.data(), Params.size()),
841 static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
843 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
847 Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
848 SourceLocation KWLoc, CXXScopeSpec &SS,
849 IdentifierInfo *Name, SourceLocation NameLoc,
851 TemplateParameterList *TemplateParams,
852 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
853 SourceLocation FriendLoc,
854 unsigned NumOuterTemplateParamLists,
855 TemplateParameterList** OuterTemplateParamLists,
856 SkipBodyInfo *SkipBody) {
857 assert(TemplateParams && TemplateParams->size() > 0 &&
858 "No template parameters");
859 assert(TUK != TUK_Reference && "Can only declare or define class templates");
860 bool Invalid = false;
862 // Check that we can declare a template here.
863 if (CheckTemplateDeclScope(S, TemplateParams))
866 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
867 assert(Kind != TTK_Enum && "can't build template of enumerated type");
869 // There is no such thing as an unnamed class template.
871 Diag(KWLoc, diag::err_template_unnamed_class);
875 // Find any previous declaration with this name. For a friend with no
876 // scope explicitly specified, we only look for tag declarations (per
877 // C++11 [basic.lookup.elab]p2).
878 DeclContext *SemanticContext;
879 LookupResult Previous(*this, Name, NameLoc,
880 (SS.isEmpty() && TUK == TUK_Friend)
881 ? LookupTagName : LookupOrdinaryName,
883 if (SS.isNotEmpty() && !SS.isInvalid()) {
884 SemanticContext = computeDeclContext(SS, true);
885 if (!SemanticContext) {
886 // FIXME: Horrible, horrible hack! We can't currently represent this
887 // in the AST, and historically we have just ignored such friend
888 // class templates, so don't complain here.
889 Diag(NameLoc, TUK == TUK_Friend
890 ? diag::warn_template_qualified_friend_ignored
891 : diag::err_template_qualified_declarator_no_match)
892 << SS.getScopeRep() << SS.getRange();
893 return TUK != TUK_Friend;
896 if (RequireCompleteDeclContext(SS, SemanticContext))
899 // If we're adding a template to a dependent context, we may need to
900 // rebuilding some of the types used within the template parameter list,
901 // now that we know what the current instantiation is.
902 if (SemanticContext->isDependentContext()) {
903 ContextRAII SavedContext(*this, SemanticContext);
904 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
906 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
907 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
909 LookupQualifiedName(Previous, SemanticContext);
911 SemanticContext = CurContext;
913 // C++14 [class.mem]p14:
914 // If T is the name of a class, then each of the following shall have a
915 // name different from T:
916 // -- every member template of class T
917 if (TUK != TUK_Friend &&
918 DiagnoseClassNameShadow(SemanticContext,
919 DeclarationNameInfo(Name, NameLoc)))
922 LookupName(Previous, S);
925 if (Previous.isAmbiguous())
928 NamedDecl *PrevDecl = nullptr;
929 if (Previous.begin() != Previous.end())
930 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
932 // If there is a previous declaration with the same name, check
933 // whether this is a valid redeclaration.
934 ClassTemplateDecl *PrevClassTemplate
935 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
937 // We may have found the injected-class-name of a class template,
938 // class template partial specialization, or class template specialization.
939 // In these cases, grab the template that is being defined or specialized.
940 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
941 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
942 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
944 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
945 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
947 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
948 ->getSpecializedTemplate();
952 if (TUK == TUK_Friend) {
953 // C++ [namespace.memdef]p3:
954 // [...] When looking for a prior declaration of a class or a function
955 // declared as a friend, and when the name of the friend class or
956 // function is neither a qualified name nor a template-id, scopes outside
957 // the innermost enclosing namespace scope are not considered.
959 DeclContext *OutermostContext = CurContext;
960 while (!OutermostContext->isFileContext())
961 OutermostContext = OutermostContext->getLookupParent();
964 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
965 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
966 SemanticContext = PrevDecl->getDeclContext();
968 // Declarations in outer scopes don't matter. However, the outermost
969 // context we computed is the semantic context for our new
971 PrevDecl = PrevClassTemplate = nullptr;
972 SemanticContext = OutermostContext;
974 // Check that the chosen semantic context doesn't already contain a
975 // declaration of this name as a non-tag type.
976 Previous.clear(LookupOrdinaryName);
977 DeclContext *LookupContext = SemanticContext;
978 while (LookupContext->isTransparentContext())
979 LookupContext = LookupContext->getLookupParent();
980 LookupQualifiedName(Previous, LookupContext);
982 if (Previous.isAmbiguous())
985 if (Previous.begin() != Previous.end())
986 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
989 } else if (PrevDecl &&
990 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
992 PrevDecl = PrevClassTemplate = nullptr;
994 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
995 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
997 !(PrevClassTemplate &&
998 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
999 SemanticContext->getRedeclContext()))) {
1000 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1001 Diag(Shadow->getTargetDecl()->getLocation(),
1002 diag::note_using_decl_target);
1003 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1004 // Recover by ignoring the old declaration.
1005 PrevDecl = PrevClassTemplate = nullptr;
1009 if (PrevClassTemplate) {
1010 // Ensure that the template parameter lists are compatible. Skip this check
1011 // for a friend in a dependent context: the template parameter list itself
1012 // could be dependent.
1013 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1014 !TemplateParameterListsAreEqual(TemplateParams,
1015 PrevClassTemplate->getTemplateParameters(),
1020 // C++ [temp.class]p4:
1021 // In a redeclaration, partial specialization, explicit
1022 // specialization or explicit instantiation of a class template,
1023 // the class-key shall agree in kind with the original class
1024 // template declaration (7.1.5.3).
1025 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
1026 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
1027 TUK == TUK_Definition, KWLoc, Name)) {
1028 Diag(KWLoc, diag::err_use_with_wrong_tag)
1030 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
1031 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
1032 Kind = PrevRecordDecl->getTagKind();
1035 // Check for redefinition of this class template.
1036 if (TUK == TUK_Definition) {
1037 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
1038 // If we have a prior definition that is not visible, treat this as
1039 // simply making that previous definition visible.
1040 NamedDecl *Hidden = nullptr;
1041 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
1042 SkipBody->ShouldSkip = true;
1043 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1044 assert(Tmpl && "original definition of a class template is not a "
1046 makeMergedDefinitionVisible(Hidden, KWLoc);
1047 makeMergedDefinitionVisible(Tmpl, KWLoc);
1051 Diag(NameLoc, diag::err_redefinition) << Name;
1052 Diag(Def->getLocation(), diag::note_previous_definition);
1053 // FIXME: Would it make sense to try to "forget" the previous
1054 // definition, as part of error recovery?
1058 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
1059 // Maybe we will complain about the shadowed template parameter.
1060 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1061 // Just pretend that we didn't see the previous declaration.
1063 } else if (PrevDecl) {
1065 // A class template shall not have the same name as any other
1066 // template, class, function, object, enumeration, enumerator,
1067 // namespace, or type in the same scope (3.3), except as specified
1069 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1070 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1074 // Check the template parameter list of this declaration, possibly
1075 // merging in the template parameter list from the previous class
1076 // template declaration. Skip this check for a friend in a dependent
1077 // context, because the template parameter list might be dependent.
1078 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1079 CheckTemplateParameterList(
1081 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1083 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1084 SemanticContext->isDependentContext())
1085 ? TPC_ClassTemplateMember
1086 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1087 : TPC_ClassTemplate))
1091 // If the name of the template was qualified, we must be defining the
1092 // template out-of-line.
1093 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1094 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
1095 : diag::err_member_decl_does_not_match)
1096 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
1101 CXXRecordDecl *NewClass =
1102 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
1104 PrevClassTemplate->getTemplatedDecl() : nullptr,
1105 /*DelayTypeCreation=*/true);
1106 SetNestedNameSpecifier(NewClass, SS);
1107 if (NumOuterTemplateParamLists > 0)
1108 NewClass->setTemplateParameterListsInfo(
1109 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1110 NumOuterTemplateParamLists));
1112 // Add alignment attributes if necessary; these attributes are checked when
1113 // the ASTContext lays out the structure.
1114 if (TUK == TUK_Definition) {
1115 AddAlignmentAttributesForRecord(NewClass);
1116 AddMsStructLayoutForRecord(NewClass);
1119 ClassTemplateDecl *NewTemplate
1120 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1121 DeclarationName(Name), TemplateParams,
1122 NewClass, PrevClassTemplate);
1123 NewClass->setDescribedClassTemplate(NewTemplate);
1125 if (ModulePrivateLoc.isValid())
1126 NewTemplate->setModulePrivate();
1128 // Build the type for the class template declaration now.
1129 QualType T = NewTemplate->getInjectedClassNameSpecialization();
1130 T = Context.getInjectedClassNameType(NewClass, T);
1131 assert(T->isDependentType() && "Class template type is not dependent?");
1134 // If we are providing an explicit specialization of a member that is a
1135 // class template, make a note of that.
1136 if (PrevClassTemplate &&
1137 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1138 PrevClassTemplate->setMemberSpecialization();
1140 // Set the access specifier.
1141 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
1142 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
1144 // Set the lexical context of these templates
1145 NewClass->setLexicalDeclContext(CurContext);
1146 NewTemplate->setLexicalDeclContext(CurContext);
1148 if (TUK == TUK_Definition)
1149 NewClass->startDefinition();
1152 ProcessDeclAttributeList(S, NewClass, Attr);
1154 if (PrevClassTemplate)
1155 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1157 AddPushedVisibilityAttribute(NewClass);
1159 if (TUK != TUK_Friend) {
1160 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1162 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1163 Outer = Outer->getParent();
1164 PushOnScopeChains(NewTemplate, Outer);
1166 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
1167 NewTemplate->setAccess(PrevClassTemplate->getAccess());
1168 NewClass->setAccess(PrevClassTemplate->getAccess());
1171 NewTemplate->setObjectOfFriendDecl();
1173 // Friend templates are visible in fairly strange ways.
1174 if (!CurContext->isDependentContext()) {
1175 DeclContext *DC = SemanticContext->getRedeclContext();
1176 DC->makeDeclVisibleInContext(NewTemplate);
1177 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1178 PushOnScopeChains(NewTemplate, EnclosingScope,
1179 /* AddToContext = */ false);
1182 FriendDecl *Friend = FriendDecl::Create(
1183 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
1184 Friend->setAccess(AS_public);
1185 CurContext->addDecl(Friend);
1189 NewTemplate->setInvalidDecl();
1190 NewClass->setInvalidDecl();
1193 ActOnDocumentableDecl(NewTemplate);
1198 /// \brief Diagnose the presence of a default template argument on a
1199 /// template parameter, which is ill-formed in certain contexts.
1201 /// \returns true if the default template argument should be dropped.
1202 static bool DiagnoseDefaultTemplateArgument(Sema &S,
1203 Sema::TemplateParamListContext TPC,
1204 SourceLocation ParamLoc,
1205 SourceRange DefArgRange) {
1207 case Sema::TPC_ClassTemplate:
1208 case Sema::TPC_VarTemplate:
1209 case Sema::TPC_TypeAliasTemplate:
1212 case Sema::TPC_FunctionTemplate:
1213 case Sema::TPC_FriendFunctionTemplateDefinition:
1214 // C++ [temp.param]p9:
1215 // A default template-argument shall not be specified in a
1216 // function template declaration or a function template
1218 // If a friend function template declaration specifies a default
1219 // template-argument, that declaration shall be a definition and shall be
1220 // the only declaration of the function template in the translation unit.
1221 // (C++98/03 doesn't have this wording; see DR226).
1222 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
1223 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1224 : diag::ext_template_parameter_default_in_function_template)
1228 case Sema::TPC_ClassTemplateMember:
1229 // C++0x [temp.param]p9:
1230 // A default template-argument shall not be specified in the
1231 // template-parameter-lists of the definition of a member of a
1232 // class template that appears outside of the member's class.
1233 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1237 case Sema::TPC_FriendClassTemplate:
1238 case Sema::TPC_FriendFunctionTemplate:
1239 // C++ [temp.param]p9:
1240 // A default template-argument shall not be specified in a
1241 // friend template declaration.
1242 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1246 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1247 // for friend function templates if there is only a single
1248 // declaration (and it is a definition). Strange!
1251 llvm_unreachable("Invalid TemplateParamListContext!");
1254 /// \brief Check for unexpanded parameter packs within the template parameters
1255 /// of a template template parameter, recursively.
1256 static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1257 TemplateTemplateParmDecl *TTP) {
1258 // A template template parameter which is a parameter pack is also a pack
1260 if (TTP->isParameterPack())
1263 TemplateParameterList *Params = TTP->getTemplateParameters();
1264 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1265 NamedDecl *P = Params->getParam(I);
1266 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
1267 if (!NTTP->isParameterPack() &&
1268 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
1269 NTTP->getTypeSourceInfo(),
1270 Sema::UPPC_NonTypeTemplateParameterType))
1276 if (TemplateTemplateParmDecl *InnerTTP
1277 = dyn_cast<TemplateTemplateParmDecl>(P))
1278 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1285 /// \brief Checks the validity of a template parameter list, possibly
1286 /// considering the template parameter list from a previous
1289 /// If an "old" template parameter list is provided, it must be
1290 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
1291 /// template parameter list.
1293 /// \param NewParams Template parameter list for a new template
1294 /// declaration. This template parameter list will be updated with any
1295 /// default arguments that are carried through from the previous
1296 /// template parameter list.
1298 /// \param OldParams If provided, template parameter list from a
1299 /// previous declaration of the same template. Default template
1300 /// arguments will be merged from the old template parameter list to
1301 /// the new template parameter list.
1303 /// \param TPC Describes the context in which we are checking the given
1304 /// template parameter list.
1306 /// \returns true if an error occurred, false otherwise.
1307 bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
1308 TemplateParameterList *OldParams,
1309 TemplateParamListContext TPC) {
1310 bool Invalid = false;
1312 // C++ [temp.param]p10:
1313 // The set of default template-arguments available for use with a
1314 // template declaration or definition is obtained by merging the
1315 // default arguments from the definition (if in scope) and all
1316 // declarations in scope in the same way default function
1317 // arguments are (8.3.6).
1318 bool SawDefaultArgument = false;
1319 SourceLocation PreviousDefaultArgLoc;
1321 // Dummy initialization to avoid warnings.
1322 TemplateParameterList::iterator OldParam = NewParams->end();
1324 OldParam = OldParams->begin();
1326 bool RemoveDefaultArguments = false;
1327 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1328 NewParamEnd = NewParams->end();
1329 NewParam != NewParamEnd; ++NewParam) {
1330 // Variables used to diagnose redundant default arguments
1331 bool RedundantDefaultArg = false;
1332 SourceLocation OldDefaultLoc;
1333 SourceLocation NewDefaultLoc;
1335 // Variable used to diagnose missing default arguments
1336 bool MissingDefaultArg = false;
1338 // Variable used to diagnose non-final parameter packs
1339 bool SawParameterPack = false;
1341 if (TemplateTypeParmDecl *NewTypeParm
1342 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
1343 // Check the presence of a default argument here.
1344 if (NewTypeParm->hasDefaultArgument() &&
1345 DiagnoseDefaultTemplateArgument(*this, TPC,
1346 NewTypeParm->getLocation(),
1347 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1349 NewTypeParm->removeDefaultArgument();
1351 // Merge default arguments for template type parameters.
1352 TemplateTypeParmDecl *OldTypeParm
1353 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
1354 if (NewTypeParm->isParameterPack()) {
1355 assert(!NewTypeParm->hasDefaultArgument() &&
1356 "Parameter packs can't have a default argument!");
1357 SawParameterPack = true;
1358 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
1359 NewTypeParm->hasDefaultArgument()) {
1360 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1361 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1362 SawDefaultArgument = true;
1363 RedundantDefaultArg = true;
1364 PreviousDefaultArgLoc = NewDefaultLoc;
1365 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1366 // Merge the default argument from the old declaration to the
1368 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
1369 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1370 } else if (NewTypeParm->hasDefaultArgument()) {
1371 SawDefaultArgument = true;
1372 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1373 } else if (SawDefaultArgument)
1374 MissingDefaultArg = true;
1375 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
1376 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
1377 // Check for unexpanded parameter packs.
1378 if (!NewNonTypeParm->isParameterPack() &&
1379 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
1380 NewNonTypeParm->getTypeSourceInfo(),
1381 UPPC_NonTypeTemplateParameterType)) {
1386 // Check the presence of a default argument here.
1387 if (NewNonTypeParm->hasDefaultArgument() &&
1388 DiagnoseDefaultTemplateArgument(*this, TPC,
1389 NewNonTypeParm->getLocation(),
1390 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1391 NewNonTypeParm->removeDefaultArgument();
1394 // Merge default arguments for non-type template parameters
1395 NonTypeTemplateParmDecl *OldNonTypeParm
1396 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
1397 if (NewNonTypeParm->isParameterPack()) {
1398 assert(!NewNonTypeParm->hasDefaultArgument() &&
1399 "Parameter packs can't have a default argument!");
1400 if (!NewNonTypeParm->isPackExpansion())
1401 SawParameterPack = true;
1402 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
1403 NewNonTypeParm->hasDefaultArgument()) {
1404 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1405 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1406 SawDefaultArgument = true;
1407 RedundantDefaultArg = true;
1408 PreviousDefaultArgLoc = NewDefaultLoc;
1409 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1410 // Merge the default argument from the old declaration to the
1412 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
1413 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1414 } else if (NewNonTypeParm->hasDefaultArgument()) {
1415 SawDefaultArgument = true;
1416 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1417 } else if (SawDefaultArgument)
1418 MissingDefaultArg = true;
1420 TemplateTemplateParmDecl *NewTemplateParm
1421 = cast<TemplateTemplateParmDecl>(*NewParam);
1423 // Check for unexpanded parameter packs, recursively.
1424 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
1429 // Check the presence of a default argument here.
1430 if (NewTemplateParm->hasDefaultArgument() &&
1431 DiagnoseDefaultTemplateArgument(*this, TPC,
1432 NewTemplateParm->getLocation(),
1433 NewTemplateParm->getDefaultArgument().getSourceRange()))
1434 NewTemplateParm->removeDefaultArgument();
1436 // Merge default arguments for template template parameters
1437 TemplateTemplateParmDecl *OldTemplateParm
1438 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
1439 if (NewTemplateParm->isParameterPack()) {
1440 assert(!NewTemplateParm->hasDefaultArgument() &&
1441 "Parameter packs can't have a default argument!");
1442 if (!NewTemplateParm->isPackExpansion())
1443 SawParameterPack = true;
1444 } else if (OldTemplateParm &&
1445 hasVisibleDefaultArgument(OldTemplateParm) &&
1446 NewTemplateParm->hasDefaultArgument()) {
1447 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1448 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
1449 SawDefaultArgument = true;
1450 RedundantDefaultArg = true;
1451 PreviousDefaultArgLoc = NewDefaultLoc;
1452 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1453 // Merge the default argument from the old declaration to the
1455 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
1456 PreviousDefaultArgLoc
1457 = OldTemplateParm->getDefaultArgument().getLocation();
1458 } else if (NewTemplateParm->hasDefaultArgument()) {
1459 SawDefaultArgument = true;
1460 PreviousDefaultArgLoc
1461 = NewTemplateParm->getDefaultArgument().getLocation();
1462 } else if (SawDefaultArgument)
1463 MissingDefaultArg = true;
1466 // C++11 [temp.param]p11:
1467 // If a template parameter of a primary class template or alias template
1468 // is a template parameter pack, it shall be the last template parameter.
1469 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
1470 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
1471 TPC == TPC_TypeAliasTemplate)) {
1472 Diag((*NewParam)->getLocation(),
1473 diag::err_template_param_pack_must_be_last_template_parameter);
1477 if (RedundantDefaultArg) {
1478 // C++ [temp.param]p12:
1479 // A template-parameter shall not be given default arguments
1480 // by two different declarations in the same scope.
1481 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1482 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1484 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
1485 // C++ [temp.param]p11:
1486 // If a template-parameter of a class template has a default
1487 // template-argument, each subsequent template-parameter shall either
1488 // have a default template-argument supplied or be a template parameter
1490 Diag((*NewParam)->getLocation(),
1491 diag::err_template_param_default_arg_missing);
1492 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1494 RemoveDefaultArguments = true;
1497 // If we have an old template parameter list that we're merging
1498 // in, move on to the next parameter.
1503 // We were missing some default arguments at the end of the list, so remove
1504 // all of the default arguments.
1505 if (RemoveDefaultArguments) {
1506 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1507 NewParamEnd = NewParams->end();
1508 NewParam != NewParamEnd; ++NewParam) {
1509 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1510 TTP->removeDefaultArgument();
1511 else if (NonTypeTemplateParmDecl *NTTP
1512 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1513 NTTP->removeDefaultArgument();
1515 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1524 /// A class which looks for a use of a certain level of template
1526 struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1527 typedef RecursiveASTVisitor<DependencyChecker> super;
1531 SourceLocation MatchLoc;
1533 DependencyChecker(unsigned Depth) : Depth(Depth), Match(false) {}
1535 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1536 NamedDecl *ND = Params->getParam(0);
1537 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1538 Depth = PD->getDepth();
1539 } else if (NonTypeTemplateParmDecl *PD =
1540 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1541 Depth = PD->getDepth();
1543 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1547 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
1548 if (ParmDepth >= Depth) {
1556 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1557 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
1560 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1561 return !Matches(T->getDepth());
1564 bool TraverseTemplateName(TemplateName N) {
1565 if (TemplateTemplateParmDecl *PD =
1566 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
1567 if (Matches(PD->getDepth()))
1569 return super::TraverseTemplateName(N);
1572 bool VisitDeclRefExpr(DeclRefExpr *E) {
1573 if (NonTypeTemplateParmDecl *PD =
1574 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
1575 if (Matches(PD->getDepth(), E->getExprLoc()))
1577 return super::VisitDeclRefExpr(E);
1580 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1581 return TraverseType(T->getReplacementType());
1585 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
1586 return TraverseTemplateArgument(T->getArgumentPack());
1589 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1590 return TraverseType(T->getInjectedSpecializationType());
1593 } // end anonymous namespace
1595 /// Determines whether a given type depends on the given parameter
1598 DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
1599 DependencyChecker Checker(Params);
1600 Checker.TraverseType(T);
1601 return Checker.Match;
1604 // Find the source range corresponding to the named type in the given
1605 // nested-name-specifier, if any.
1606 static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
1608 const CXXScopeSpec &SS) {
1609 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
1610 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1611 if (const Type *CurType = NNS->getAsType()) {
1612 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1613 return NNSLoc.getTypeLoc().getSourceRange();
1617 NNSLoc = NNSLoc.getPrefix();
1620 return SourceRange();
1623 /// \brief Match the given template parameter lists to the given scope
1624 /// specifier, returning the template parameter list that applies to the
1627 /// \param DeclStartLoc the start of the declaration that has a scope
1628 /// specifier or a template parameter list.
1630 /// \param DeclLoc The location of the declaration itself.
1632 /// \param SS the scope specifier that will be matched to the given template
1633 /// parameter lists. This scope specifier precedes a qualified name that is
1636 /// \param TemplateId The template-id following the scope specifier, if there
1637 /// is one. Used to check for a missing 'template<>'.
1639 /// \param ParamLists the template parameter lists, from the outermost to the
1640 /// innermost template parameter lists.
1642 /// \param IsFriend Whether to apply the slightly different rules for
1643 /// matching template parameters to scope specifiers in friend
1646 /// \param IsExplicitSpecialization will be set true if the entity being
1647 /// declared is an explicit specialization, false otherwise.
1649 /// \returns the template parameter list, if any, that corresponds to the
1650 /// name that is preceded by the scope specifier @p SS. This template
1651 /// parameter list may have template parameters (if we're declaring a
1652 /// template) or may have no template parameters (if we're declaring a
1653 /// template specialization), or may be NULL (if what we're declaring isn't
1654 /// itself a template).
1655 TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
1656 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
1657 TemplateIdAnnotation *TemplateId,
1658 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
1659 bool &IsExplicitSpecialization, bool &Invalid) {
1660 IsExplicitSpecialization = false;
1663 // The sequence of nested types to which we will match up the template
1664 // parameter lists. We first build this list by starting with the type named
1665 // by the nested-name-specifier and walking out until we run out of types.
1666 SmallVector<QualType, 4> NestedTypes;
1668 if (SS.getScopeRep()) {
1669 if (CXXRecordDecl *Record
1670 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1671 T = Context.getTypeDeclType(Record);
1673 T = QualType(SS.getScopeRep()->getAsType(), 0);
1676 // If we found an explicit specialization that prevents us from needing
1677 // 'template<>' headers, this will be set to the location of that
1678 // explicit specialization.
1679 SourceLocation ExplicitSpecLoc;
1681 while (!T.isNull()) {
1682 NestedTypes.push_back(T);
1684 // Retrieve the parent of a record type.
1685 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1686 // If this type is an explicit specialization, we're done.
1687 if (ClassTemplateSpecializationDecl *Spec
1688 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1689 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
1690 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1691 ExplicitSpecLoc = Spec->getLocation();
1694 } else if (Record->getTemplateSpecializationKind()
1695 == TSK_ExplicitSpecialization) {
1696 ExplicitSpecLoc = Record->getLocation();
1700 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1701 T = Context.getTypeDeclType(Parent);
1707 if (const TemplateSpecializationType *TST
1708 = T->getAs<TemplateSpecializationType>()) {
1709 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1710 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1711 T = Context.getTypeDeclType(Parent);
1718 // Look one step prior in a dependent template specialization type.
1719 if (const DependentTemplateSpecializationType *DependentTST
1720 = T->getAs<DependentTemplateSpecializationType>()) {
1721 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1722 T = QualType(NNS->getAsType(), 0);
1728 // Look one step prior in a dependent name type.
1729 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1730 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1731 T = QualType(NNS->getAsType(), 0);
1737 // Retrieve the parent of an enumeration type.
1738 if (const EnumType *EnumT = T->getAs<EnumType>()) {
1739 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1741 EnumDecl *Enum = EnumT->getDecl();
1743 // Get to the parent type.
1744 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1745 T = Context.getTypeDeclType(Parent);
1753 // Reverse the nested types list, since we want to traverse from the outermost
1754 // to the innermost while checking template-parameter-lists.
1755 std::reverse(NestedTypes.begin(), NestedTypes.end());
1757 // C++0x [temp.expl.spec]p17:
1758 // A member or a member template may be nested within many
1759 // enclosing class templates. In an explicit specialization for
1760 // such a member, the member declaration shall be preceded by a
1761 // template<> for each enclosing class template that is
1762 // explicitly specialized.
1763 bool SawNonEmptyTemplateParameterList = false;
1765 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
1766 if (SawNonEmptyTemplateParameterList) {
1767 Diag(DeclLoc, diag::err_specialize_member_of_template)
1768 << !Recovery << Range;
1770 IsExplicitSpecialization = false;
1777 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
1778 // Check that we can have an explicit specialization here.
1779 if (CheckExplicitSpecialization(Range, true))
1782 // We don't have a template header, but we should.
1783 SourceLocation ExpectedTemplateLoc;
1784 if (!ParamLists.empty())
1785 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
1787 ExpectedTemplateLoc = DeclStartLoc;
1789 Diag(DeclLoc, diag::err_template_spec_needs_header)
1791 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
1795 unsigned ParamIdx = 0;
1796 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
1798 T = NestedTypes[TypeIdx];
1800 // Whether we expect a 'template<>' header.
1801 bool NeedEmptyTemplateHeader = false;
1803 // Whether we expect a template header with parameters.
1804 bool NeedNonemptyTemplateHeader = false;
1806 // For a dependent type, the set of template parameters that we
1808 TemplateParameterList *ExpectedTemplateParams = nullptr;
1810 // C++0x [temp.expl.spec]p15:
1811 // A member or a member template may be nested within many enclosing
1812 // class templates. In an explicit specialization for such a member, the
1813 // member declaration shall be preceded by a template<> for each
1814 // enclosing class template that is explicitly specialized.
1815 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1816 if (ClassTemplatePartialSpecializationDecl *Partial
1817 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1818 ExpectedTemplateParams = Partial->getTemplateParameters();
1819 NeedNonemptyTemplateHeader = true;
1820 } else if (Record->isDependentType()) {
1821 if (Record->getDescribedClassTemplate()) {
1822 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1823 ->getTemplateParameters();
1824 NeedNonemptyTemplateHeader = true;
1826 } else if (ClassTemplateSpecializationDecl *Spec
1827 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1828 // C++0x [temp.expl.spec]p4:
1829 // Members of an explicitly specialized class template are defined
1830 // in the same manner as members of normal classes, and not using
1831 // the template<> syntax.
1832 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
1833 NeedEmptyTemplateHeader = true;
1836 } else if (Record->getTemplateSpecializationKind()) {
1837 if (Record->getTemplateSpecializationKind()
1838 != TSK_ExplicitSpecialization &&
1839 TypeIdx == NumTypes - 1)
1840 IsExplicitSpecialization = true;
1844 } else if (const TemplateSpecializationType *TST
1845 = T->getAs<TemplateSpecializationType>()) {
1846 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1847 ExpectedTemplateParams = Template->getTemplateParameters();
1848 NeedNonemptyTemplateHeader = true;
1850 } else if (T->getAs<DependentTemplateSpecializationType>()) {
1851 // FIXME: We actually could/should check the template arguments here
1852 // against the corresponding template parameter list.
1853 NeedNonemptyTemplateHeader = false;
1856 // C++ [temp.expl.spec]p16:
1857 // In an explicit specialization declaration for a member of a class
1858 // template or a member template that ap- pears in namespace scope, the
1859 // member template and some of its enclosing class templates may remain
1860 // unspecialized, except that the declaration shall not explicitly
1861 // specialize a class member template if its en- closing class templates
1862 // are not explicitly specialized as well.
1863 if (ParamIdx < ParamLists.size()) {
1864 if (ParamLists[ParamIdx]->size() == 0) {
1865 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1869 SawNonEmptyTemplateParameterList = true;
1872 if (NeedEmptyTemplateHeader) {
1873 // If we're on the last of the types, and we need a 'template<>' header
1874 // here, then it's an explicit specialization.
1875 if (TypeIdx == NumTypes - 1)
1876 IsExplicitSpecialization = true;
1878 if (ParamIdx < ParamLists.size()) {
1879 if (ParamLists[ParamIdx]->size() > 0) {
1880 // The header has template parameters when it shouldn't. Complain.
1881 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1882 diag::err_template_param_list_matches_nontemplate)
1884 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
1885 ParamLists[ParamIdx]->getRAngleLoc())
1886 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1891 // Consume this template header.
1897 if (DiagnoseMissingExplicitSpecialization(
1898 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
1904 if (NeedNonemptyTemplateHeader) {
1905 // In friend declarations we can have template-ids which don't
1906 // depend on the corresponding template parameter lists. But
1907 // assume that empty parameter lists are supposed to match this
1909 if (IsFriend && T->isDependentType()) {
1910 if (ParamIdx < ParamLists.size() &&
1911 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
1912 ExpectedTemplateParams = nullptr;
1917 if (ParamIdx < ParamLists.size()) {
1918 // Check the template parameter list, if we can.
1919 if (ExpectedTemplateParams &&
1920 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
1921 ExpectedTemplateParams,
1922 true, TPL_TemplateMatch))
1926 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
1927 TPC_ClassTemplateMember))
1934 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
1936 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1942 // If there were at least as many template-ids as there were template
1943 // parameter lists, then there are no template parameter lists remaining for
1944 // the declaration itself.
1945 if (ParamIdx >= ParamLists.size()) {
1946 if (TemplateId && !IsFriend) {
1947 // We don't have a template header for the declaration itself, but we
1949 IsExplicitSpecialization = true;
1950 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
1951 TemplateId->RAngleLoc));
1953 // Fabricate an empty template parameter list for the invented header.
1954 return TemplateParameterList::Create(Context, SourceLocation(),
1955 SourceLocation(), None,
1962 // If there were too many template parameter lists, complain about that now.
1963 if (ParamIdx < ParamLists.size() - 1) {
1964 bool HasAnyExplicitSpecHeader = false;
1965 bool AllExplicitSpecHeaders = true;
1966 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
1967 if (ParamLists[I]->size() == 0)
1968 HasAnyExplicitSpecHeader = true;
1970 AllExplicitSpecHeaders = false;
1973 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1974 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
1975 : diag::err_template_spec_extra_headers)
1976 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1977 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
1979 // If there was a specialization somewhere, such that 'template<>' is
1980 // not required, and there were any 'template<>' headers, note where the
1981 // specialization occurred.
1982 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
1983 Diag(ExplicitSpecLoc,
1984 diag::note_explicit_template_spec_does_not_need_header)
1985 << NestedTypes.back();
1987 // We have a template parameter list with no corresponding scope, which
1988 // means that the resulting template declaration can't be instantiated
1989 // properly (we'll end up with dependent nodes when we shouldn't).
1990 if (!AllExplicitSpecHeaders)
1994 // C++ [temp.expl.spec]p16:
1995 // In an explicit specialization declaration for a member of a class
1996 // template or a member template that ap- pears in namespace scope, the
1997 // member template and some of its enclosing class templates may remain
1998 // unspecialized, except that the declaration shall not explicitly
1999 // specialize a class member template if its en- closing class templates
2000 // are not explicitly specialized as well.
2001 if (ParamLists.back()->size() == 0 &&
2002 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2006 // Return the last template parameter list, which corresponds to the
2007 // entity being declared.
2008 return ParamLists.back();
2011 void Sema::NoteAllFoundTemplates(TemplateName Name) {
2012 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2013 Diag(Template->getLocation(), diag::note_template_declared_here)
2014 << (isa<FunctionTemplateDecl>(Template)
2016 : isa<ClassTemplateDecl>(Template)
2018 : isa<VarTemplateDecl>(Template)
2020 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2021 << Template->getDeclName();
2025 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
2026 for (OverloadedTemplateStorage::iterator I = OST->begin(),
2029 Diag((*I)->getLocation(), diag::note_template_declared_here)
2030 << 0 << (*I)->getDeclName();
2037 checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
2038 const SmallVectorImpl<TemplateArgument> &Converted,
2039 SourceLocation TemplateLoc,
2040 TemplateArgumentListInfo &TemplateArgs) {
2041 ASTContext &Context = SemaRef.getASTContext();
2042 switch (BTD->getBuiltinTemplateKind()) {
2043 case BTK__make_integer_seq:
2044 // Specializations of __make_integer_seq<S, T, N> are treated like
2045 // S<T, 0, ..., N-1>.
2047 // C++14 [inteseq.intseq]p1:
2048 // T shall be an integer type.
2049 if (!Converted[1].getAsType()->isIntegralType(Context)) {
2050 SemaRef.Diag(TemplateArgs[1].getLocation(),
2051 diag::err_integer_sequence_integral_element_type);
2055 // C++14 [inteseq.make]p1:
2056 // If N is negative the program is ill-formed.
2057 TemplateArgument NumArgsArg = Converted[2];
2058 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2060 SemaRef.Diag(TemplateArgs[2].getLocation(),
2061 diag::err_integer_sequence_negative_length);
2065 QualType ArgTy = NumArgsArg.getIntegralType();
2066 TemplateArgumentListInfo SyntheticTemplateArgs;
2067 // The type argument gets reused as the first template argument in the
2068 // synthetic template argument list.
2069 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2070 // Expand N into 0 ... N-1.
2071 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2073 TemplateArgument TA(Context, I, ArgTy);
2074 Expr *E = SemaRef.BuildExpressionFromIntegralTemplateArgument(
2075 TA, TemplateArgs[2].getLocation())
2077 SyntheticTemplateArgs.addArgument(
2078 TemplateArgumentLoc(TemplateArgument(E), E));
2080 // The first template argument will be reused as the template decl that
2081 // our synthetic template arguments will be applied to.
2082 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2083 TemplateLoc, SyntheticTemplateArgs);
2085 llvm_unreachable("unexpected BuiltinTemplateDecl!");
2088 QualType Sema::CheckTemplateIdType(TemplateName Name,
2089 SourceLocation TemplateLoc,
2090 TemplateArgumentListInfo &TemplateArgs) {
2091 DependentTemplateName *DTN
2092 = Name.getUnderlying().getAsDependentTemplateName();
2093 if (DTN && DTN->isIdentifier())
2094 // When building a template-id where the template-name is dependent,
2095 // assume the template is a type template. Either our assumption is
2096 // correct, or the code is ill-formed and will be diagnosed when the
2097 // dependent name is substituted.
2098 return Context.getDependentTemplateSpecializationType(ETK_None,
2099 DTN->getQualifier(),
2100 DTN->getIdentifier(),
2103 TemplateDecl *Template = Name.getAsTemplateDecl();
2104 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2105 isa<VarTemplateDecl>(Template)) {
2106 // We might have a substituted template template parameter pack. If so,
2107 // build a template specialization type for it.
2108 if (Name.getAsSubstTemplateTemplateParmPack())
2109 return Context.getTemplateSpecializationType(Name, TemplateArgs);
2111 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2113 NoteAllFoundTemplates(Name);
2117 // Check that the template argument list is well-formed for this
2119 SmallVector<TemplateArgument, 4> Converted;
2120 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
2126 bool InstantiationDependent = false;
2127 if (TypeAliasTemplateDecl *AliasTemplate =
2128 dyn_cast<TypeAliasTemplateDecl>(Template)) {
2129 // Find the canonical type for this type alias template specialization.
2130 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2131 if (Pattern->isInvalidDecl())
2134 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2135 Converted.data(), Converted.size());
2137 // Only substitute for the innermost template argument list.
2138 MultiLevelTemplateArgumentList TemplateArgLists;
2139 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
2140 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2141 for (unsigned I = 0; I < Depth; ++I)
2142 TemplateArgLists.addOuterTemplateArguments(None);
2144 LocalInstantiationScope Scope(*this);
2145 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
2146 if (Inst.isInvalid())
2149 CanonType = SubstType(Pattern->getUnderlyingType(),
2150 TemplateArgLists, AliasTemplate->getLocation(),
2151 AliasTemplate->getDeclName());
2152 if (CanonType.isNull())
2154 } else if (Name.isDependent() ||
2155 TemplateSpecializationType::anyDependentTemplateArguments(
2156 TemplateArgs, InstantiationDependent)) {
2157 // This class template specialization is a dependent
2158 // type. Therefore, its canonical type is another class template
2159 // specialization type that contains all of the converted
2160 // arguments in canonical form. This ensures that, e.g., A<T> and
2161 // A<T, T> have identical types when A is declared as:
2163 // template<typename T, typename U = T> struct A;
2164 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
2165 CanonType = Context.getTemplateSpecializationType(CanonName,
2169 // FIXME: CanonType is not actually the canonical type, and unfortunately
2170 // it is a TemplateSpecializationType that we will never use again.
2171 // In the future, we need to teach getTemplateSpecializationType to only
2172 // build the canonical type and return that to us.
2173 CanonType = Context.getCanonicalType(CanonType);
2175 // This might work out to be a current instantiation, in which
2176 // case the canonical type needs to be the InjectedClassNameType.
2178 // TODO: in theory this could be a simple hashtable lookup; most
2179 // changes to CurContext don't change the set of current
2181 if (isa<ClassTemplateDecl>(Template)) {
2182 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2183 // If we get out to a namespace, we're done.
2184 if (Ctx->isFileContext()) break;
2186 // If this isn't a record, keep looking.
2187 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2188 if (!Record) continue;
2190 // Look for one of the two cases with InjectedClassNameTypes
2191 // and check whether it's the same template.
2192 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2193 !Record->getDescribedClassTemplate())
2196 // Fetch the injected class name type and check whether its
2197 // injected type is equal to the type we just built.
2198 QualType ICNT = Context.getTypeDeclType(Record);
2199 QualType Injected = cast<InjectedClassNameType>(ICNT)
2200 ->getInjectedSpecializationType();
2202 if (CanonType != Injected->getCanonicalTypeInternal())
2205 // If so, the canonical type of this TST is the injected
2206 // class name type of the record we just found.
2207 assert(ICNT.isCanonical());
2212 } else if (ClassTemplateDecl *ClassTemplate
2213 = dyn_cast<ClassTemplateDecl>(Template)) {
2214 // Find the class template specialization declaration that
2215 // corresponds to these arguments.
2216 void *InsertPos = nullptr;
2217 ClassTemplateSpecializationDecl *Decl
2218 = ClassTemplate->findSpecialization(Converted, InsertPos);
2220 // This is the first time we have referenced this class template
2221 // specialization. Create the canonical declaration and add it to
2222 // the set of specializations.
2223 Decl = ClassTemplateSpecializationDecl::Create(Context,
2224 ClassTemplate->getTemplatedDecl()->getTagKind(),
2225 ClassTemplate->getDeclContext(),
2226 ClassTemplate->getTemplatedDecl()->getLocStart(),
2227 ClassTemplate->getLocation(),
2230 Converted.size(), nullptr);
2231 ClassTemplate->AddSpecialization(Decl, InsertPos);
2232 if (ClassTemplate->isOutOfLine())
2233 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
2236 // Diagnose uses of this specialization.
2237 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2239 CanonType = Context.getTypeDeclType(Decl);
2240 assert(isa<RecordType>(CanonType) &&
2241 "type of non-dependent specialization is not a RecordType");
2242 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
2243 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
2247 // Build the fully-sugared type for this class template
2248 // specialization, which refers back to the class template
2249 // specialization we created or found.
2250 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
2254 Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
2255 TemplateTy TemplateD, SourceLocation TemplateLoc,
2256 SourceLocation LAngleLoc,
2257 ASTTemplateArgsPtr TemplateArgsIn,
2258 SourceLocation RAngleLoc,
2259 bool IsCtorOrDtorName) {
2263 TemplateName Template = TemplateD.get();
2265 // Translate the parser's template argument list in our AST format.
2266 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2267 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2269 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2271 = Context.getDependentTemplateSpecializationType(ETK_None,
2272 DTN->getQualifier(),
2273 DTN->getIdentifier(),
2275 // Build type-source information.
2277 DependentTemplateSpecializationTypeLoc SpecTL
2278 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2279 SpecTL.setElaboratedKeywordLoc(SourceLocation());
2280 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
2281 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2282 SpecTL.setTemplateNameLoc(TemplateLoc);
2283 SpecTL.setLAngleLoc(LAngleLoc);
2284 SpecTL.setRAngleLoc(RAngleLoc);
2285 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2286 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2287 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2290 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2292 if (Result.isNull())
2295 // Build type-source information.
2297 TemplateSpecializationTypeLoc SpecTL
2298 = TLB.push<TemplateSpecializationTypeLoc>(Result);
2299 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2300 SpecTL.setTemplateNameLoc(TemplateLoc);
2301 SpecTL.setLAngleLoc(LAngleLoc);
2302 SpecTL.setRAngleLoc(RAngleLoc);
2303 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2304 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
2306 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2307 // constructor or destructor name (in such a case, the scope specifier
2308 // will be attached to the enclosing Decl or Expr node).
2309 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
2310 // Create an elaborated-type-specifier containing the nested-name-specifier.
2311 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2312 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
2313 ElabTL.setElaboratedKeywordLoc(SourceLocation());
2314 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2317 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
2320 TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
2321 TypeSpecifierType TagSpec,
2322 SourceLocation TagLoc,
2324 SourceLocation TemplateKWLoc,
2325 TemplateTy TemplateD,
2326 SourceLocation TemplateLoc,
2327 SourceLocation LAngleLoc,
2328 ASTTemplateArgsPtr TemplateArgsIn,
2329 SourceLocation RAngleLoc) {
2330 TemplateName Template = TemplateD.get();
2332 // Translate the parser's template argument list in our AST format.
2333 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2334 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2336 // Determine the tag kind
2337 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
2338 ElaboratedTypeKeyword Keyword
2339 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
2341 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2342 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
2343 DTN->getQualifier(),
2344 DTN->getIdentifier(),
2347 // Build type-source information.
2349 DependentTemplateSpecializationTypeLoc SpecTL
2350 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2351 SpecTL.setElaboratedKeywordLoc(TagLoc);
2352 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
2353 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2354 SpecTL.setTemplateNameLoc(TemplateLoc);
2355 SpecTL.setLAngleLoc(LAngleLoc);
2356 SpecTL.setRAngleLoc(RAngleLoc);
2357 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2358 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2359 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2362 if (TypeAliasTemplateDecl *TAT =
2363 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2364 // C++0x [dcl.type.elab]p2:
2365 // If the identifier resolves to a typedef-name or the simple-template-id
2366 // resolves to an alias template specialization, the
2367 // elaborated-type-specifier is ill-formed.
2368 Diag(TemplateLoc, diag::err_tag_reference_non_tag) << 4;
2369 Diag(TAT->getLocation(), diag::note_declared_at);
2372 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2373 if (Result.isNull())
2374 return TypeResult(true);
2376 // Check the tag kind
2377 if (const RecordType *RT = Result->getAs<RecordType>()) {
2378 RecordDecl *D = RT->getDecl();
2380 IdentifierInfo *Id = D->getIdentifier();
2381 assert(Id && "templated class must have an identifier");
2383 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
2385 Diag(TagLoc, diag::err_use_with_wrong_tag)
2387 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
2388 Diag(D->getLocation(), diag::note_previous_use);
2392 // Provide source-location information for the template specialization.
2394 TemplateSpecializationTypeLoc SpecTL
2395 = TLB.push<TemplateSpecializationTypeLoc>(Result);
2396 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2397 SpecTL.setTemplateNameLoc(TemplateLoc);
2398 SpecTL.setLAngleLoc(LAngleLoc);
2399 SpecTL.setRAngleLoc(RAngleLoc);
2400 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2401 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
2403 // Construct an elaborated type containing the nested-name-specifier (if any)
2405 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2406 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
2407 ElabTL.setElaboratedKeywordLoc(TagLoc);
2408 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2409 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
2412 static bool CheckTemplatePartialSpecializationArgs(
2413 Sema &S, SourceLocation NameLoc, TemplateParameterList *TemplateParams,
2414 unsigned ExplicitArgs, SmallVectorImpl<TemplateArgument> &TemplateArgs);
2416 static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
2417 NamedDecl *PrevDecl,
2419 bool IsPartialSpecialization);
2421 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
2423 static bool isTemplateArgumentTemplateParameter(
2424 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
2425 switch (Arg.getKind()) {
2426 case TemplateArgument::Null:
2427 case TemplateArgument::NullPtr:
2428 case TemplateArgument::Integral:
2429 case TemplateArgument::Declaration:
2430 case TemplateArgument::Pack:
2431 case TemplateArgument::TemplateExpansion:
2434 case TemplateArgument::Type: {
2435 QualType Type = Arg.getAsType();
2436 const TemplateTypeParmType *TPT =
2437 Arg.getAsType()->getAs<TemplateTypeParmType>();
2438 return TPT && !Type.hasQualifiers() &&
2439 TPT->getDepth() == Depth && TPT->getIndex() == Index;
2442 case TemplateArgument::Expression: {
2443 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
2444 if (!DRE || !DRE->getDecl())
2446 const NonTypeTemplateParmDecl *NTTP =
2447 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2448 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
2451 case TemplateArgument::Template:
2452 const TemplateTemplateParmDecl *TTP =
2453 dyn_cast_or_null<TemplateTemplateParmDecl>(
2454 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
2455 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
2457 llvm_unreachable("unexpected kind of template argument");
2460 static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
2461 ArrayRef<TemplateArgument> Args) {
2462 if (Params->size() != Args.size())
2465 unsigned Depth = Params->getDepth();
2467 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2468 TemplateArgument Arg = Args[I];
2470 // If the parameter is a pack expansion, the argument must be a pack
2471 // whose only element is a pack expansion.
2472 if (Params->getParam(I)->isParameterPack()) {
2473 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
2474 !Arg.pack_begin()->isPackExpansion())
2476 Arg = Arg.pack_begin()->getPackExpansionPattern();
2479 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
2486 /// Convert the parser's template argument list representation into our form.
2487 static TemplateArgumentListInfo
2488 makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
2489 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
2490 TemplateId.RAngleLoc);
2491 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
2492 TemplateId.NumArgs);
2493 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
2494 return TemplateArgs;
2497 DeclResult Sema::ActOnVarTemplateSpecialization(
2498 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
2499 TemplateParameterList *TemplateParams, StorageClass SC,
2500 bool IsPartialSpecialization) {
2501 // D must be variable template id.
2502 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
2503 "Variable template specialization is declared with a template it.");
2505 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
2506 TemplateArgumentListInfo TemplateArgs =
2507 makeTemplateArgumentListInfo(*this, *TemplateId);
2508 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
2509 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
2510 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
2512 TemplateName Name = TemplateId->Template.get();
2514 // The template-id must name a variable template.
2515 VarTemplateDecl *VarTemplate =
2516 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
2518 NamedDecl *FnTemplate;
2519 if (auto *OTS = Name.getAsOverloadedTemplate())
2520 FnTemplate = *OTS->begin();
2522 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
2524 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
2525 << FnTemplate->getDeclName();
2526 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
2527 << IsPartialSpecialization;
2530 // Check for unexpanded parameter packs in any of the template arguments.
2531 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2532 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
2533 UPPC_PartialSpecialization))
2536 // Check that the template argument list is well-formed for this
2538 SmallVector<TemplateArgument, 4> Converted;
2539 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
2543 // Find the variable template (partial) specialization declaration that
2544 // corresponds to these arguments.
2545 if (IsPartialSpecialization) {
2546 if (CheckTemplatePartialSpecializationArgs(
2547 *this, TemplateNameLoc, VarTemplate->getTemplateParameters(),
2548 TemplateArgs.size(), Converted))
2551 bool InstantiationDependent;
2552 if (!Name.isDependent() &&
2553 !TemplateSpecializationType::anyDependentTemplateArguments(
2554 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
2555 InstantiationDependent)) {
2556 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
2557 << VarTemplate->getDeclName();
2558 IsPartialSpecialization = false;
2561 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
2563 // C++ [temp.class.spec]p9b3:
2565 // -- The argument list of the specialization shall not be identical
2566 // to the implicit argument list of the primary template.
2567 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2568 << /*variable template*/ 1
2569 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
2570 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
2571 // FIXME: Recover from this by treating the declaration as a redeclaration
2572 // of the primary template.
2577 void *InsertPos = nullptr;
2578 VarTemplateSpecializationDecl *PrevDecl = nullptr;
2580 if (IsPartialSpecialization)
2581 // FIXME: Template parameter list matters too
2582 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
2584 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
2586 VarTemplateSpecializationDecl *Specialization = nullptr;
2588 // Check whether we can declare a variable template specialization in
2589 // the current scope.
2590 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
2592 IsPartialSpecialization))
2595 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2596 // Since the only prior variable template specialization with these
2597 // arguments was referenced but not declared, reuse that
2598 // declaration node as our own, updating its source location and
2599 // the list of outer template parameters to reflect our new declaration.
2600 Specialization = PrevDecl;
2601 Specialization->setLocation(TemplateNameLoc);
2603 } else if (IsPartialSpecialization) {
2604 // Create a new class template partial specialization declaration node.
2605 VarTemplatePartialSpecializationDecl *PrevPartial =
2606 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
2607 VarTemplatePartialSpecializationDecl *Partial =
2608 VarTemplatePartialSpecializationDecl::Create(
2609 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
2610 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
2611 Converted.data(), Converted.size(), TemplateArgs);
2614 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
2615 Specialization = Partial;
2617 // If we are providing an explicit specialization of a member variable
2618 // template specialization, make a note of that.
2619 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
2620 PrevPartial->setMemberSpecialization();
2622 // Check that all of the template parameters of the variable template
2623 // partial specialization are deducible from the template
2624 // arguments. If not, this variable template partial specialization
2625 // will never be used.
2626 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
2627 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2628 TemplateParams->getDepth(), DeducibleParams);
2630 if (!DeducibleParams.all()) {
2631 unsigned NumNonDeducible =
2632 DeducibleParams.size() - DeducibleParams.count();
2633 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2634 << /*variable template*/ 1 << (NumNonDeducible > 1)
2635 << SourceRange(TemplateNameLoc, RAngleLoc);
2636 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2637 if (!DeducibleParams[I]) {
2638 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2639 if (Param->getDeclName())
2640 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2641 << Param->getDeclName();
2643 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2649 // Create a new class template specialization declaration node for
2650 // this explicit specialization or friend declaration.
2651 Specialization = VarTemplateSpecializationDecl::Create(
2652 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
2653 VarTemplate, DI->getType(), DI, SC, Converted.data(), Converted.size());
2654 Specialization->setTemplateArgsInfo(TemplateArgs);
2657 VarTemplate->AddSpecialization(Specialization, InsertPos);
2660 // C++ [temp.expl.spec]p6:
2661 // If a template, a member template or the member of a class template is
2662 // explicitly specialized then that specialization shall be declared
2663 // before the first use of that specialization that would cause an implicit
2664 // instantiation to take place, in every translation unit in which such a
2665 // use occurs; no diagnostic is required.
2666 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
2668 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
2669 // Is there any previous explicit specialization declaration?
2670 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
2677 SourceRange Range(TemplateNameLoc, RAngleLoc);
2678 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
2681 Diag(PrevDecl->getPointOfInstantiation(),
2682 diag::note_instantiation_required_here)
2683 << (PrevDecl->getTemplateSpecializationKind() !=
2684 TSK_ImplicitInstantiation);
2689 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
2690 Specialization->setLexicalDeclContext(CurContext);
2692 // Add the specialization into its lexical context, so that it can
2693 // be seen when iterating through the list of declarations in that
2694 // context. However, specializations are not found by name lookup.
2695 CurContext->addDecl(Specialization);
2697 // Note that this is an explicit specialization.
2698 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2701 // Check that this isn't a redefinition of this specialization,
2702 // merging with previous declarations.
2703 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
2705 PrevSpec.addDecl(PrevDecl);
2706 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
2707 } else if (Specialization->isStaticDataMember() &&
2708 Specialization->isOutOfLine()) {
2709 Specialization->setAccess(VarTemplate->getAccess());
2712 // Link instantiations of static data members back to the template from
2713 // which they were instantiated.
2714 if (Specialization->isStaticDataMember())
2715 Specialization->setInstantiationOfStaticDataMember(
2716 VarTemplate->getTemplatedDecl(),
2717 Specialization->getSpecializationKind());
2719 return Specialization;
2723 /// \brief A partial specialization whose template arguments have matched
2724 /// a given template-id.
2725 struct PartialSpecMatchResult {
2726 VarTemplatePartialSpecializationDecl *Partial;
2727 TemplateArgumentList *Args;
2729 } // end anonymous namespace
2732 Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
2733 SourceLocation TemplateNameLoc,
2734 const TemplateArgumentListInfo &TemplateArgs) {
2735 assert(Template && "A variable template id without template?");
2737 // Check that the template argument list is well-formed for this template.
2738 SmallVector<TemplateArgument, 4> Converted;
2739 if (CheckTemplateArgumentList(
2740 Template, TemplateNameLoc,
2741 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
2745 // Find the variable template specialization declaration that
2746 // corresponds to these arguments.
2747 void *InsertPos = nullptr;
2748 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
2749 Converted, InsertPos)) {
2750 checkSpecializationVisibility(TemplateNameLoc, Spec);
2751 // If we already have a variable template specialization, return it.
2755 // This is the first time we have referenced this variable template
2756 // specialization. Create the canonical declaration and add it to
2757 // the set of specializations, based on the closest partial specialization
2758 // that it represents. That is,
2759 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
2760 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
2761 Converted.data(), Converted.size());
2762 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
2763 bool AmbiguousPartialSpec = false;
2764 typedef PartialSpecMatchResult MatchResult;
2765 SmallVector<MatchResult, 4> Matched;
2766 SourceLocation PointOfInstantiation = TemplateNameLoc;
2767 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
2768 /*ForTakingAddress=*/false);
2770 // 1. Attempt to find the closest partial specialization that this
2771 // specializes, if any.
2772 // If any of the template arguments is dependent, then this is probably
2773 // a placeholder for an incomplete declarative context; which must be
2774 // complete by instantiation time. Thus, do not search through the partial
2775 // specializations yet.
2776 // TODO: Unify with InstantiateClassTemplateSpecialization()?
2777 // Perhaps better after unification of DeduceTemplateArguments() and
2778 // getMoreSpecializedPartialSpecialization().
2779 bool InstantiationDependent = false;
2780 if (!TemplateSpecializationType::anyDependentTemplateArguments(
2781 TemplateArgs, InstantiationDependent)) {
2783 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2784 Template->getPartialSpecializations(PartialSpecs);
2786 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2787 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2788 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2790 if (TemplateDeductionResult Result =
2791 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
2792 // Store the failed-deduction information for use in diagnostics, later.
2793 // TODO: Actually use the failed-deduction info?
2794 FailedCandidates.addCandidate().set(
2795 DeclAccessPair::make(Template, AS_public), Partial,
2796 MakeDeductionFailureInfo(Context, Result, Info));
2799 Matched.push_back(PartialSpecMatchResult());
2800 Matched.back().Partial = Partial;
2801 Matched.back().Args = Info.take();
2805 if (Matched.size() >= 1) {
2806 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
2807 if (Matched.size() == 1) {
2808 // -- If exactly one matching specialization is found, the
2809 // instantiation is generated from that specialization.
2810 // We don't need to do anything for this.
2812 // -- If more than one matching specialization is found, the
2813 // partial order rules (14.5.4.2) are used to determine
2814 // whether one of the specializations is more specialized
2815 // than the others. If none of the specializations is more
2816 // specialized than all of the other matching
2817 // specializations, then the use of the variable template is
2818 // ambiguous and the program is ill-formed.
2819 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
2820 PEnd = Matched.end();
2822 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2823 PointOfInstantiation) ==
2828 // Determine if the best partial specialization is more specialized than
2830 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2831 PEnd = Matched.end();
2833 if (P != Best && getMoreSpecializedPartialSpecialization(
2834 P->Partial, Best->Partial,
2835 PointOfInstantiation) != Best->Partial) {
2836 AmbiguousPartialSpec = true;
2842 // Instantiate using the best variable template partial specialization.
2843 InstantiationPattern = Best->Partial;
2844 InstantiationArgs = Best->Args;
2846 // -- If no match is found, the instantiation is generated
2847 // from the primary template.
2848 // InstantiationPattern = Template->getTemplatedDecl();
2852 // 2. Create the canonical declaration.
2853 // Note that we do not instantiate a definition until we see an odr-use
2854 // in DoMarkVarDeclReferenced().
2855 // FIXME: LateAttrs et al.?
2856 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
2857 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
2858 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
2862 if (AmbiguousPartialSpec) {
2863 // Partial ordering did not produce a clear winner. Complain.
2864 Decl->setInvalidDecl();
2865 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2868 // Print the matching partial specializations.
2869 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2870 PEnd = Matched.end();
2872 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2873 << getTemplateArgumentBindingsText(
2874 P->Partial->getTemplateParameters(), *P->Args);
2878 if (VarTemplatePartialSpecializationDecl *D =
2879 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
2880 Decl->setInstantiationOf(D, InstantiationArgs);
2882 checkSpecializationVisibility(TemplateNameLoc, Decl);
2884 assert(Decl && "No variable template specialization?");
2889 Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
2890 const DeclarationNameInfo &NameInfo,
2891 VarTemplateDecl *Template, SourceLocation TemplateLoc,
2892 const TemplateArgumentListInfo *TemplateArgs) {
2894 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
2896 if (Decl.isInvalid())
2899 VarDecl *Var = cast<VarDecl>(Decl.get());
2900 if (!Var->getTemplateSpecializationKind())
2901 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
2904 // Build an ordinary singleton decl ref.
2905 return BuildDeclarationNameExpr(SS, NameInfo, Var,
2906 /*FoundD=*/nullptr, TemplateArgs);
2909 ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
2910 SourceLocation TemplateKWLoc,
2913 const TemplateArgumentListInfo *TemplateArgs) {
2914 // FIXME: Can we do any checking at this point? I guess we could check the
2915 // template arguments that we have against the template name, if the template
2916 // name refers to a single template. That's not a terribly common case,
2918 // foo<int> could identify a single function unambiguously
2919 // This approach does NOT work, since f<int>(1);
2920 // gets resolved prior to resorting to overload resolution
2921 // i.e., template<class T> void f(double);
2922 // vs template<class T, class U> void f(U);
2924 // These should be filtered out by our callers.
2925 assert(!R.empty() && "empty lookup results when building templateid");
2926 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
2928 // In C++1y, check variable template ids.
2929 bool InstantiationDependent;
2930 if (R.getAsSingle<VarTemplateDecl>() &&
2931 !TemplateSpecializationType::anyDependentTemplateArguments(
2932 *TemplateArgs, InstantiationDependent)) {
2933 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
2934 R.getAsSingle<VarTemplateDecl>(),
2935 TemplateKWLoc, TemplateArgs);
2938 // We don't want lookup warnings at this point.
2939 R.suppressDiagnostics();
2941 UnresolvedLookupExpr *ULE
2942 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2943 SS.getWithLocInContext(Context),
2945 R.getLookupNameInfo(),
2946 RequiresADL, TemplateArgs,
2947 R.begin(), R.end());
2952 // We actually only call this from template instantiation.
2954 Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
2955 SourceLocation TemplateKWLoc,
2956 const DeclarationNameInfo &NameInfo,
2957 const TemplateArgumentListInfo *TemplateArgs) {
2959 assert(TemplateArgs || TemplateKWLoc.isValid());
2961 if (!(DC = computeDeclContext(SS, false)) ||
2962 DC->isDependentContext() ||
2963 RequireCompleteDeclContext(SS, DC))
2964 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
2966 bool MemberOfUnknownSpecialization;
2967 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2968 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
2969 MemberOfUnknownSpecialization);
2971 if (R.isAmbiguous())
2975 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
2976 << NameInfo.getName() << SS.getRange();
2980 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
2981 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
2983 << NameInfo.getName().getAsString() << SS.getRange();
2984 Diag(Temp->getLocation(), diag::note_referenced_class_template);
2988 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
2991 /// \brief Form a dependent template name.
2993 /// This action forms a dependent template name given the template
2994 /// name and its (presumably dependent) scope specifier. For
2995 /// example, given "MetaFun::template apply", the scope specifier \p
2996 /// SS will be "MetaFun::", \p TemplateKWLoc contains the location
2997 /// of the "template" keyword, and "apply" is the \p Name.
2998 TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
3000 SourceLocation TemplateKWLoc,
3001 UnqualifiedId &Name,
3002 ParsedType ObjectType,
3003 bool EnteringContext,
3004 TemplateTy &Result) {
3005 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
3007 getLangOpts().CPlusPlus11 ?
3008 diag::warn_cxx98_compat_template_outside_of_template :
3009 diag::ext_template_outside_of_template)
3010 << FixItHint::CreateRemoval(TemplateKWLoc);
3012 DeclContext *LookupCtx = nullptr;
3014 LookupCtx = computeDeclContext(SS, EnteringContext);
3015 if (!LookupCtx && ObjectType)
3016 LookupCtx = computeDeclContext(ObjectType.get());
3018 // C++0x [temp.names]p5:
3019 // If a name prefixed by the keyword template is not the name of
3020 // a template, the program is ill-formed. [Note: the keyword
3021 // template may not be applied to non-template members of class
3022 // templates. -end note ] [ Note: as is the case with the
3023 // typename prefix, the template prefix is allowed in cases
3024 // where it is not strictly necessary; i.e., when the
3025 // nested-name-specifier or the expression on the left of the ->
3026 // or . is not dependent on a template-parameter, or the use
3027 // does not appear in the scope of a template. -end note]
3029 // Note: C++03 was more strict here, because it banned the use of
3030 // the "template" keyword prior to a template-name that was not a
3031 // dependent name. C++ DR468 relaxed this requirement (the
3032 // "template" keyword is now permitted). We follow the C++0x
3033 // rules, even in C++03 mode with a warning, retroactively applying the DR.
3034 bool MemberOfUnknownSpecialization;
3035 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
3036 ObjectType, EnteringContext, Result,
3037 MemberOfUnknownSpecialization);
3038 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
3039 isa<CXXRecordDecl>(LookupCtx) &&
3040 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
3041 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
3042 // This is a dependent template. Handle it below.
3043 } else if (TNK == TNK_Non_template) {
3044 Diag(Name.getLocStart(),
3045 diag::err_template_kw_refers_to_non_template)
3046 << GetNameFromUnqualifiedId(Name).getName()
3047 << Name.getSourceRange()
3049 return TNK_Non_template;
3051 // We found something; return it.
3056 NestedNameSpecifier *Qualifier = SS.getScopeRep();
3058 switch (Name.getKind()) {
3059 case UnqualifiedId::IK_Identifier:
3060 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
3062 return TNK_Dependent_template_name;
3064 case UnqualifiedId::IK_OperatorFunctionId:
3065 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
3066 Name.OperatorFunctionId.Operator));
3067 return TNK_Function_template;
3069 case UnqualifiedId::IK_LiteralOperatorId:
3070 llvm_unreachable("literal operator id cannot have a dependent scope");
3076 Diag(Name.getLocStart(),
3077 diag::err_template_kw_refers_to_non_template)
3078 << GetNameFromUnqualifiedId(Name).getName()
3079 << Name.getSourceRange()
3081 return TNK_Non_template;
3084 bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
3085 TemplateArgumentLoc &AL,
3086 SmallVectorImpl<TemplateArgument> &Converted) {
3087 const TemplateArgument &Arg = AL.getArgument();
3089 TypeSourceInfo *TSI = nullptr;
3091 // Check template type parameter.
3092 switch(Arg.getKind()) {
3093 case TemplateArgument::Type:
3094 // C++ [temp.arg.type]p1:
3095 // A template-argument for a template-parameter which is a
3096 // type shall be a type-id.
3097 ArgType = Arg.getAsType();
3098 TSI = AL.getTypeSourceInfo();
3100 case TemplateArgument::Template: {
3101 // We have a template type parameter but the template argument
3102 // is a template without any arguments.
3103 SourceRange SR = AL.getSourceRange();
3104 TemplateName Name = Arg.getAsTemplate();
3105 Diag(SR.getBegin(), diag::err_template_missing_args)
3107 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3108 Diag(Decl->getLocation(), diag::note_template_decl_here);
3112 case TemplateArgument::Expression: {
3113 // We have a template type parameter but the template argument is an
3114 // expression; see if maybe it is missing the "typename" keyword.
3116 DeclarationNameInfo NameInfo;
3118 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3119 SS.Adopt(ArgExpr->getQualifierLoc());
3120 NameInfo = ArgExpr->getNameInfo();
3121 } else if (DependentScopeDeclRefExpr *ArgExpr =
3122 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3123 SS.Adopt(ArgExpr->getQualifierLoc());
3124 NameInfo = ArgExpr->getNameInfo();
3125 } else if (CXXDependentScopeMemberExpr *ArgExpr =
3126 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
3127 if (ArgExpr->isImplicitAccess()) {
3128 SS.Adopt(ArgExpr->getQualifierLoc());
3129 NameInfo = ArgExpr->getMemberNameInfo();
3133 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
3134 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3135 LookupParsedName(Result, CurScope, &SS);
3137 if (Result.getAsSingle<TypeDecl>() ||
3138 Result.getResultKind() ==
3139 LookupResult::NotFoundInCurrentInstantiation) {
3140 // Suggest that the user add 'typename' before the NNS.
3141 SourceLocation Loc = AL.getSourceRange().getBegin();
3142 Diag(Loc, getLangOpts().MSVCCompat
3143 ? diag::ext_ms_template_type_arg_missing_typename
3144 : diag::err_template_arg_must_be_type_suggest)
3145 << FixItHint::CreateInsertion(Loc, "typename ");
3146 Diag(Param->getLocation(), diag::note_template_param_here);
3148 // Recover by synthesizing a type using the location information that we
3151 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
3153 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
3154 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
3155 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3156 TL.setNameLoc(NameInfo.getLoc());
3157 TSI = TLB.getTypeSourceInfo(Context, ArgType);
3159 // Overwrite our input TemplateArgumentLoc so that we can recover
3161 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
3162 TemplateArgumentLocInfo(TSI));
3170 // We have a template type parameter but the template argument
3172 SourceRange SR = AL.getSourceRange();
3173 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
3174 Diag(Param->getLocation(), diag::note_template_param_here);
3180 if (CheckTemplateArgument(Param, TSI))
3183 // Add the converted template type argument.
3184 ArgType = Context.getCanonicalType(ArgType);
3187 // If an explicitly-specified template argument type is a lifetime type
3188 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
3189 if (getLangOpts().ObjCAutoRefCount &&
3190 ArgType->isObjCLifetimeType() &&
3191 !ArgType.getObjCLifetime()) {
3193 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
3194 ArgType = Context.getQualifiedType(ArgType, Qs);
3197 Converted.push_back(TemplateArgument(ArgType));
3201 /// \brief Substitute template arguments into the default template argument for
3202 /// the given template type parameter.
3204 /// \param SemaRef the semantic analysis object for which we are performing
3205 /// the substitution.
3207 /// \param Template the template that we are synthesizing template arguments
3210 /// \param TemplateLoc the location of the template name that started the
3211 /// template-id we are checking.
3213 /// \param RAngleLoc the location of the right angle bracket ('>') that
3214 /// terminates the template-id.
3216 /// \param Param the template template parameter whose default we are
3217 /// substituting into.
3219 /// \param Converted the list of template arguments provided for template
3220 /// parameters that precede \p Param in the template parameter list.
3221 /// \returns the substituted template argument, or NULL if an error occurred.
3222 static TypeSourceInfo *
3223 SubstDefaultTemplateArgument(Sema &SemaRef,
3224 TemplateDecl *Template,
3225 SourceLocation TemplateLoc,
3226 SourceLocation RAngleLoc,
3227 TemplateTypeParmDecl *Param,
3228 SmallVectorImpl<TemplateArgument> &Converted) {
3229 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
3231 // If the argument type is dependent, instantiate it now based
3232 // on the previously-computed template arguments.
3233 if (ArgType->getType()->isDependentType()) {
3234 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
3235 Template, Converted,
3236 SourceRange(TemplateLoc, RAngleLoc));
3237 if (Inst.isInvalid())
3240 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3241 Converted.data(), Converted.size());
3243 // Only substitute for the innermost template argument list.
3244 MultiLevelTemplateArgumentList TemplateArgLists;
3245 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3246 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3247 TemplateArgLists.addOuterTemplateArguments(None);
3249 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
3251 SemaRef.SubstType(ArgType, TemplateArgLists,
3252 Param->getDefaultArgumentLoc(), Param->getDeclName());
3258 /// \brief Substitute template arguments into the default template argument for
3259 /// the given non-type template parameter.
3261 /// \param SemaRef the semantic analysis object for which we are performing
3262 /// the substitution.
3264 /// \param Template the template that we are synthesizing template arguments
3267 /// \param TemplateLoc the location of the template name that started the
3268 /// template-id we are checking.
3270 /// \param RAngleLoc the location of the right angle bracket ('>') that
3271 /// terminates the template-id.
3273 /// \param Param the non-type template parameter whose default we are
3274 /// substituting into.
3276 /// \param Converted the list of template arguments provided for template
3277 /// parameters that precede \p Param in the template parameter list.
3279 /// \returns the substituted template argument, or NULL if an error occurred.
3281 SubstDefaultTemplateArgument(Sema &SemaRef,
3282 TemplateDecl *Template,
3283 SourceLocation TemplateLoc,
3284 SourceLocation RAngleLoc,
3285 NonTypeTemplateParmDecl *Param,
3286 SmallVectorImpl<TemplateArgument> &Converted) {
3287 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
3288 Template, Converted,
3289 SourceRange(TemplateLoc, RAngleLoc));
3290 if (Inst.isInvalid())
3293 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3294 Converted.data(), Converted.size());
3296 // Only substitute for the innermost template argument list.
3297 MultiLevelTemplateArgumentList TemplateArgLists;
3298 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3299 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3300 TemplateArgLists.addOuterTemplateArguments(None);
3302 EnterExpressionEvaluationContext ConstantEvaluated(SemaRef,
3303 Sema::ConstantEvaluated);
3304 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
3307 /// \brief Substitute template arguments into the default template argument for
3308 /// the given template template parameter.
3310 /// \param SemaRef the semantic analysis object for which we are performing
3311 /// the substitution.
3313 /// \param Template the template that we are synthesizing template arguments
3316 /// \param TemplateLoc the location of the template name that started the
3317 /// template-id we are checking.
3319 /// \param RAngleLoc the location of the right angle bracket ('>') that
3320 /// terminates the template-id.
3322 /// \param Param the template template parameter whose default we are
3323 /// substituting into.
3325 /// \param Converted the list of template arguments provided for template
3326 /// parameters that precede \p Param in the template parameter list.
3328 /// \param QualifierLoc Will be set to the nested-name-specifier (with
3329 /// source-location information) that precedes the template name.
3331 /// \returns the substituted template argument, or NULL if an error occurred.
3333 SubstDefaultTemplateArgument(Sema &SemaRef,
3334 TemplateDecl *Template,
3335 SourceLocation TemplateLoc,
3336 SourceLocation RAngleLoc,
3337 TemplateTemplateParmDecl *Param,
3338 SmallVectorImpl<TemplateArgument> &Converted,
3339 NestedNameSpecifierLoc &QualifierLoc) {
3340 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Template, Converted,
3341 SourceRange(TemplateLoc, RAngleLoc));
3342 if (Inst.isInvalid())
3343 return TemplateName();
3345 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3346 Converted.data(), Converted.size());
3348 // Only substitute for the innermost template argument list.
3349 MultiLevelTemplateArgumentList TemplateArgLists;
3350 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3351 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3352 TemplateArgLists.addOuterTemplateArguments(None);
3354 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
3355 // Substitute into the nested-name-specifier first,
3356 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
3359 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
3361 return TemplateName();
3364 return SemaRef.SubstTemplateName(
3366 Param->getDefaultArgument().getArgument().getAsTemplate(),
3367 Param->getDefaultArgument().getTemplateNameLoc(),
3371 /// \brief If the given template parameter has a default template
3372 /// argument, substitute into that default template argument and
3373 /// return the corresponding template argument.
3375 Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
3376 SourceLocation TemplateLoc,
3377 SourceLocation RAngleLoc,
3379 SmallVectorImpl<TemplateArgument>
3381 bool &HasDefaultArg) {
3382 HasDefaultArg = false;
3384 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
3385 if (!hasVisibleDefaultArgument(TypeParm))
3386 return TemplateArgumentLoc();
3388 HasDefaultArg = true;
3389 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
3395 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3397 return TemplateArgumentLoc();
3400 if (NonTypeTemplateParmDecl *NonTypeParm
3401 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3402 if (!hasVisibleDefaultArgument(NonTypeParm))
3403 return TemplateArgumentLoc();
3405 HasDefaultArg = true;
3406 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
3411 if (Arg.isInvalid())
3412 return TemplateArgumentLoc();
3414 Expr *ArgE = Arg.getAs<Expr>();
3415 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
3418 TemplateTemplateParmDecl *TempTempParm
3419 = cast<TemplateTemplateParmDecl>(Param);
3420 if (!hasVisibleDefaultArgument(TempTempParm))
3421 return TemplateArgumentLoc();
3423 HasDefaultArg = true;
3424 NestedNameSpecifierLoc QualifierLoc;
3425 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
3432 return TemplateArgumentLoc();
3434 return TemplateArgumentLoc(TemplateArgument(TName),
3435 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
3436 TempTempParm->getDefaultArgument().getTemplateNameLoc());
3439 /// \brief Check that the given template argument corresponds to the given
3440 /// template parameter.
3442 /// \param Param The template parameter against which the argument will be
3445 /// \param Arg The template argument, which may be updated due to conversions.
3447 /// \param Template The template in which the template argument resides.
3449 /// \param TemplateLoc The location of the template name for the template
3450 /// whose argument list we're matching.
3452 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
3453 /// the template argument list.
3455 /// \param ArgumentPackIndex The index into the argument pack where this
3456 /// argument will be placed. Only valid if the parameter is a parameter pack.
3458 /// \param Converted The checked, converted argument will be added to the
3459 /// end of this small vector.
3461 /// \param CTAK Describes how we arrived at this particular template argument:
3462 /// explicitly written, deduced, etc.
3464 /// \returns true on error, false otherwise.
3465 bool Sema::CheckTemplateArgument(NamedDecl *Param,
3466 TemplateArgumentLoc &Arg,
3467 NamedDecl *Template,
3468 SourceLocation TemplateLoc,
3469 SourceLocation RAngleLoc,
3470 unsigned ArgumentPackIndex,
3471 SmallVectorImpl<TemplateArgument> &Converted,
3472 CheckTemplateArgumentKind CTAK) {
3473 // Check template type parameters.
3474 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3475 return CheckTemplateTypeArgument(TTP, Arg, Converted);
3477 // Check non-type template parameters.
3478 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3479 // Do substitution on the type of the non-type template parameter
3480 // with the template arguments we've seen thus far. But if the
3481 // template has a dependent context then we cannot substitute yet.
3482 QualType NTTPType = NTTP->getType();
3483 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
3484 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
3486 if (NTTPType->isDependentType() &&
3487 !isa<TemplateTemplateParmDecl>(Template) &&
3488 !Template->getDeclContext()->isDependentContext()) {
3489 // Do substitution on the type of the non-type template parameter.
3490 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
3492 SourceRange(TemplateLoc, RAngleLoc));
3493 if (Inst.isInvalid())
3496 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3497 Converted.data(), Converted.size());
3498 NTTPType = SubstType(NTTPType,
3499 MultiLevelTemplateArgumentList(TemplateArgs),
3500 NTTP->getLocation(),
3501 NTTP->getDeclName());
3502 // If that worked, check the non-type template parameter type
3504 if (!NTTPType.isNull())
3505 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
3506 NTTP->getLocation());
3507 if (NTTPType.isNull())
3511 switch (Arg.getArgument().getKind()) {
3512 case TemplateArgument::Null:
3513 llvm_unreachable("Should never see a NULL template argument here");
3515 case TemplateArgument::Expression: {
3516 TemplateArgument Result;
3518 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
3520 if (Res.isInvalid())
3523 // If the resulting expression is new, then use it in place of the
3524 // old expression in the template argument.
3525 if (Res.get() != Arg.getArgument().getAsExpr()) {
3526 TemplateArgument TA(Res.get());
3527 Arg = TemplateArgumentLoc(TA, Res.get());
3530 Converted.push_back(Result);
3534 case TemplateArgument::Declaration:
3535 case TemplateArgument::Integral:
3536 case TemplateArgument::NullPtr:
3537 // We've already checked this template argument, so just copy
3538 // it to the list of converted arguments.
3539 Converted.push_back(Arg.getArgument());
3542 case TemplateArgument::Template:
3543 case TemplateArgument::TemplateExpansion:
3544 // We were given a template template argument. It may not be ill-formed;
3546 if (DependentTemplateName *DTN
3547 = Arg.getArgument().getAsTemplateOrTemplatePattern()
3548 .getAsDependentTemplateName()) {
3549 // We have a template argument such as \c T::template X, which we
3550 // parsed as a template template argument. However, since we now
3551 // know that we need a non-type template argument, convert this
3552 // template name into an expression.
3554 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
3555 Arg.getTemplateNameLoc());
3558 SS.Adopt(Arg.getTemplateQualifierLoc());
3559 // FIXME: the template-template arg was a DependentTemplateName,
3560 // so it was provided with a template keyword. However, its source
3561 // location is not stored in the template argument structure.
3562 SourceLocation TemplateKWLoc;
3563 ExprResult E = DependentScopeDeclRefExpr::Create(
3564 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
3567 // If we parsed the template argument as a pack expansion, create a
3568 // pack expansion expression.
3569 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
3570 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
3575 TemplateArgument Result;
3576 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
3580 Converted.push_back(Result);
3584 // We have a template argument that actually does refer to a class
3585 // template, alias template, or template template parameter, and
3586 // therefore cannot be a non-type template argument.
3587 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
3588 << Arg.getSourceRange();
3590 Diag(Param->getLocation(), diag::note_template_param_here);
3593 case TemplateArgument::Type: {
3594 // We have a non-type template parameter but the template
3595 // argument is a type.
3597 // C++ [temp.arg]p2:
3598 // In a template-argument, an ambiguity between a type-id and
3599 // an expression is resolved to a type-id, regardless of the
3600 // form of the corresponding template-parameter.
3602 // We warn specifically about this case, since it can be rather
3603 // confusing for users.
3604 QualType T = Arg.getArgument().getAsType();
3605 SourceRange SR = Arg.getSourceRange();
3606 if (T->isFunctionType())
3607 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
3609 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
3610 Diag(Param->getLocation(), diag::note_template_param_here);
3614 case TemplateArgument::Pack:
3615 llvm_unreachable("Caller must expand template argument packs");
3622 // Check template template parameters.
3623 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
3625 // Substitute into the template parameter list of the template
3626 // template parameter, since previously-supplied template arguments
3627 // may appear within the template template parameter.
3629 // Set up a template instantiation context.
3630 LocalInstantiationScope Scope(*this);
3631 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
3632 TempParm, Converted,
3633 SourceRange(TemplateLoc, RAngleLoc));
3634 if (Inst.isInvalid())
3637 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3638 Converted.data(), Converted.size());
3639 TempParm = cast_or_null<TemplateTemplateParmDecl>(
3640 SubstDecl(TempParm, CurContext,
3641 MultiLevelTemplateArgumentList(TemplateArgs)));
3646 switch (Arg.getArgument().getKind()) {
3647 case TemplateArgument::Null:
3648 llvm_unreachable("Should never see a NULL template argument here");
3650 case TemplateArgument::Template:
3651 case TemplateArgument::TemplateExpansion:
3652 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
3655 Converted.push_back(Arg.getArgument());
3658 case TemplateArgument::Expression:
3659 case TemplateArgument::Type:
3660 // We have a template template parameter but the template
3661 // argument does not refer to a template.
3662 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
3663 << getLangOpts().CPlusPlus11;
3666 case TemplateArgument::Declaration:
3667 llvm_unreachable("Declaration argument with template template parameter");
3668 case TemplateArgument::Integral:
3669 llvm_unreachable("Integral argument with template template parameter");
3670 case TemplateArgument::NullPtr:
3671 llvm_unreachable("Null pointer argument with template template parameter");
3673 case TemplateArgument::Pack:
3674 llvm_unreachable("Caller must expand template argument packs");
3680 /// \brief Diagnose an arity mismatch in the
3681 static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
3682 SourceLocation TemplateLoc,
3683 TemplateArgumentListInfo &TemplateArgs) {
3684 TemplateParameterList *Params = Template->getTemplateParameters();
3685 unsigned NumParams = Params->size();
3686 unsigned NumArgs = TemplateArgs.size();
3689 if (NumArgs > NumParams)
3690 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
3691 TemplateArgs.getRAngleLoc());
3692 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3693 << (NumArgs > NumParams)
3694 << (isa<ClassTemplateDecl>(Template)? 0 :
3695 isa<FunctionTemplateDecl>(Template)? 1 :
3696 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3697 << Template << Range;
3698 S.Diag(Template->getLocation(), diag::note_template_decl_here)
3699 << Params->getSourceRange();
3703 /// \brief Check whether the template parameter is a pack expansion, and if so,
3704 /// determine the number of parameters produced by that expansion. For instance:
3707 /// template<typename ...Ts> struct A {
3708 /// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
3712 /// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
3713 /// is not a pack expansion, so returns an empty Optional.
3714 static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
3715 if (NonTypeTemplateParmDecl *NTTP
3716 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3717 if (NTTP->isExpandedParameterPack())
3718 return NTTP->getNumExpansionTypes();
3721 if (TemplateTemplateParmDecl *TTP
3722 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3723 if (TTP->isExpandedParameterPack())
3724 return TTP->getNumExpansionTemplateParameters();
3730 /// Diagnose a missing template argument.
3731 template<typename TemplateParmDecl>
3732 static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
3734 const TemplateParmDecl *D,
3735 TemplateArgumentListInfo &Args) {
3736 // Dig out the most recent declaration of the template parameter; there may be
3737 // declarations of the template that are more recent than TD.
3738 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
3739 ->getTemplateParameters()
3740 ->getParam(D->getIndex()));
3742 // If there's a default argument that's not visible, diagnose that we're
3743 // missing a module import.
3744 llvm::SmallVector<Module*, 8> Modules;
3745 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
3746 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
3747 D->getDefaultArgumentLoc(), Modules,
3748 Sema::MissingImportKind::DefaultArgument,
3753 // FIXME: If there's a more recent default argument that *is* visible,
3754 // diagnose that it was declared too late.
3756 return diagnoseArityMismatch(S, TD, Loc, Args);
3759 /// \brief Check that the given template argument list is well-formed
3760 /// for specializing the given template.
3761 bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
3762 SourceLocation TemplateLoc,
3763 TemplateArgumentListInfo &TemplateArgs,
3764 bool PartialTemplateArgs,
3765 SmallVectorImpl<TemplateArgument> &Converted) {
3766 // Make a copy of the template arguments for processing. Only make the
3767 // changes at the end when successful in matching the arguments to the
3769 TemplateArgumentListInfo NewArgs = TemplateArgs;
3771 TemplateParameterList *Params = Template->getTemplateParameters();
3773 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
3775 // C++ [temp.arg]p1:
3776 // [...] The type and form of each template-argument specified in
3777 // a template-id shall match the type and form specified for the
3778 // corresponding parameter declared by the template in its
3779 // template-parameter-list.
3780 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
3781 SmallVector<TemplateArgument, 2> ArgumentPack;
3782 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
3783 LocalInstantiationScope InstScope(*this, true);
3784 for (TemplateParameterList::iterator Param = Params->begin(),
3785 ParamEnd = Params->end();
3786 Param != ParamEnd; /* increment in loop */) {
3787 // If we have an expanded parameter pack, make sure we don't have too
3789 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
3790 if (*Expansions == ArgumentPack.size()) {
3791 // We're done with this parameter pack. Pack up its arguments and add
3792 // them to the list.
3793 Converted.push_back(
3794 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
3795 ArgumentPack.clear();
3797 // This argument is assigned to the next parameter.
3800 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
3801 // Not enough arguments for this parameter pack.
3802 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3804 << (isa<ClassTemplateDecl>(Template)? 0 :
3805 isa<FunctionTemplateDecl>(Template)? 1 :
3806 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3808 Diag(Template->getLocation(), diag::note_template_decl_here)
3809 << Params->getSourceRange();
3814 if (ArgIdx < NumArgs) {
3815 // Check the template argument we were given.
3816 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
3817 TemplateLoc, RAngleLoc,
3818 ArgumentPack.size(), Converted))
3821 bool PackExpansionIntoNonPack =
3822 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
3823 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
3824 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
3825 // Core issue 1430: we have a pack expansion as an argument to an
3826 // alias template, and it's not part of a parameter pack. This
3827 // can't be canonicalized, so reject it now.
3828 Diag(NewArgs[ArgIdx].getLocation(),
3829 diag::err_alias_template_expansion_into_fixed_list)
3830 << NewArgs[ArgIdx].getSourceRange();
3831 Diag((*Param)->getLocation(), diag::note_template_param_here);
3835 // We're now done with this argument.
3838 if ((*Param)->isTemplateParameterPack()) {
3839 // The template parameter was a template parameter pack, so take the
3840 // deduced argument and place it on the argument pack. Note that we
3841 // stay on the same template parameter so that we can deduce more
3843 ArgumentPack.push_back(Converted.pop_back_val());
3845 // Move to the next template parameter.
3849 // If we just saw a pack expansion into a non-pack, then directly convert
3850 // the remaining arguments, because we don't know what parameters they'll
3852 if (PackExpansionIntoNonPack) {
3853 if (!ArgumentPack.empty()) {
3854 // If we were part way through filling in an expanded parameter pack,
3855 // fall back to just producing individual arguments.
3856 Converted.insert(Converted.end(),
3857 ArgumentPack.begin(), ArgumentPack.end());
3858 ArgumentPack.clear();
3861 while (ArgIdx < NumArgs) {
3862 Converted.push_back(NewArgs[ArgIdx].getArgument());
3872 // If we're checking a partial template argument list, we're done.
3873 if (PartialTemplateArgs) {
3874 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
3875 Converted.push_back(
3876 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
3881 // If we have a template parameter pack with no more corresponding
3882 // arguments, just break out now and we'll fill in the argument pack below.
3883 if ((*Param)->isTemplateParameterPack()) {
3884 assert(!getExpandedPackSize(*Param) &&
3885 "Should have dealt with this already");
3887 // A non-expanded parameter pack before the end of the parameter list
3888 // only occurs for an ill-formed template parameter list, unless we've
3889 // got a partial argument list for a function template, so just bail out.
3890 if (Param + 1 != ParamEnd)
3893 Converted.push_back(
3894 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
3895 ArgumentPack.clear();
3901 // Check whether we have a default argument.
3902 TemplateArgumentLoc Arg;
3904 // Retrieve the default template argument from the template
3905 // parameter. For each kind of template parameter, we substitute the
3906 // template arguments provided thus far and any "outer" template arguments
3907 // (when the template parameter was part of a nested template) into
3908 // the default argument.
3909 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
3910 if (!hasVisibleDefaultArgument(TTP))
3911 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
3914 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
3923 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
3925 } else if (NonTypeTemplateParmDecl *NTTP
3926 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
3927 if (!hasVisibleDefaultArgument(NTTP))
3928 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
3931 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
3939 Expr *Ex = E.getAs<Expr>();
3940 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
3942 TemplateTemplateParmDecl *TempParm
3943 = cast<TemplateTemplateParmDecl>(*Param);
3945 if (!hasVisibleDefaultArgument(TempParm))
3946 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
3949 NestedNameSpecifierLoc QualifierLoc;
3950 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
3959 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
3960 TempParm->getDefaultArgument().getTemplateNameLoc());
3963 // Introduce an instantiation record that describes where we are using
3964 // the default template argument.
3965 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
3966 SourceRange(TemplateLoc, RAngleLoc));
3967 if (Inst.isInvalid())
3970 // Check the default template argument.
3971 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
3972 RAngleLoc, 0, Converted))
3975 // Core issue 150 (assumed resolution): if this is a template template
3976 // parameter, keep track of the default template arguments from the
3977 // template definition.
3978 if (isTemplateTemplateParameter)
3979 NewArgs.addArgument(Arg);
3981 // Move to the next template parameter and argument.
3986 // If we're performing a partial argument substitution, allow any trailing
3987 // pack expansions; they might be empty. This can happen even if
3988 // PartialTemplateArgs is false (the list of arguments is complete but
3989 // still dependent).
3990 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
3991 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
3992 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
3993 Converted.push_back(NewArgs[ArgIdx++].getArgument());
3996 // If we have any leftover arguments, then there were too many arguments.
3997 // Complain and fail.
3998 if (ArgIdx < NumArgs)
3999 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
4001 // No problems found with the new argument list, propagate changes back
4003 TemplateArgs = std::move(NewArgs);
4009 class UnnamedLocalNoLinkageFinder
4010 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
4015 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
4018 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
4020 bool Visit(QualType T) {
4021 return inherited::Visit(T.getTypePtr());
4024 #define TYPE(Class, Parent) \
4025 bool Visit##Class##Type(const Class##Type *);
4026 #define ABSTRACT_TYPE(Class, Parent) \
4027 bool Visit##Class##Type(const Class##Type *) { return false; }
4028 #define NON_CANONICAL_TYPE(Class, Parent) \
4029 bool Visit##Class##Type(const Class##Type *) { return false; }
4030 #include "clang/AST/TypeNodes.def"
4032 bool VisitTagDecl(const TagDecl *Tag);
4033 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
4035 } // end anonymous namespace
4037 bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
4041 bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
4042 return Visit(T->getElementType());
4045 bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
4046 return Visit(T->getPointeeType());
4049 bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
4050 const BlockPointerType* T) {
4051 return Visit(T->getPointeeType());
4054 bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
4055 const LValueReferenceType* T) {
4056 return Visit(T->getPointeeType());
4059 bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
4060 const RValueReferenceType* T) {
4061 return Visit(T->getPointeeType());
4064 bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
4065 const MemberPointerType* T) {
4066 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
4069 bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
4070 const ConstantArrayType* T) {
4071 return Visit(T->getElementType());
4074 bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
4075 const IncompleteArrayType* T) {
4076 return Visit(T->getElementType());
4079 bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
4080 const VariableArrayType* T) {
4081 return Visit(T->getElementType());
4084 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
4085 const DependentSizedArrayType* T) {
4086 return Visit(T->getElementType());
4089 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
4090 const DependentSizedExtVectorType* T) {
4091 return Visit(T->getElementType());
4094 bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
4095 return Visit(T->getElementType());
4098 bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
4099 return Visit(T->getElementType());
4102 bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
4103 const FunctionProtoType* T) {
4104 for (const auto &A : T->param_types()) {
4109 return Visit(T->getReturnType());
4112 bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
4113 const FunctionNoProtoType* T) {
4114 return Visit(T->getReturnType());
4117 bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
4118 const UnresolvedUsingType*) {
4122 bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
4126 bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
4127 return Visit(T->getUnderlyingType());
4130 bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
4134 bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
4135 const UnaryTransformType*) {
4139 bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
4140 return Visit(T->getDeducedType());
4143 bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
4144 return VisitTagDecl(T->getDecl());
4147 bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
4148 return VisitTagDecl(T->getDecl());
4151 bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
4152 const TemplateTypeParmType*) {
4156 bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
4157 const SubstTemplateTypeParmPackType *) {
4161 bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
4162 const TemplateSpecializationType*) {
4166 bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
4167 const InjectedClassNameType* T) {
4168 return VisitTagDecl(T->getDecl());
4171 bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
4172 const DependentNameType* T) {
4173 return VisitNestedNameSpecifier(T->getQualifier());
4176 bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
4177 const DependentTemplateSpecializationType* T) {
4178 return VisitNestedNameSpecifier(T->getQualifier());
4181 bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
4182 const PackExpansionType* T) {
4183 return Visit(T->getPattern());
4186 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
4190 bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
4191 const ObjCInterfaceType *) {
4195 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
4196 const ObjCObjectPointerType *) {
4200 bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
4201 return Visit(T->getValueType());
4204 bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
4208 bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
4209 if (Tag->getDeclContext()->isFunctionOrMethod()) {
4210 S.Diag(SR.getBegin(),
4211 S.getLangOpts().CPlusPlus11 ?
4212 diag::warn_cxx98_compat_template_arg_local_type :
4213 diag::ext_template_arg_local_type)
4214 << S.Context.getTypeDeclType(Tag) << SR;
4218 if (!Tag->hasNameForLinkage()) {
4219 S.Diag(SR.getBegin(),
4220 S.getLangOpts().CPlusPlus11 ?
4221 diag::warn_cxx98_compat_template_arg_unnamed_type :
4222 diag::ext_template_arg_unnamed_type) << SR;
4223 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
4230 bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
4231 NestedNameSpecifier *NNS) {
4232 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
4235 switch (NNS->getKind()) {
4236 case NestedNameSpecifier::Identifier:
4237 case NestedNameSpecifier::Namespace:
4238 case NestedNameSpecifier::NamespaceAlias:
4239 case NestedNameSpecifier::Global:
4240 case NestedNameSpecifier::Super:
4243 case NestedNameSpecifier::TypeSpec:
4244 case NestedNameSpecifier::TypeSpecWithTemplate:
4245 return Visit(QualType(NNS->getAsType(), 0));
4247 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
4250 /// \brief Check a template argument against its corresponding
4251 /// template type parameter.
4253 /// This routine implements the semantics of C++ [temp.arg.type]. It
4254 /// returns true if an error occurred, and false otherwise.
4255 bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
4256 TypeSourceInfo *ArgInfo) {
4257 assert(ArgInfo && "invalid TypeSourceInfo");
4258 QualType Arg = ArgInfo->getType();
4259 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
4261 if (Arg->isVariablyModifiedType()) {
4262 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
4263 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
4264 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
4267 // C++03 [temp.arg.type]p2:
4268 // A local type, a type with no linkage, an unnamed type or a type
4269 // compounded from any of these types shall not be used as a
4270 // template-argument for a template type-parameter.
4272 // C++11 allows these, and even in C++03 we allow them as an extension with
4275 if (LangOpts.CPlusPlus11)
4277 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_unnamed_type,
4279 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_local_type,
4282 NeedsCheck = Arg->hasUnnamedOrLocalType();
4285 UnnamedLocalNoLinkageFinder Finder(*this, SR);
4286 (void)Finder.Visit(Context.getCanonicalType(Arg));
4292 enum NullPointerValueKind {
4298 /// \brief Determine whether the given template argument is a null pointer
4299 /// value of the appropriate type.
4300 static NullPointerValueKind
4301 isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
4302 QualType ParamType, Expr *Arg) {
4303 if (Arg->isValueDependent() || Arg->isTypeDependent())
4304 return NPV_NotNullPointer;
4306 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
4308 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
4310 if (!S.getLangOpts().CPlusPlus11)
4311 return NPV_NotNullPointer;
4313 // Determine whether we have a constant expression.
4314 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
4315 if (ArgRV.isInvalid())
4319 Expr::EvalResult EvalResult;
4320 SmallVector<PartialDiagnosticAt, 8> Notes;
4321 EvalResult.Diag = &Notes;
4322 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
4323 EvalResult.HasSideEffects) {
4324 SourceLocation DiagLoc = Arg->getExprLoc();
4326 // If our only note is the usual "invalid subexpression" note, just point
4327 // the caret at its location rather than producing an essentially
4329 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
4330 diag::note_invalid_subexpr_in_const_expr) {
4331 DiagLoc = Notes[0].first;
4335 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
4336 << Arg->getType() << Arg->getSourceRange();
4337 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
4338 S.Diag(Notes[I].first, Notes[I].second);
4340 S.Diag(Param->getLocation(), diag::note_template_param_here);
4344 // C++11 [temp.arg.nontype]p1:
4345 // - an address constant expression of type std::nullptr_t
4346 if (Arg->getType()->isNullPtrType())
4347 return NPV_NullPointer;
4349 // - a constant expression that evaluates to a null pointer value (4.10); or
4350 // - a constant expression that evaluates to a null member pointer value
4352 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
4353 (EvalResult.Val.isMemberPointer() &&
4354 !EvalResult.Val.getMemberPointerDecl())) {
4355 // If our expression has an appropriate type, we've succeeded.
4356 bool ObjCLifetimeConversion;
4357 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
4358 S.IsQualificationConversion(Arg->getType(), ParamType, false,
4359 ObjCLifetimeConversion))
4360 return NPV_NullPointer;
4362 // The types didn't match, but we know we got a null pointer; complain,
4363 // then recover as if the types were correct.
4364 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
4365 << Arg->getType() << ParamType << Arg->getSourceRange();
4366 S.Diag(Param->getLocation(), diag::note_template_param_here);
4367 return NPV_NullPointer;
4370 // If we don't have a null pointer value, but we do have a NULL pointer
4371 // constant, suggest a cast to the appropriate type.
4372 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
4373 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
4374 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
4375 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
4376 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
4378 S.Diag(Param->getLocation(), diag::note_template_param_here);
4379 return NPV_NullPointer;
4382 // FIXME: If we ever want to support general, address-constant expressions
4383 // as non-type template arguments, we should return the ExprResult here to
4384 // be interpreted by the caller.
4385 return NPV_NotNullPointer;
4388 /// \brief Checks whether the given template argument is compatible with its
4389 /// template parameter.
4390 static bool CheckTemplateArgumentIsCompatibleWithParameter(
4391 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
4392 Expr *Arg, QualType ArgType) {
4393 bool ObjCLifetimeConversion;
4394 if (ParamType->isPointerType() &&
4395 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
4396 S.IsQualificationConversion(ArgType, ParamType, false,
4397 ObjCLifetimeConversion)) {
4398 // For pointer-to-object types, qualification conversions are
4401 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
4402 if (!ParamRef->getPointeeType()->isFunctionType()) {
4403 // C++ [temp.arg.nontype]p5b3:
4404 // For a non-type template-parameter of type reference to
4405 // object, no conversions apply. The type referred to by the
4406 // reference may be more cv-qualified than the (otherwise
4407 // identical) type of the template- argument. The
4408 // template-parameter is bound directly to the
4409 // template-argument, which shall be an lvalue.
4411 // FIXME: Other qualifiers?
4412 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
4413 unsigned ArgQuals = ArgType.getCVRQualifiers();
4415 if ((ParamQuals | ArgQuals) != ParamQuals) {
4416 S.Diag(Arg->getLocStart(),
4417 diag::err_template_arg_ref_bind_ignores_quals)
4418 << ParamType << Arg->getType() << Arg->getSourceRange();
4419 S.Diag(Param->getLocation(), diag::note_template_param_here);
4425 // At this point, the template argument refers to an object or
4426 // function with external linkage. We now need to check whether the
4427 // argument and parameter types are compatible.
4428 if (!S.Context.hasSameUnqualifiedType(ArgType,
4429 ParamType.getNonReferenceType())) {
4430 // We can't perform this conversion or binding.
4431 if (ParamType->isReferenceType())
4432 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
4433 << ParamType << ArgIn->getType() << Arg->getSourceRange();
4435 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4436 << ArgIn->getType() << ParamType << Arg->getSourceRange();
4437 S.Diag(Param->getLocation(), diag::note_template_param_here);
4445 /// \brief Checks whether the given template argument is the address
4446 /// of an object or function according to C++ [temp.arg.nontype]p1.
4448 CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
4449 NonTypeTemplateParmDecl *Param,
4452 TemplateArgument &Converted) {
4453 bool Invalid = false;
4455 QualType ArgType = Arg->getType();
4457 bool AddressTaken = false;
4458 SourceLocation AddrOpLoc;
4459 if (S.getLangOpts().MicrosoftExt) {
4460 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
4461 // dereference and address-of operators.
4462 Arg = Arg->IgnoreParenCasts();
4464 bool ExtWarnMSTemplateArg = false;
4465 UnaryOperatorKind FirstOpKind;
4466 SourceLocation FirstOpLoc;
4467 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4468 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
4469 if (UnOpKind == UO_Deref)
4470 ExtWarnMSTemplateArg = true;
4471 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
4472 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
4473 if (!AddrOpLoc.isValid()) {
4474 FirstOpKind = UnOpKind;
4475 FirstOpLoc = UnOp->getOperatorLoc();
4480 if (FirstOpLoc.isValid()) {
4481 if (ExtWarnMSTemplateArg)
4482 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
4483 << ArgIn->getSourceRange();
4485 if (FirstOpKind == UO_AddrOf)
4486 AddressTaken = true;
4487 else if (Arg->getType()->isPointerType()) {
4488 // We cannot let pointers get dereferenced here, that is obviously not a
4489 // constant expression.
4490 assert(FirstOpKind == UO_Deref);
4491 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4492 << Arg->getSourceRange();
4496 // See through any implicit casts we added to fix the type.
4497 Arg = Arg->IgnoreImpCasts();
4499 // C++ [temp.arg.nontype]p1:
4501 // A template-argument for a non-type, non-template
4502 // template-parameter shall be one of: [...]
4504 // -- the address of an object or function with external
4505 // linkage, including function templates and function
4506 // template-ids but excluding non-static class members,
4507 // expressed as & id-expression where the & is optional if
4508 // the name refers to a function or array, or if the
4509 // corresponding template-parameter is a reference; or
4511 // In C++98/03 mode, give an extension warning on any extra parentheses.
4512 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4513 bool ExtraParens = false;
4514 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4515 if (!Invalid && !ExtraParens) {
4516 S.Diag(Arg->getLocStart(),
4517 S.getLangOpts().CPlusPlus11
4518 ? diag::warn_cxx98_compat_template_arg_extra_parens
4519 : diag::ext_template_arg_extra_parens)
4520 << Arg->getSourceRange();
4524 Arg = Parens->getSubExpr();
4527 while (SubstNonTypeTemplateParmExpr *subst =
4528 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4529 Arg = subst->getReplacement()->IgnoreImpCasts();
4531 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4532 if (UnOp->getOpcode() == UO_AddrOf) {
4533 Arg = UnOp->getSubExpr();
4534 AddressTaken = true;
4535 AddrOpLoc = UnOp->getOperatorLoc();
4539 while (SubstNonTypeTemplateParmExpr *subst =
4540 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4541 Arg = subst->getReplacement()->IgnoreImpCasts();
4544 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
4545 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
4547 // If our parameter has pointer type, check for a null template value.
4548 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
4549 NullPointerValueKind NPV;
4550 // dllimport'd entities aren't constant but are available inside of template
4552 if (Entity && Entity->hasAttr<DLLImportAttr>())
4553 NPV = NPV_NotNullPointer;
4555 NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
4557 case NPV_NullPointer:
4558 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
4559 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4560 /*isNullPtr=*/true);
4566 case NPV_NotNullPointer:
4571 // Stop checking the precise nature of the argument if it is value dependent,
4572 // it should be checked when instantiated.
4573 if (Arg->isValueDependent()) {
4574 Converted = TemplateArgument(ArgIn);
4578 if (isa<CXXUuidofExpr>(Arg)) {
4579 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
4580 ArgIn, Arg, ArgType))
4583 Converted = TemplateArgument(ArgIn);
4588 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4589 << Arg->getSourceRange();
4590 S.Diag(Param->getLocation(), diag::note_template_param_here);
4594 // Cannot refer to non-static data members
4595 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
4596 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
4597 << Entity << Arg->getSourceRange();
4598 S.Diag(Param->getLocation(), diag::note_template_param_here);
4602 // Cannot refer to non-static member functions
4603 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
4604 if (!Method->isStatic()) {
4605 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
4606 << Method << Arg->getSourceRange();
4607 S.Diag(Param->getLocation(), diag::note_template_param_here);
4612 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
4613 VarDecl *Var = dyn_cast<VarDecl>(Entity);
4615 // A non-type template argument must refer to an object or function.
4616 if (!Func && !Var) {
4617 // We found something, but we don't know specifically what it is.
4618 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
4619 << Arg->getSourceRange();
4620 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4624 // Address / reference template args must have external linkage in C++98.
4625 if (Entity->getFormalLinkage() == InternalLinkage) {
4626 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
4627 diag::warn_cxx98_compat_template_arg_object_internal :
4628 diag::ext_template_arg_object_internal)
4629 << !Func << Entity << Arg->getSourceRange();
4630 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4632 } else if (!Entity->hasLinkage()) {
4633 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
4634 << !Func << Entity << Arg->getSourceRange();
4635 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4641 // If the template parameter has pointer type, the function decays.
4642 if (ParamType->isPointerType() && !AddressTaken)
4643 ArgType = S.Context.getPointerType(Func->getType());
4644 else if (AddressTaken && ParamType->isReferenceType()) {
4645 // If we originally had an address-of operator, but the
4646 // parameter has reference type, complain and (if things look
4647 // like they will work) drop the address-of operator.
4648 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
4649 ParamType.getNonReferenceType())) {
4650 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4652 S.Diag(Param->getLocation(), diag::note_template_param_here);
4656 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4658 << FixItHint::CreateRemoval(AddrOpLoc);
4659 S.Diag(Param->getLocation(), diag::note_template_param_here);
4661 ArgType = Func->getType();
4664 // A value of reference type is not an object.
4665 if (Var->getType()->isReferenceType()) {
4666 S.Diag(Arg->getLocStart(),
4667 diag::err_template_arg_reference_var)
4668 << Var->getType() << Arg->getSourceRange();
4669 S.Diag(Param->getLocation(), diag::note_template_param_here);
4673 // A template argument must have static storage duration.
4674 if (Var->getTLSKind()) {
4675 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
4676 << Arg->getSourceRange();
4677 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
4681 // If the template parameter has pointer type, we must have taken
4682 // the address of this object.
4683 if (ParamType->isReferenceType()) {
4685 // If we originally had an address-of operator, but the
4686 // parameter has reference type, complain and (if things look
4687 // like they will work) drop the address-of operator.
4688 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
4689 ParamType.getNonReferenceType())) {
4690 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4692 S.Diag(Param->getLocation(), diag::note_template_param_here);
4696 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4698 << FixItHint::CreateRemoval(AddrOpLoc);
4699 S.Diag(Param->getLocation(), diag::note_template_param_here);
4701 ArgType = Var->getType();
4703 } else if (!AddressTaken && ParamType->isPointerType()) {
4704 if (Var->getType()->isArrayType()) {
4705 // Array-to-pointer decay.
4706 ArgType = S.Context.getArrayDecayedType(Var->getType());
4708 // If the template parameter has pointer type but the address of
4709 // this object was not taken, complain and (possibly) recover by
4710 // taking the address of the entity.
4711 ArgType = S.Context.getPointerType(Var->getType());
4712 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
4713 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4715 S.Diag(Param->getLocation(), diag::note_template_param_here);
4719 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4721 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
4723 S.Diag(Param->getLocation(), diag::note_template_param_here);
4728 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
4732 // Create the template argument.
4734 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
4735 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
4739 /// \brief Checks whether the given template argument is a pointer to
4740 /// member constant according to C++ [temp.arg.nontype]p1.
4741 static bool CheckTemplateArgumentPointerToMember(Sema &S,
4742 NonTypeTemplateParmDecl *Param,
4745 TemplateArgument &Converted) {
4746 bool Invalid = false;
4748 // Check for a null pointer value.
4749 Expr *Arg = ResultArg;
4750 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
4753 case NPV_NullPointer:
4754 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
4755 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4758 case NPV_NotNullPointer:
4762 bool ObjCLifetimeConversion;
4763 if (S.IsQualificationConversion(Arg->getType(),
4764 ParamType.getNonReferenceType(),
4765 false, ObjCLifetimeConversion)) {
4766 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
4767 Arg->getValueKind()).get();
4769 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
4770 ParamType.getNonReferenceType())) {
4771 // We can't perform this conversion.
4772 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4773 << Arg->getType() << ParamType << Arg->getSourceRange();
4774 S.Diag(Param->getLocation(), diag::note_template_param_here);
4778 // See through any implicit casts we added to fix the type.
4779 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
4780 Arg = Cast->getSubExpr();
4782 // C++ [temp.arg.nontype]p1:
4784 // A template-argument for a non-type, non-template
4785 // template-parameter shall be one of: [...]
4787 // -- a pointer to member expressed as described in 5.3.1.
4788 DeclRefExpr *DRE = nullptr;
4790 // In C++98/03 mode, give an extension warning on any extra parentheses.
4791 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4792 bool ExtraParens = false;
4793 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4794 if (!Invalid && !ExtraParens) {
4795 S.Diag(Arg->getLocStart(),
4796 S.getLangOpts().CPlusPlus11 ?
4797 diag::warn_cxx98_compat_template_arg_extra_parens :
4798 diag::ext_template_arg_extra_parens)
4799 << Arg->getSourceRange();
4803 Arg = Parens->getSubExpr();
4806 while (SubstNonTypeTemplateParmExpr *subst =
4807 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4808 Arg = subst->getReplacement()->IgnoreImpCasts();
4810 // A pointer-to-member constant written &Class::member.
4811 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4812 if (UnOp->getOpcode() == UO_AddrOf) {
4813 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
4814 if (DRE && !DRE->getQualifier())
4818 // A constant of pointer-to-member type.
4819 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
4820 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
4821 if (VD->getType()->isMemberPointerType()) {
4822 if (isa<NonTypeTemplateParmDecl>(VD)) {
4823 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
4824 Converted = TemplateArgument(Arg);
4826 VD = cast<ValueDecl>(VD->getCanonicalDecl());
4827 Converted = TemplateArgument(VD, ParamType);
4838 return S.Diag(Arg->getLocStart(),
4839 diag::err_template_arg_not_pointer_to_member_form)
4840 << Arg->getSourceRange();
4842 if (isa<FieldDecl>(DRE->getDecl()) ||
4843 isa<IndirectFieldDecl>(DRE->getDecl()) ||
4844 isa<CXXMethodDecl>(DRE->getDecl())) {
4845 assert((isa<FieldDecl>(DRE->getDecl()) ||
4846 isa<IndirectFieldDecl>(DRE->getDecl()) ||
4847 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
4848 "Only non-static member pointers can make it here");
4850 // Okay: this is the address of a non-static member, and therefore
4851 // a member pointer constant.
4852 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
4853 Converted = TemplateArgument(Arg);
4855 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
4856 Converted = TemplateArgument(D, ParamType);
4861 // We found something else, but we don't know specifically what it is.
4862 S.Diag(Arg->getLocStart(),
4863 diag::err_template_arg_not_pointer_to_member_form)
4864 << Arg->getSourceRange();
4865 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4869 /// \brief Check a template argument against its corresponding
4870 /// non-type template parameter.
4872 /// This routine implements the semantics of C++ [temp.arg.nontype].
4873 /// If an error occurred, it returns ExprError(); otherwise, it
4874 /// returns the converted template argument. \p ParamType is the
4875 /// type of the non-type template parameter after it has been instantiated.
4876 ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
4877 QualType ParamType, Expr *Arg,
4878 TemplateArgument &Converted,
4879 CheckTemplateArgumentKind CTAK) {
4880 SourceLocation StartLoc = Arg->getLocStart();
4882 // If either the parameter has a dependent type or the argument is
4883 // type-dependent, there's nothing we can check now.
4884 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
4885 // FIXME: Produce a cloned, canonical expression?
4886 Converted = TemplateArgument(Arg);
4890 // We should have already dropped all cv-qualifiers by now.
4891 assert(!ParamType.hasQualifiers() &&
4892 "non-type template parameter type cannot be qualified");
4894 if (CTAK == CTAK_Deduced &&
4895 !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) {
4896 // C++ [temp.deduct.type]p17:
4897 // If, in the declaration of a function template with a non-type
4898 // template-parameter, the non-type template-parameter is used
4899 // in an expression in the function parameter-list and, if the
4900 // corresponding template-argument is deduced, the
4901 // template-argument type shall match the type of the
4902 // template-parameter exactly, except that a template-argument
4903 // deduced from an array bound may be of any integral type.
4904 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
4905 << Arg->getType().getUnqualifiedType()
4906 << ParamType.getUnqualifiedType();
4907 Diag(Param->getLocation(), diag::note_template_param_here);
4911 if (getLangOpts().CPlusPlus1z) {
4912 // FIXME: We can do some limited checking for a value-dependent but not
4913 // type-dependent argument.
4914 if (Arg->isValueDependent()) {
4915 Converted = TemplateArgument(Arg);
4919 // C++1z [temp.arg.nontype]p1:
4920 // A template-argument for a non-type template parameter shall be
4921 // a converted constant expression of the type of the template-parameter.
4923 ExprResult ArgResult = CheckConvertedConstantExpression(
4924 Arg, ParamType, Value, CCEK_TemplateArg);
4925 if (ArgResult.isInvalid())
4928 QualType CanonParamType = Context.getCanonicalType(ParamType);
4930 // Convert the APValue to a TemplateArgument.
4931 switch (Value.getKind()) {
4932 case APValue::Uninitialized:
4933 assert(ParamType->isNullPtrType());
4934 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
4937 assert(ParamType->isIntegralOrEnumerationType());
4938 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
4940 case APValue::MemberPointer: {
4941 assert(ParamType->isMemberPointerType());
4943 // FIXME: We need TemplateArgument representation and mangling for these.
4944 if (!Value.getMemberPointerPath().empty()) {
4945 Diag(Arg->getLocStart(),
4946 diag::err_template_arg_member_ptr_base_derived_not_supported)
4947 << Value.getMemberPointerDecl() << ParamType
4948 << Arg->getSourceRange();
4952 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
4953 Converted = VD ? TemplateArgument(VD, CanonParamType)
4954 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
4957 case APValue::LValue: {
4958 // For a non-type template-parameter of pointer or reference type,
4959 // the value of the constant expression shall not refer to
4960 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
4961 ParamType->isNullPtrType());
4962 // -- a temporary object
4963 // -- a string literal
4964 // -- the result of a typeid expression, or
4965 // -- a predefind __func__ variable
4966 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
4967 if (isa<CXXUuidofExpr>(E)) {
4968 Converted = TemplateArgument(const_cast<Expr*>(E));
4971 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4972 << Arg->getSourceRange();
4975 auto *VD = const_cast<ValueDecl *>(
4976 Value.getLValueBase().dyn_cast<const ValueDecl *>());
4978 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
4979 VD && VD->getType()->isArrayType() &&
4980 Value.getLValuePath()[0].ArrayIndex == 0 &&
4981 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
4982 // Per defect report (no number yet):
4983 // ... other than a pointer to the first element of a complete array
4985 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
4986 Value.isLValueOnePastTheEnd()) {
4987 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
4988 << Value.getAsString(Context, ParamType);
4991 assert((VD || !ParamType->isReferenceType()) &&
4992 "null reference should not be a constant expression");
4993 assert((!VD || !ParamType->isNullPtrType()) &&
4994 "non-null value of type nullptr_t?");
4995 Converted = VD ? TemplateArgument(VD, CanonParamType)
4996 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
4999 case APValue::AddrLabelDiff:
5000 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
5001 case APValue::Float:
5002 case APValue::ComplexInt:
5003 case APValue::ComplexFloat:
5004 case APValue::Vector:
5005 case APValue::Array:
5006 case APValue::Struct:
5007 case APValue::Union:
5008 llvm_unreachable("invalid kind for template argument");
5011 return ArgResult.get();
5014 // C++ [temp.arg.nontype]p5:
5015 // The following conversions are performed on each expression used
5016 // as a non-type template-argument. If a non-type
5017 // template-argument cannot be converted to the type of the
5018 // corresponding template-parameter then the program is
5020 if (ParamType->isIntegralOrEnumerationType()) {
5022 // -- for a non-type template-parameter of integral or
5023 // enumeration type, conversions permitted in a converted
5024 // constant expression are applied.
5027 // -- for a non-type template-parameter of integral or
5028 // enumeration type, integral promotions (4.5) and integral
5029 // conversions (4.7) are applied.
5031 if (getLangOpts().CPlusPlus11) {
5032 // We can't check arbitrary value-dependent arguments.
5033 // FIXME: If there's no viable conversion to the template parameter type,
5034 // we should be able to diagnose that prior to instantiation.
5035 if (Arg->isValueDependent()) {
5036 Converted = TemplateArgument(Arg);
5040 // C++ [temp.arg.nontype]p1:
5041 // A template-argument for a non-type, non-template template-parameter
5044 // -- for a non-type template-parameter of integral or enumeration
5045 // type, a converted constant expression of the type of the
5046 // template-parameter; or
5048 ExprResult ArgResult =
5049 CheckConvertedConstantExpression(Arg, ParamType, Value,
5051 if (ArgResult.isInvalid())
5054 // Widen the argument value to sizeof(parameter type). This is almost
5055 // always a no-op, except when the parameter type is bool. In
5056 // that case, this may extend the argument from 1 bit to 8 bits.
5057 QualType IntegerType = ParamType;
5058 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
5059 IntegerType = Enum->getDecl()->getIntegerType();
5060 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
5062 Converted = TemplateArgument(Context, Value,
5063 Context.getCanonicalType(ParamType));
5067 ExprResult ArgResult = DefaultLvalueConversion(Arg);
5068 if (ArgResult.isInvalid())
5070 Arg = ArgResult.get();
5072 QualType ArgType = Arg->getType();
5074 // C++ [temp.arg.nontype]p1:
5075 // A template-argument for a non-type, non-template
5076 // template-parameter shall be one of:
5078 // -- an integral constant-expression of integral or enumeration
5080 // -- the name of a non-type template-parameter; or
5081 SourceLocation NonConstantLoc;
5083 if (!ArgType->isIntegralOrEnumerationType()) {
5084 Diag(Arg->getLocStart(),
5085 diag::err_template_arg_not_integral_or_enumeral)
5086 << ArgType << Arg->getSourceRange();
5087 Diag(Param->getLocation(), diag::note_template_param_here);
5089 } else if (!Arg->isValueDependent()) {
5090 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
5094 TmplArgICEDiagnoser(QualType T) : T(T) { }
5096 void diagnoseNotICE(Sema &S, SourceLocation Loc,
5097 SourceRange SR) override {
5098 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
5100 } Diagnoser(ArgType);
5102 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
5108 // From here on out, all we care about is the unqualified form
5109 // of the argument type.
5110 ArgType = ArgType.getUnqualifiedType();
5112 // Try to convert the argument to the parameter's type.
5113 if (Context.hasSameType(ParamType, ArgType)) {
5114 // Okay: no conversion necessary
5115 } else if (ParamType->isBooleanType()) {
5116 // This is an integral-to-boolean conversion.
5117 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
5118 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
5119 !ParamType->isEnumeralType()) {
5120 // This is an integral promotion or conversion.
5121 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
5123 // We can't perform this conversion.
5124 Diag(Arg->getLocStart(),
5125 diag::err_template_arg_not_convertible)
5126 << Arg->getType() << ParamType << Arg->getSourceRange();
5127 Diag(Param->getLocation(), diag::note_template_param_here);
5131 // Add the value of this argument to the list of converted
5132 // arguments. We use the bitwidth and signedness of the template
5134 if (Arg->isValueDependent()) {
5135 // The argument is value-dependent. Create a new
5136 // TemplateArgument with the converted expression.
5137 Converted = TemplateArgument(Arg);
5141 QualType IntegerType = Context.getCanonicalType(ParamType);
5142 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
5143 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
5145 if (ParamType->isBooleanType()) {
5146 // Value must be zero or one.
5148 unsigned AllowedBits = Context.getTypeSize(IntegerType);
5149 if (Value.getBitWidth() != AllowedBits)
5150 Value = Value.extOrTrunc(AllowedBits);
5151 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
5153 llvm::APSInt OldValue = Value;
5155 // Coerce the template argument's value to the value it will have
5156 // based on the template parameter's type.
5157 unsigned AllowedBits = Context.getTypeSize(IntegerType);
5158 if (Value.getBitWidth() != AllowedBits)
5159 Value = Value.extOrTrunc(AllowedBits);
5160 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
5162 // Complain if an unsigned parameter received a negative value.
5163 if (IntegerType->isUnsignedIntegerOrEnumerationType()
5164 && (OldValue.isSigned() && OldValue.isNegative())) {
5165 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
5166 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5167 << Arg->getSourceRange();
5168 Diag(Param->getLocation(), diag::note_template_param_here);
5171 // Complain if we overflowed the template parameter's type.
5172 unsigned RequiredBits;
5173 if (IntegerType->isUnsignedIntegerOrEnumerationType())
5174 RequiredBits = OldValue.getActiveBits();
5175 else if (OldValue.isUnsigned())
5176 RequiredBits = OldValue.getActiveBits() + 1;
5178 RequiredBits = OldValue.getMinSignedBits();
5179 if (RequiredBits > AllowedBits) {
5180 Diag(Arg->getLocStart(),
5181 diag::warn_template_arg_too_large)
5182 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5183 << Arg->getSourceRange();
5184 Diag(Param->getLocation(), diag::note_template_param_here);
5188 Converted = TemplateArgument(Context, Value,
5189 ParamType->isEnumeralType()
5190 ? Context.getCanonicalType(ParamType)
5195 QualType ArgType = Arg->getType();
5196 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
5198 // Handle pointer-to-function, reference-to-function, and
5199 // pointer-to-member-function all in (roughly) the same way.
5200 if (// -- For a non-type template-parameter of type pointer to
5201 // function, only the function-to-pointer conversion (4.3) is
5202 // applied. If the template-argument represents a set of
5203 // overloaded functions (or a pointer to such), the matching
5204 // function is selected from the set (13.4).
5205 (ParamType->isPointerType() &&
5206 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
5207 // -- For a non-type template-parameter of type reference to
5208 // function, no conversions apply. If the template-argument
5209 // represents a set of overloaded functions, the matching
5210 // function is selected from the set (13.4).
5211 (ParamType->isReferenceType() &&
5212 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
5213 // -- For a non-type template-parameter of type pointer to
5214 // member function, no conversions apply. If the
5215 // template-argument represents a set of overloaded member
5216 // functions, the matching member function is selected from
5218 (ParamType->isMemberPointerType() &&
5219 ParamType->getAs<MemberPointerType>()->getPointeeType()
5220 ->isFunctionType())) {
5222 if (Arg->getType() == Context.OverloadTy) {
5223 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
5226 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
5229 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5230 ArgType = Arg->getType();
5235 if (!ParamType->isMemberPointerType()) {
5236 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5243 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5249 if (ParamType->isPointerType()) {
5250 // -- for a non-type template-parameter of type pointer to
5251 // object, qualification conversions (4.4) and the
5252 // array-to-pointer conversion (4.2) are applied.
5253 // C++0x also allows a value of std::nullptr_t.
5254 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
5255 "Only object pointers allowed here");
5257 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5264 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
5265 // -- For a non-type template-parameter of type reference to
5266 // object, no conversions apply. The type referred to by the
5267 // reference may be more cv-qualified than the (otherwise
5268 // identical) type of the template-argument. The
5269 // template-parameter is bound directly to the
5270 // template-argument, which must be an lvalue.
5271 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
5272 "Only object references allowed here");
5274 if (Arg->getType() == Context.OverloadTy) {
5275 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
5276 ParamRefType->getPointeeType(),
5279 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
5282 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5283 ArgType = Arg->getType();
5288 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5295 // Deal with parameters of type std::nullptr_t.
5296 if (ParamType->isNullPtrType()) {
5297 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5298 Converted = TemplateArgument(Arg);
5302 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
5303 case NPV_NotNullPointer:
5304 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
5305 << Arg->getType() << ParamType;
5306 Diag(Param->getLocation(), diag::note_template_param_here);
5312 case NPV_NullPointer:
5313 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
5314 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
5320 // -- For a non-type template-parameter of type pointer to data
5321 // member, qualification conversions (4.4) are applied.
5322 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
5324 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5330 /// \brief Check a template argument against its corresponding
5331 /// template template parameter.
5333 /// This routine implements the semantics of C++ [temp.arg.template].
5334 /// It returns true if an error occurred, and false otherwise.
5335 bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
5336 TemplateArgumentLoc &Arg,
5337 unsigned ArgumentPackIndex) {
5338 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
5339 TemplateDecl *Template = Name.getAsTemplateDecl();
5341 // Any dependent template name is fine.
5342 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
5346 // C++0x [temp.arg.template]p1:
5347 // A template-argument for a template template-parameter shall be
5348 // the name of a class template or an alias template, expressed as an
5349 // id-expression. When the template-argument names a class template, only
5350 // primary class templates are considered when matching the
5351 // template template argument with the corresponding parameter;
5352 // partial specializations are not considered even if their
5353 // parameter lists match that of the template template parameter.
5355 // Note that we also allow template template parameters here, which
5356 // will happen when we are dealing with, e.g., class template
5357 // partial specializations.
5358 if (!isa<ClassTemplateDecl>(Template) &&
5359 !isa<TemplateTemplateParmDecl>(Template) &&
5360 !isa<TypeAliasTemplateDecl>(Template)) {
5361 assert(isa<FunctionTemplateDecl>(Template) &&
5362 "Only function templates are possible here");
5363 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
5364 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
5368 TemplateParameterList *Params = Param->getTemplateParameters();
5369 if (Param->isExpandedParameterPack())
5370 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
5372 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
5375 TPL_TemplateTemplateArgumentMatch,
5379 /// \brief Given a non-type template argument that refers to a
5380 /// declaration and the type of its corresponding non-type template
5381 /// parameter, produce an expression that properly refers to that
5384 Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5386 SourceLocation Loc) {
5387 // C++ [temp.param]p8:
5389 // A non-type template-parameter of type "array of T" or
5390 // "function returning T" is adjusted to be of type "pointer to
5391 // T" or "pointer to function returning T", respectively.
5392 if (ParamType->isArrayType())
5393 ParamType = Context.getArrayDecayedType(ParamType);
5394 else if (ParamType->isFunctionType())
5395 ParamType = Context.getPointerType(ParamType);
5397 // For a NULL non-type template argument, return nullptr casted to the
5398 // parameter's type.
5399 if (Arg.getKind() == TemplateArgument::NullPtr) {
5400 return ImpCastExprToType(
5401 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
5403 ParamType->getAs<MemberPointerType>()
5404 ? CK_NullToMemberPointer
5405 : CK_NullToPointer);
5407 assert(Arg.getKind() == TemplateArgument::Declaration &&
5408 "Only declaration template arguments permitted here");
5410 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
5412 if (VD->getDeclContext()->isRecord() &&
5413 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
5414 isa<IndirectFieldDecl>(VD))) {
5415 // If the value is a class member, we might have a pointer-to-member.
5416 // Determine whether the non-type template template parameter is of
5417 // pointer-to-member type. If so, we need to build an appropriate
5418 // expression for a pointer-to-member, since a "normal" DeclRefExpr
5419 // would refer to the member itself.
5420 if (ParamType->isMemberPointerType()) {
5422 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
5423 NestedNameSpecifier *Qualifier
5424 = NestedNameSpecifier::Create(Context, nullptr, false,
5425 ClassType.getTypePtr());
5427 SS.MakeTrivial(Context, Qualifier, Loc);
5429 // The actual value-ness of this is unimportant, but for
5430 // internal consistency's sake, references to instance methods
5432 ExprValueKind VK = VK_LValue;
5433 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
5436 ExprResult RefExpr = BuildDeclRefExpr(VD,
5437 VD->getType().getNonReferenceType(),
5441 if (RefExpr.isInvalid())
5444 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
5446 // We might need to perform a trailing qualification conversion, since
5447 // the element type on the parameter could be more qualified than the
5448 // element type in the expression we constructed.
5449 bool ObjCLifetimeConversion;
5450 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
5451 ParamType.getUnqualifiedType(), false,
5452 ObjCLifetimeConversion))
5453 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
5455 assert(!RefExpr.isInvalid() &&
5456 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
5457 ParamType.getUnqualifiedType()));
5462 QualType T = VD->getType().getNonReferenceType();
5464 if (ParamType->isPointerType()) {
5465 // When the non-type template parameter is a pointer, take the
5466 // address of the declaration.
5467 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
5468 if (RefExpr.isInvalid())
5471 if (T->isFunctionType() || T->isArrayType()) {
5472 // Decay functions and arrays.
5473 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
5474 if (RefExpr.isInvalid())
5480 // Take the address of everything else
5481 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
5484 ExprValueKind VK = VK_RValue;
5486 // If the non-type template parameter has reference type, qualify the
5487 // resulting declaration reference with the extra qualifiers on the
5488 // type that the reference refers to.
5489 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
5491 T = Context.getQualifiedType(T,
5492 TargetRef->getPointeeType().getQualifiers());
5493 } else if (isa<FunctionDecl>(VD)) {
5494 // References to functions are always lvalues.
5498 return BuildDeclRefExpr(VD, T, VK, Loc);
5501 /// \brief Construct a new expression that refers to the given
5502 /// integral template argument with the given source-location
5505 /// This routine takes care of the mapping from an integral template
5506 /// argument (which may have any integral type) to the appropriate
5509 Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5510 SourceLocation Loc) {
5511 assert(Arg.getKind() == TemplateArgument::Integral &&
5512 "Operation is only valid for integral template arguments");
5513 QualType OrigT = Arg.getIntegralType();
5515 // If this is an enum type that we're instantiating, we need to use an integer
5516 // type the same size as the enumerator. We don't want to build an
5517 // IntegerLiteral with enum type. The integer type of an enum type can be of
5518 // any integral type with C++11 enum classes, make sure we create the right
5519 // type of literal for it.
5521 if (const EnumType *ET = OrigT->getAs<EnumType>())
5522 T = ET->getDecl()->getIntegerType();
5525 if (T->isAnyCharacterType()) {
5526 // This does not need to handle u8 character literals because those are
5527 // of type char, and so can also be covered by an ASCII character literal.
5528 CharacterLiteral::CharacterKind Kind;
5529 if (T->isWideCharType())
5530 Kind = CharacterLiteral::Wide;
5531 else if (T->isChar16Type())
5532 Kind = CharacterLiteral::UTF16;
5533 else if (T->isChar32Type())
5534 Kind = CharacterLiteral::UTF32;
5536 Kind = CharacterLiteral::Ascii;
5538 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
5540 } else if (T->isBooleanType()) {
5541 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
5543 } else if (T->isNullPtrType()) {
5544 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
5546 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
5549 if (OrigT->isEnumeralType()) {
5550 // FIXME: This is a hack. We need a better way to handle substituted
5551 // non-type template parameters.
5552 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
5554 Context.getTrivialTypeSourceInfo(OrigT, Loc),
5561 /// \brief Match two template parameters within template parameter lists.
5562 static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
5564 Sema::TemplateParameterListEqualKind Kind,
5565 SourceLocation TemplateArgLoc) {
5566 // Check the actual kind (type, non-type, template).
5567 if (Old->getKind() != New->getKind()) {
5569 unsigned NextDiag = diag::err_template_param_different_kind;
5570 if (TemplateArgLoc.isValid()) {
5571 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5572 NextDiag = diag::note_template_param_different_kind;
5574 S.Diag(New->getLocation(), NextDiag)
5575 << (Kind != Sema::TPL_TemplateMatch);
5576 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
5577 << (Kind != Sema::TPL_TemplateMatch);
5583 // Check that both are parameter packs are neither are parameter packs.
5584 // However, if we are matching a template template argument to a
5585 // template template parameter, the template template parameter can have
5586 // a parameter pack where the template template argument does not.
5587 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
5588 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5589 Old->isTemplateParameterPack())) {
5591 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
5592 if (TemplateArgLoc.isValid()) {
5593 S.Diag(TemplateArgLoc,
5594 diag::err_template_arg_template_params_mismatch);
5595 NextDiag = diag::note_template_parameter_pack_non_pack;
5598 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
5599 : isa<NonTypeTemplateParmDecl>(New)? 1
5601 S.Diag(New->getLocation(), NextDiag)
5602 << ParamKind << New->isParameterPack();
5603 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
5604 << ParamKind << Old->isParameterPack();
5610 // For non-type template parameters, check the type of the parameter.
5611 if (NonTypeTemplateParmDecl *OldNTTP
5612 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
5613 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
5615 // If we are matching a template template argument to a template
5616 // template parameter and one of the non-type template parameter types
5617 // is dependent, then we must wait until template instantiation time
5618 // to actually compare the arguments.
5619 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5620 (OldNTTP->getType()->isDependentType() ||
5621 NewNTTP->getType()->isDependentType()))
5624 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
5626 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
5627 if (TemplateArgLoc.isValid()) {
5628 S.Diag(TemplateArgLoc,
5629 diag::err_template_arg_template_params_mismatch);
5630 NextDiag = diag::note_template_nontype_parm_different_type;
5632 S.Diag(NewNTTP->getLocation(), NextDiag)
5633 << NewNTTP->getType()
5634 << (Kind != Sema::TPL_TemplateMatch);
5635 S.Diag(OldNTTP->getLocation(),
5636 diag::note_template_nontype_parm_prev_declaration)
5637 << OldNTTP->getType();
5646 // For template template parameters, check the template parameter types.
5647 // The template parameter lists of template template
5648 // parameters must agree.
5649 if (TemplateTemplateParmDecl *OldTTP
5650 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
5651 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
5652 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
5653 OldTTP->getTemplateParameters(),
5655 (Kind == Sema::TPL_TemplateMatch
5656 ? Sema::TPL_TemplateTemplateParmMatch
5664 /// \brief Diagnose a known arity mismatch when comparing template argument
5667 void DiagnoseTemplateParameterListArityMismatch(Sema &S,
5668 TemplateParameterList *New,
5669 TemplateParameterList *Old,
5670 Sema::TemplateParameterListEqualKind Kind,
5671 SourceLocation TemplateArgLoc) {
5672 unsigned NextDiag = diag::err_template_param_list_different_arity;
5673 if (TemplateArgLoc.isValid()) {
5674 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5675 NextDiag = diag::note_template_param_list_different_arity;
5677 S.Diag(New->getTemplateLoc(), NextDiag)
5678 << (New->size() > Old->size())
5679 << (Kind != Sema::TPL_TemplateMatch)
5680 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
5681 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
5682 << (Kind != Sema::TPL_TemplateMatch)
5683 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
5686 /// \brief Determine whether the given template parameter lists are
5689 /// \param New The new template parameter list, typically written in the
5690 /// source code as part of a new template declaration.
5692 /// \param Old The old template parameter list, typically found via
5693 /// name lookup of the template declared with this template parameter
5696 /// \param Complain If true, this routine will produce a diagnostic if
5697 /// the template parameter lists are not equivalent.
5699 /// \param Kind describes how we are to match the template parameter lists.
5701 /// \param TemplateArgLoc If this source location is valid, then we
5702 /// are actually checking the template parameter list of a template
5703 /// argument (New) against the template parameter list of its
5704 /// corresponding template template parameter (Old). We produce
5705 /// slightly different diagnostics in this scenario.
5707 /// \returns True if the template parameter lists are equal, false
5710 Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
5711 TemplateParameterList *Old,
5713 TemplateParameterListEqualKind Kind,
5714 SourceLocation TemplateArgLoc) {
5715 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
5717 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5723 // C++0x [temp.arg.template]p3:
5724 // A template-argument matches a template template-parameter (call it P)
5725 // when each of the template parameters in the template-parameter-list of
5726 // the template-argument's corresponding class template or alias template
5727 // (call it A) matches the corresponding template parameter in the
5728 // template-parameter-list of P. [...]
5729 TemplateParameterList::iterator NewParm = New->begin();
5730 TemplateParameterList::iterator NewParmEnd = New->end();
5731 for (TemplateParameterList::iterator OldParm = Old->begin(),
5732 OldParmEnd = Old->end();
5733 OldParm != OldParmEnd; ++OldParm) {
5734 if (Kind != TPL_TemplateTemplateArgumentMatch ||
5735 !(*OldParm)->isTemplateParameterPack()) {
5736 if (NewParm == NewParmEnd) {
5738 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5744 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5745 Kind, TemplateArgLoc))
5752 // C++0x [temp.arg.template]p3:
5753 // [...] When P's template- parameter-list contains a template parameter
5754 // pack (14.5.3), the template parameter pack will match zero or more
5755 // template parameters or template parameter packs in the
5756 // template-parameter-list of A with the same type and form as the
5757 // template parameter pack in P (ignoring whether those template
5758 // parameters are template parameter packs).
5759 for (; NewParm != NewParmEnd; ++NewParm) {
5760 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5761 Kind, TemplateArgLoc))
5766 // Make sure we exhausted all of the arguments.
5767 if (NewParm != NewParmEnd) {
5769 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5778 /// \brief Check whether a template can be declared within this scope.
5780 /// If the template declaration is valid in this scope, returns
5781 /// false. Otherwise, issues a diagnostic and returns true.
5783 Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
5787 // Find the nearest enclosing declaration scope.
5788 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5789 (S->getFlags() & Scope::TemplateParamScope) != 0)
5793 // A template [...] shall not have C linkage.
5794 DeclContext *Ctx = S->getEntity();
5795 if (Ctx && Ctx->isExternCContext())
5796 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
5797 << TemplateParams->getSourceRange();
5799 while (Ctx && isa<LinkageSpecDecl>(Ctx))
5800 Ctx = Ctx->getParent();
5803 // A template-declaration can appear only as a namespace scope or
5804 // class scope declaration.
5806 if (Ctx->isFileContext())
5808 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
5809 // C++ [temp.mem]p2:
5810 // A local class shall not have member templates.
5811 if (RD->isLocalClass())
5812 return Diag(TemplateParams->getTemplateLoc(),
5813 diag::err_template_inside_local_class)
5814 << TemplateParams->getSourceRange();
5820 return Diag(TemplateParams->getTemplateLoc(),
5821 diag::err_template_outside_namespace_or_class_scope)
5822 << TemplateParams->getSourceRange();
5825 /// \brief Determine what kind of template specialization the given declaration
5827 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
5829 return TSK_Undeclared;
5831 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
5832 return Record->getTemplateSpecializationKind();
5833 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
5834 return Function->getTemplateSpecializationKind();
5835 if (VarDecl *Var = dyn_cast<VarDecl>(D))
5836 return Var->getTemplateSpecializationKind();
5838 return TSK_Undeclared;
5841 /// \brief Check whether a specialization is well-formed in the current
5844 /// This routine determines whether a template specialization can be declared
5845 /// in the current context (C++ [temp.expl.spec]p2).
5847 /// \param S the semantic analysis object for which this check is being
5850 /// \param Specialized the entity being specialized or instantiated, which
5851 /// may be a kind of template (class template, function template, etc.) or
5852 /// a member of a class template (member function, static data member,
5855 /// \param PrevDecl the previous declaration of this entity, if any.
5857 /// \param Loc the location of the explicit specialization or instantiation of
5860 /// \param IsPartialSpecialization whether this is a partial specialization of
5861 /// a class template.
5863 /// \returns true if there was an error that we cannot recover from, false
5865 static bool CheckTemplateSpecializationScope(Sema &S,
5866 NamedDecl *Specialized,
5867 NamedDecl *PrevDecl,
5869 bool IsPartialSpecialization) {
5870 // Keep these "kind" numbers in sync with the %select statements in the
5871 // various diagnostics emitted by this routine.
5873 if (isa<ClassTemplateDecl>(Specialized))
5874 EntityKind = IsPartialSpecialization? 1 : 0;
5875 else if (isa<VarTemplateDecl>(Specialized))
5876 EntityKind = IsPartialSpecialization ? 3 : 2;
5877 else if (isa<FunctionTemplateDecl>(Specialized))
5879 else if (isa<CXXMethodDecl>(Specialized))
5881 else if (isa<VarDecl>(Specialized))
5883 else if (isa<RecordDecl>(Specialized))
5885 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
5888 S.Diag(Loc, diag::err_template_spec_unknown_kind)
5889 << S.getLangOpts().CPlusPlus11;
5890 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5894 // C++ [temp.expl.spec]p2:
5895 // An explicit specialization shall be declared in the namespace
5896 // of which the template is a member, or, for member templates, in
5897 // the namespace of which the enclosing class or enclosing class
5898 // template is a member. An explicit specialization of a member
5899 // function, member class or static data member of a class
5900 // template shall be declared in the namespace of which the class
5901 // template is a member. Such a declaration may also be a
5902 // definition. If the declaration is not a definition, the
5903 // specialization may be defined later in the name- space in which
5904 // the explicit specialization was declared, or in a namespace
5905 // that encloses the one in which the explicit specialization was
5907 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
5908 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
5913 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
5914 if (S.getLangOpts().MicrosoftExt) {
5915 // Do not warn for class scope explicit specialization during
5916 // instantiation, warning was already emitted during pattern
5917 // semantic analysis.
5918 if (!S.ActiveTemplateInstantiations.size())
5919 S.Diag(Loc, diag::ext_function_specialization_in_class)
5922 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5928 if (S.CurContext->isRecord() &&
5929 !S.CurContext->Equals(Specialized->getDeclContext())) {
5930 // Make sure that we're specializing in the right record context.
5931 // Otherwise, things can go horribly wrong.
5932 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5937 // C++ [temp.class.spec]p6:
5938 // A class template partial specialization may be declared or redeclared
5939 // in any namespace scope in which its definition may be defined (14.5.1
5941 DeclContext *SpecializedContext
5942 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
5943 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
5945 // Make sure that this redeclaration (or definition) occurs in an enclosing
5947 // Note that HandleDeclarator() performs this check for explicit
5948 // specializations of function templates, static data members, and member
5949 // functions, so we skip the check here for those kinds of entities.
5950 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
5951 // Should we refactor that check, so that it occurs later?
5952 if (!DC->Encloses(SpecializedContext) &&
5953 !(isa<FunctionTemplateDecl>(Specialized) ||
5954 isa<FunctionDecl>(Specialized) ||
5955 isa<VarTemplateDecl>(Specialized) ||
5956 isa<VarDecl>(Specialized))) {
5957 if (isa<TranslationUnitDecl>(SpecializedContext))
5958 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
5959 << EntityKind << Specialized;
5960 else if (isa<NamespaceDecl>(SpecializedContext)) {
5961 int Diag = diag::err_template_spec_redecl_out_of_scope;
5962 if (S.getLangOpts().MicrosoftExt)
5963 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
5964 S.Diag(Loc, Diag) << EntityKind << Specialized
5965 << cast<NamedDecl>(SpecializedContext);
5967 llvm_unreachable("unexpected namespace context for specialization");
5969 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5970 } else if ((!PrevDecl ||
5971 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
5972 getTemplateSpecializationKind(PrevDecl) ==
5973 TSK_ImplicitInstantiation)) {
5974 // C++ [temp.exp.spec]p2:
5975 // An explicit specialization shall be declared in the namespace of which
5976 // the template is a member, or, for member templates, in the namespace
5977 // of which the enclosing class or enclosing class template is a member.
5978 // An explicit specialization of a member function, member class or
5979 // static data member of a class template shall be declared in the
5980 // namespace of which the class template is a member.
5982 // C++11 [temp.expl.spec]p2:
5983 // An explicit specialization shall be declared in a namespace enclosing
5984 // the specialized template.
5985 // C++11 [temp.explicit]p3:
5986 // An explicit instantiation shall appear in an enclosing namespace of its
5988 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
5989 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
5990 if (isa<TranslationUnitDecl>(SpecializedContext)) {
5991 assert(!IsCPlusPlus11Extension &&
5992 "DC encloses TU but isn't in enclosing namespace set");
5993 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
5994 << EntityKind << Specialized;
5995 } else if (isa<NamespaceDecl>(SpecializedContext)) {
5997 if (!IsCPlusPlus11Extension)
5998 Diag = diag::err_template_spec_decl_out_of_scope;
5999 else if (!S.getLangOpts().CPlusPlus11)
6000 Diag = diag::ext_template_spec_decl_out_of_scope;
6002 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
6004 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
6007 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
6014 static SourceRange findTemplateParameter(unsigned Depth, Expr *E) {
6015 if (!E->isInstantiationDependent())
6016 return SourceLocation();
6017 DependencyChecker Checker(Depth);
6018 Checker.TraverseStmt(E);
6019 if (Checker.Match && Checker.MatchLoc.isInvalid())
6020 return E->getSourceRange();
6021 return Checker.MatchLoc;
6024 static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
6025 if (!TL.getType()->isDependentType())
6026 return SourceLocation();
6027 DependencyChecker Checker(Depth);
6028 Checker.TraverseTypeLoc(TL);
6029 if (Checker.Match && Checker.MatchLoc.isInvalid())
6030 return TL.getSourceRange();
6031 return Checker.MatchLoc;
6034 /// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
6035 /// that checks non-type template partial specialization arguments.
6036 static bool CheckNonTypeTemplatePartialSpecializationArgs(
6037 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
6038 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
6039 for (unsigned I = 0; I != NumArgs; ++I) {
6040 if (Args[I].getKind() == TemplateArgument::Pack) {
6041 if (CheckNonTypeTemplatePartialSpecializationArgs(
6042 S, TemplateNameLoc, Param, Args[I].pack_begin(),
6043 Args[I].pack_size(), IsDefaultArgument))
6049 if (Args[I].getKind() != TemplateArgument::Expression)
6052 Expr *ArgExpr = Args[I].getAsExpr();
6054 // We can have a pack expansion of any of the bullets below.
6055 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
6056 ArgExpr = Expansion->getPattern();
6058 // Strip off any implicit casts we added as part of type checking.
6059 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
6060 ArgExpr = ICE->getSubExpr();
6062 // C++ [temp.class.spec]p8:
6063 // A non-type argument is non-specialized if it is the name of a
6064 // non-type parameter. All other non-type arguments are
6067 // Below, we check the two conditions that only apply to
6068 // specialized non-type arguments, so skip any non-specialized
6070 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
6071 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
6074 // C++ [temp.class.spec]p9:
6075 // Within the argument list of a class template partial
6076 // specialization, the following restrictions apply:
6077 // -- A partially specialized non-type argument expression
6078 // shall not involve a template parameter of the partial
6079 // specialization except when the argument expression is a
6080 // simple identifier.
6081 SourceRange ParamUseRange =
6082 findTemplateParameter(Param->getDepth(), ArgExpr);
6083 if (ParamUseRange.isValid()) {
6084 if (IsDefaultArgument) {
6085 S.Diag(TemplateNameLoc,
6086 diag::err_dependent_non_type_arg_in_partial_spec);
6087 S.Diag(ParamUseRange.getBegin(),
6088 diag::note_dependent_non_type_default_arg_in_partial_spec)
6091 S.Diag(ParamUseRange.getBegin(),
6092 diag::err_dependent_non_type_arg_in_partial_spec)
6098 // -- The type of a template parameter corresponding to a
6099 // specialized non-type argument shall not be dependent on a
6100 // parameter of the specialization.
6102 // FIXME: We need to delay this check until instantiation in some cases:
6104 // template<template<typename> class X> struct A {
6105 // template<typename T, X<T> N> struct B;
6106 // template<typename T> struct B<T, 0>;
6108 // template<typename> using X = int;
6109 // A<X>::B<int, 0> b;
6110 ParamUseRange = findTemplateParameter(
6111 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
6112 if (ParamUseRange.isValid()) {
6113 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
6114 diag::err_dependent_typed_non_type_arg_in_partial_spec)
6115 << Param->getType() << ParamUseRange;
6116 S.Diag(Param->getLocation(), diag::note_template_param_here)
6117 << (IsDefaultArgument ? ParamUseRange : SourceRange());
6125 /// \brief Check the non-type template arguments of a class template
6126 /// partial specialization according to C++ [temp.class.spec]p9.
6128 /// \param TemplateNameLoc the location of the template name.
6129 /// \param TemplateParams the template parameters of the primary class
6131 /// \param NumExplicit the number of explicitly-specified template arguments.
6132 /// \param TemplateArgs the template arguments of the class template
6133 /// partial specialization.
6135 /// \returns \c true if there was an error, \c false otherwise.
6136 static bool CheckTemplatePartialSpecializationArgs(
6137 Sema &S, SourceLocation TemplateNameLoc,
6138 TemplateParameterList *TemplateParams, unsigned NumExplicit,
6139 SmallVectorImpl<TemplateArgument> &TemplateArgs) {
6140 const TemplateArgument *ArgList = TemplateArgs.data();
6142 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6143 NonTypeTemplateParmDecl *Param
6144 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
6148 if (CheckNonTypeTemplatePartialSpecializationArgs(
6149 S, TemplateNameLoc, Param, &ArgList[I], 1, I >= NumExplicit))
6157 Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
6159 SourceLocation KWLoc,
6160 SourceLocation ModulePrivateLoc,
6161 TemplateIdAnnotation &TemplateId,
6162 AttributeList *Attr,
6163 MultiTemplateParamsArg
6164 TemplateParameterLists,
6165 SkipBodyInfo *SkipBody) {
6166 assert(TUK != TUK_Reference && "References are not specializations");
6168 CXXScopeSpec &SS = TemplateId.SS;
6170 // NOTE: KWLoc is the location of the tag keyword. This will instead
6171 // store the location of the outermost template keyword in the declaration.
6172 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
6173 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
6174 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
6175 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
6176 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
6178 // Find the class template we're specializing
6179 TemplateName Name = TemplateId.Template.get();
6180 ClassTemplateDecl *ClassTemplate
6181 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
6183 if (!ClassTemplate) {
6184 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
6185 << (Name.getAsTemplateDecl() &&
6186 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
6190 bool isExplicitSpecialization = false;
6191 bool isPartialSpecialization = false;
6193 // Check the validity of the template headers that introduce this
6195 // FIXME: We probably shouldn't complain about these headers for
6196 // friend declarations.
6197 bool Invalid = false;
6198 TemplateParameterList *TemplateParams =
6199 MatchTemplateParametersToScopeSpecifier(
6200 KWLoc, TemplateNameLoc, SS, &TemplateId,
6201 TemplateParameterLists, TUK == TUK_Friend, isExplicitSpecialization,
6206 if (TemplateParams && TemplateParams->size() > 0) {
6207 isPartialSpecialization = true;
6209 if (TUK == TUK_Friend) {
6210 Diag(KWLoc, diag::err_partial_specialization_friend)
6211 << SourceRange(LAngleLoc, RAngleLoc);
6215 // C++ [temp.class.spec]p10:
6216 // The template parameter list of a specialization shall not
6217 // contain default template argument values.
6218 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6219 Decl *Param = TemplateParams->getParam(I);
6220 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6221 if (TTP->hasDefaultArgument()) {
6222 Diag(TTP->getDefaultArgumentLoc(),
6223 diag::err_default_arg_in_partial_spec);
6224 TTP->removeDefaultArgument();
6226 } else if (NonTypeTemplateParmDecl *NTTP
6227 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6228 if (Expr *DefArg = NTTP->getDefaultArgument()) {
6229 Diag(NTTP->getDefaultArgumentLoc(),
6230 diag::err_default_arg_in_partial_spec)
6231 << DefArg->getSourceRange();
6232 NTTP->removeDefaultArgument();
6235 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
6236 if (TTP->hasDefaultArgument()) {
6237 Diag(TTP->getDefaultArgument().getLocation(),
6238 diag::err_default_arg_in_partial_spec)
6239 << TTP->getDefaultArgument().getSourceRange();
6240 TTP->removeDefaultArgument();
6244 } else if (TemplateParams) {
6245 if (TUK == TUK_Friend)
6246 Diag(KWLoc, diag::err_template_spec_friend)
6247 << FixItHint::CreateRemoval(
6248 SourceRange(TemplateParams->getTemplateLoc(),
6249 TemplateParams->getRAngleLoc()))
6250 << SourceRange(LAngleLoc, RAngleLoc);
6252 isExplicitSpecialization = true;
6254 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
6257 // Check that the specialization uses the same tag kind as the
6258 // original template.
6259 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6260 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
6261 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
6262 Kind, TUK == TUK_Definition, KWLoc,
6263 ClassTemplate->getIdentifier())) {
6264 Diag(KWLoc, diag::err_use_with_wrong_tag)
6266 << FixItHint::CreateReplacement(KWLoc,
6267 ClassTemplate->getTemplatedDecl()->getKindName());
6268 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
6269 diag::note_previous_use);
6270 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
6273 // Translate the parser's template argument list in our AST format.
6274 TemplateArgumentListInfo TemplateArgs =
6275 makeTemplateArgumentListInfo(*this, TemplateId);
6277 // Check for unexpanded parameter packs in any of the template arguments.
6278 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
6279 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
6280 UPPC_PartialSpecialization))
6283 // Check that the template argument list is well-formed for this
6285 SmallVector<TemplateArgument, 4> Converted;
6286 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
6287 TemplateArgs, false, Converted))
6290 // Find the class template (partial) specialization declaration that
6291 // corresponds to these arguments.
6292 if (isPartialSpecialization) {
6293 if (CheckTemplatePartialSpecializationArgs(
6294 *this, TemplateNameLoc, ClassTemplate->getTemplateParameters(),
6295 TemplateArgs.size(), Converted))
6298 bool InstantiationDependent;
6299 if (!Name.isDependent() &&
6300 !TemplateSpecializationType::anyDependentTemplateArguments(
6301 TemplateArgs.getArgumentArray(),
6302 TemplateArgs.size(),
6303 InstantiationDependent)) {
6304 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
6305 << ClassTemplate->getDeclName();
6306 isPartialSpecialization = false;
6310 void *InsertPos = nullptr;
6311 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
6313 if (isPartialSpecialization)
6314 // FIXME: Template parameter list matters, too
6315 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
6317 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
6319 ClassTemplateSpecializationDecl *Specialization = nullptr;
6321 // Check whether we can declare a class template specialization in
6322 // the current scope.
6323 if (TUK != TUK_Friend &&
6324 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
6326 isPartialSpecialization))
6329 // The canonical type
6331 if (isPartialSpecialization) {
6332 // Build the canonical type that describes the converted template
6333 // arguments of the class template partial specialization.
6334 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6335 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
6339 if (Context.hasSameType(CanonType,
6340 ClassTemplate->getInjectedClassNameSpecialization())) {
6341 // C++ [temp.class.spec]p9b3:
6343 // -- The argument list of the specialization shall not be identical
6344 // to the implicit argument list of the primary template.
6345 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
6346 << /*class template*/0 << (TUK == TUK_Definition)
6347 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
6348 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
6349 ClassTemplate->getIdentifier(),
6353 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
6354 /*FriendLoc*/SourceLocation(),
6355 TemplateParameterLists.size() - 1,
6356 TemplateParameterLists.data());
6359 // Create a new class template partial specialization declaration node.
6360 ClassTemplatePartialSpecializationDecl *PrevPartial
6361 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
6362 ClassTemplatePartialSpecializationDecl *Partial
6363 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
6364 ClassTemplate->getDeclContext(),
6365 KWLoc, TemplateNameLoc,
6373 SetNestedNameSpecifier(Partial, SS);
6374 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
6375 Partial->setTemplateParameterListsInfo(
6376 Context, TemplateParameterLists.drop_back(1));
6380 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
6381 Specialization = Partial;
6383 // If we are providing an explicit specialization of a member class
6384 // template specialization, make a note of that.
6385 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
6386 PrevPartial->setMemberSpecialization();
6388 // Check that all of the template parameters of the class template
6389 // partial specialization are deducible from the template
6390 // arguments. If not, this class template partial specialization
6391 // will never be used.
6392 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
6393 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
6394 TemplateParams->getDepth(),
6397 if (!DeducibleParams.all()) {
6398 unsigned NumNonDeducible = DeducibleParams.size()-DeducibleParams.count();
6399 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
6400 << /*class template*/0 << (NumNonDeducible > 1)
6401 << SourceRange(TemplateNameLoc, RAngleLoc);
6402 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
6403 if (!DeducibleParams[I]) {
6404 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
6405 if (Param->getDeclName())
6406 Diag(Param->getLocation(),
6407 diag::note_partial_spec_unused_parameter)
6408 << Param->getDeclName();
6410 Diag(Param->getLocation(),
6411 diag::note_partial_spec_unused_parameter)
6417 // Create a new class template specialization declaration node for
6418 // this explicit specialization or friend declaration.
6420 = ClassTemplateSpecializationDecl::Create(Context, Kind,
6421 ClassTemplate->getDeclContext(),
6422 KWLoc, TemplateNameLoc,
6427 SetNestedNameSpecifier(Specialization, SS);
6428 if (TemplateParameterLists.size() > 0) {
6429 Specialization->setTemplateParameterListsInfo(Context,
6430 TemplateParameterLists);
6434 ClassTemplate->AddSpecialization(Specialization, InsertPos);
6436 if (CurContext->isDependentContext()) {
6437 // -fms-extensions permits specialization of nested classes without
6438 // fully specializing the outer class(es).
6439 assert(getLangOpts().MicrosoftExt &&
6440 "Only possible with -fms-extensions!");
6441 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6442 CanonType = Context.getTemplateSpecializationType(
6443 CanonTemplate, Converted.data(), Converted.size());
6445 CanonType = Context.getTypeDeclType(Specialization);
6449 // C++ [temp.expl.spec]p6:
6450 // If a template, a member template or the member of a class template is
6451 // explicitly specialized then that specialization shall be declared
6452 // before the first use of that specialization that would cause an implicit
6453 // instantiation to take place, in every translation unit in which such a
6454 // use occurs; no diagnostic is required.
6455 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
6457 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
6458 // Is there any previous explicit specialization declaration?
6459 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6466 SourceRange Range(TemplateNameLoc, RAngleLoc);
6467 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
6468 << Context.getTypeDeclType(Specialization) << Range;
6470 Diag(PrevDecl->getPointOfInstantiation(),
6471 diag::note_instantiation_required_here)
6472 << (PrevDecl->getTemplateSpecializationKind()
6473 != TSK_ImplicitInstantiation);
6478 // If this is not a friend, note that this is an explicit specialization.
6479 if (TUK != TUK_Friend)
6480 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
6482 // Check that this isn't a redefinition of this specialization.
6483 if (TUK == TUK_Definition) {
6484 RecordDecl *Def = Specialization->getDefinition();
6485 NamedDecl *Hidden = nullptr;
6486 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
6487 SkipBody->ShouldSkip = true;
6488 makeMergedDefinitionVisible(Hidden, KWLoc);
6489 // From here on out, treat this as just a redeclaration.
6490 TUK = TUK_Declaration;
6492 SourceRange Range(TemplateNameLoc, RAngleLoc);
6493 Diag(TemplateNameLoc, diag::err_redefinition)
6494 << Context.getTypeDeclType(Specialization) << Range;
6495 Diag(Def->getLocation(), diag::note_previous_definition);
6496 Specialization->setInvalidDecl();
6502 ProcessDeclAttributeList(S, Specialization, Attr);
6504 // Add alignment attributes if necessary; these attributes are checked when
6505 // the ASTContext lays out the structure.
6506 if (TUK == TUK_Definition) {
6507 AddAlignmentAttributesForRecord(Specialization);
6508 AddMsStructLayoutForRecord(Specialization);
6511 if (ModulePrivateLoc.isValid())
6512 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
6513 << (isPartialSpecialization? 1 : 0)
6514 << FixItHint::CreateRemoval(ModulePrivateLoc);
6516 // Build the fully-sugared type for this class template
6517 // specialization as the user wrote in the specialization
6518 // itself. This means that we'll pretty-print the type retrieved
6519 // from the specialization's declaration the way that the user
6520 // actually wrote the specialization, rather than formatting the
6521 // name based on the "canonical" representation used to store the
6522 // template arguments in the specialization.
6523 TypeSourceInfo *WrittenTy
6524 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
6525 TemplateArgs, CanonType);
6526 if (TUK != TUK_Friend) {
6527 Specialization->setTypeAsWritten(WrittenTy);
6528 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
6531 // C++ [temp.expl.spec]p9:
6532 // A template explicit specialization is in the scope of the
6533 // namespace in which the template was defined.
6535 // We actually implement this paragraph where we set the semantic
6536 // context (in the creation of the ClassTemplateSpecializationDecl),
6537 // but we also maintain the lexical context where the actual
6538 // definition occurs.
6539 Specialization->setLexicalDeclContext(CurContext);
6541 // We may be starting the definition of this specialization.
6542 if (TUK == TUK_Definition)
6543 Specialization->startDefinition();
6545 if (TUK == TUK_Friend) {
6546 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
6550 Friend->setAccess(AS_public);
6551 CurContext->addDecl(Friend);
6553 // Add the specialization into its lexical context, so that it can
6554 // be seen when iterating through the list of declarations in that
6555 // context. However, specializations are not found by name lookup.
6556 CurContext->addDecl(Specialization);
6558 return Specialization;
6561 Decl *Sema::ActOnTemplateDeclarator(Scope *S,
6562 MultiTemplateParamsArg TemplateParameterLists,
6564 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
6565 ActOnDocumentableDecl(NewDecl);
6569 /// \brief Strips various properties off an implicit instantiation
6570 /// that has just been explicitly specialized.
6571 static void StripImplicitInstantiation(NamedDecl *D) {
6572 D->dropAttr<DLLImportAttr>();
6573 D->dropAttr<DLLExportAttr>();
6575 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
6576 FD->setInlineSpecified(false);
6579 /// \brief Compute the diagnostic location for an explicit instantiation
6580 // declaration or definition.
6581 static SourceLocation DiagLocForExplicitInstantiation(
6582 NamedDecl* D, SourceLocation PointOfInstantiation) {
6583 // Explicit instantiations following a specialization have no effect and
6584 // hence no PointOfInstantiation. In that case, walk decl backwards
6585 // until a valid name loc is found.
6586 SourceLocation PrevDiagLoc = PointOfInstantiation;
6587 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
6588 Prev = Prev->getPreviousDecl()) {
6589 PrevDiagLoc = Prev->getLocation();
6591 assert(PrevDiagLoc.isValid() &&
6592 "Explicit instantiation without point of instantiation?");
6596 /// \brief Diagnose cases where we have an explicit template specialization
6597 /// before/after an explicit template instantiation, producing diagnostics
6598 /// for those cases where they are required and determining whether the
6599 /// new specialization/instantiation will have any effect.
6601 /// \param NewLoc the location of the new explicit specialization or
6604 /// \param NewTSK the kind of the new explicit specialization or instantiation.
6606 /// \param PrevDecl the previous declaration of the entity.
6608 /// \param PrevTSK the kind of the old explicit specialization or instantiatin.
6610 /// \param PrevPointOfInstantiation if valid, indicates where the previus
6611 /// declaration was instantiated (either implicitly or explicitly).
6613 /// \param HasNoEffect will be set to true to indicate that the new
6614 /// specialization or instantiation has no effect and should be ignored.
6616 /// \returns true if there was an error that should prevent the introduction of
6617 /// the new declaration into the AST, false otherwise.
6619 Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6620 TemplateSpecializationKind NewTSK,
6621 NamedDecl *PrevDecl,
6622 TemplateSpecializationKind PrevTSK,
6623 SourceLocation PrevPointOfInstantiation,
6624 bool &HasNoEffect) {
6625 HasNoEffect = false;
6628 case TSK_Undeclared:
6629 case TSK_ImplicitInstantiation:
6631 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
6632 "previous declaration must be implicit!");
6635 case TSK_ExplicitSpecialization:
6637 case TSK_Undeclared:
6638 case TSK_ExplicitSpecialization:
6639 // Okay, we're just specializing something that is either already
6640 // explicitly specialized or has merely been mentioned without any
6644 case TSK_ImplicitInstantiation:
6645 if (PrevPointOfInstantiation.isInvalid()) {
6646 // The declaration itself has not actually been instantiated, so it is
6647 // still okay to specialize it.
6648 StripImplicitInstantiation(PrevDecl);
6653 case TSK_ExplicitInstantiationDeclaration:
6654 case TSK_ExplicitInstantiationDefinition:
6655 assert((PrevTSK == TSK_ImplicitInstantiation ||
6656 PrevPointOfInstantiation.isValid()) &&
6657 "Explicit instantiation without point of instantiation?");
6659 // C++ [temp.expl.spec]p6:
6660 // If a template, a member template or the member of a class template
6661 // is explicitly specialized then that specialization shall be declared
6662 // before the first use of that specialization that would cause an
6663 // implicit instantiation to take place, in every translation unit in
6664 // which such a use occurs; no diagnostic is required.
6665 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
6666 // Is there any previous explicit specialization declaration?
6667 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
6671 Diag(NewLoc, diag::err_specialization_after_instantiation)
6673 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
6674 << (PrevTSK != TSK_ImplicitInstantiation);
6679 case TSK_ExplicitInstantiationDeclaration:
6681 case TSK_ExplicitInstantiationDeclaration:
6682 // This explicit instantiation declaration is redundant (that's okay).
6686 case TSK_Undeclared:
6687 case TSK_ImplicitInstantiation:
6688 // We're explicitly instantiating something that may have already been
6689 // implicitly instantiated; that's fine.
6692 case TSK_ExplicitSpecialization:
6693 // C++0x [temp.explicit]p4:
6694 // For a given set of template parameters, if an explicit instantiation
6695 // of a template appears after a declaration of an explicit
6696 // specialization for that template, the explicit instantiation has no
6701 case TSK_ExplicitInstantiationDefinition:
6702 // C++0x [temp.explicit]p10:
6703 // If an entity is the subject of both an explicit instantiation
6704 // declaration and an explicit instantiation definition in the same
6705 // translation unit, the definition shall follow the declaration.
6707 diag::err_explicit_instantiation_declaration_after_definition);
6709 // Explicit instantiations following a specialization have no effect and
6710 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
6711 // until a valid name loc is found.
6712 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6713 diag::note_explicit_instantiation_definition_here);
6718 case TSK_ExplicitInstantiationDefinition:
6720 case TSK_Undeclared:
6721 case TSK_ImplicitInstantiation:
6722 // We're explicitly instantiating something that may have already been
6723 // implicitly instantiated; that's fine.
6726 case TSK_ExplicitSpecialization:
6727 // C++ DR 259, C++0x [temp.explicit]p4:
6728 // For a given set of template parameters, if an explicit
6729 // instantiation of a template appears after a declaration of
6730 // an explicit specialization for that template, the explicit
6731 // instantiation has no effect.
6733 // In C++98/03 mode, we only give an extension warning here, because it
6734 // is not harmful to try to explicitly instantiate something that
6735 // has been explicitly specialized.
6736 Diag(NewLoc, getLangOpts().CPlusPlus11 ?
6737 diag::warn_cxx98_compat_explicit_instantiation_after_specialization :
6738 diag::ext_explicit_instantiation_after_specialization)
6740 Diag(PrevDecl->getLocation(),
6741 diag::note_previous_template_specialization);
6745 case TSK_ExplicitInstantiationDeclaration:
6746 // We're explicity instantiating a definition for something for which we
6747 // were previously asked to suppress instantiations. That's fine.
6749 // C++0x [temp.explicit]p4:
6750 // For a given set of template parameters, if an explicit instantiation
6751 // of a template appears after a declaration of an explicit
6752 // specialization for that template, the explicit instantiation has no
6754 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
6755 // Is there any previous explicit specialization declaration?
6756 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6764 case TSK_ExplicitInstantiationDefinition:
6765 // C++0x [temp.spec]p5:
6766 // For a given template and a given set of template-arguments,
6767 // - an explicit instantiation definition shall appear at most once
6770 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
6771 Diag(NewLoc, (getLangOpts().MSVCCompat)
6772 ? diag::ext_explicit_instantiation_duplicate
6773 : diag::err_explicit_instantiation_duplicate)
6775 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6776 diag::note_previous_explicit_instantiation);
6782 llvm_unreachable("Missing specialization/instantiation case?");
6785 /// \brief Perform semantic analysis for the given dependent function
6786 /// template specialization.
6788 /// The only possible way to get a dependent function template specialization
6789 /// is with a friend declaration, like so:
6792 /// template \<class T> void foo(T);
6793 /// template \<class T> class A {
6794 /// friend void foo<>(T);
6798 /// There really isn't any useful analysis we can do here, so we
6799 /// just store the information.
6801 Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6802 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6803 LookupResult &Previous) {
6804 // Remove anything from Previous that isn't a function template in
6805 // the correct context.
6806 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
6807 LookupResult::Filter F = Previous.makeFilter();
6808 while (F.hasNext()) {
6809 NamedDecl *D = F.next()->getUnderlyingDecl();
6810 if (!isa<FunctionTemplateDecl>(D) ||
6811 !FDLookupContext->InEnclosingNamespaceSetOf(
6812 D->getDeclContext()->getRedeclContext()))
6817 // Should this be diagnosed here?
6818 if (Previous.empty()) return true;
6820 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
6821 ExplicitTemplateArgs);
6825 /// \brief Perform semantic analysis for the given function template
6828 /// This routine performs all of the semantic analysis required for an
6829 /// explicit function template specialization. On successful completion,
6830 /// the function declaration \p FD will become a function template
6833 /// \param FD the function declaration, which will be updated to become a
6834 /// function template specialization.
6836 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
6837 /// if any. Note that this may be valid info even when 0 arguments are
6838 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
6839 /// as it anyway contains info on the angle brackets locations.
6841 /// \param Previous the set of declarations that may be specialized by
6842 /// this function specialization.
6843 bool Sema::CheckFunctionTemplateSpecialization(
6844 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
6845 LookupResult &Previous) {
6846 // The set of function template specializations that could match this
6847 // explicit function template specialization.
6848 UnresolvedSet<8> Candidates;
6849 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
6850 /*ForTakingAddress=*/false);
6852 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
6853 ConvertedTemplateArgs;
6855 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
6856 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6858 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
6859 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
6860 // Only consider templates found within the same semantic lookup scope as
6862 if (!FDLookupContext->InEnclosingNamespaceSetOf(
6863 Ovl->getDeclContext()->getRedeclContext()))
6866 // When matching a constexpr member function template specialization
6867 // against the primary template, we don't yet know whether the
6868 // specialization has an implicit 'const' (because we don't know whether
6869 // it will be a static member function until we know which template it
6870 // specializes), so adjust it now assuming it specializes this template.
6871 QualType FT = FD->getType();
6872 if (FD->isConstexpr()) {
6873 CXXMethodDecl *OldMD =
6874 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
6875 if (OldMD && OldMD->isConst()) {
6876 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
6877 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6878 EPI.TypeQuals |= Qualifiers::Const;
6879 FT = Context.getFunctionType(FPT->getReturnType(),
6880 FPT->getParamTypes(), EPI);
6884 TemplateArgumentListInfo Args;
6885 if (ExplicitTemplateArgs)
6886 Args = *ExplicitTemplateArgs;
6888 // C++ [temp.expl.spec]p11:
6889 // A trailing template-argument can be left unspecified in the
6890 // template-id naming an explicit function template specialization
6891 // provided it can be deduced from the function argument type.
6892 // Perform template argument deduction to determine whether we may be
6893 // specializing this template.
6894 // FIXME: It is somewhat wasteful to build
6895 TemplateDeductionInfo Info(FailedCandidates.getLocation());
6896 FunctionDecl *Specialization = nullptr;
6897 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
6898 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
6899 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
6901 // Template argument deduction failed; record why it failed, so
6902 // that we can provide nifty diagnostics.
6903 FailedCandidates.addCandidate().set(
6904 I.getPair(), FunTmpl->getTemplatedDecl(),
6905 MakeDeductionFailureInfo(Context, TDK, Info));
6910 // Record this candidate.
6911 if (ExplicitTemplateArgs)
6912 ConvertedTemplateArgs[Specialization] = std::move(Args);
6913 Candidates.addDecl(Specialization, I.getAccess());
6917 // Find the most specialized function template.
6918 UnresolvedSetIterator Result = getMostSpecialized(
6919 Candidates.begin(), Candidates.end(), FailedCandidates,
6921 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
6922 PDiag(diag::err_function_template_spec_ambiguous)
6923 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
6924 PDiag(diag::note_function_template_spec_matched));
6926 if (Result == Candidates.end())
6929 // Ignore access information; it doesn't figure into redeclaration checking.
6930 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
6932 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
6933 // an explicit specialization (14.8.3) [...] of a concept definition.
6934 if (Specialization->getPrimaryTemplate()->isConcept()) {
6935 Diag(FD->getLocation(), diag::err_concept_specialized)
6936 << 0 /*function*/ << 1 /*explicitly specialized*/;
6937 Diag(Specialization->getLocation(), diag::note_previous_declaration);
6941 FunctionTemplateSpecializationInfo *SpecInfo
6942 = Specialization->getTemplateSpecializationInfo();
6943 assert(SpecInfo && "Function template specialization info missing?");
6945 // Note: do not overwrite location info if previous template
6946 // specialization kind was explicit.
6947 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
6948 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
6949 Specialization->setLocation(FD->getLocation());
6950 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
6951 // function can differ from the template declaration with respect to
6952 // the constexpr specifier.
6953 Specialization->setConstexpr(FD->isConstexpr());
6956 // FIXME: Check if the prior specialization has a point of instantiation.
6957 // If so, we have run afoul of .
6959 // If this is a friend declaration, then we're not really declaring
6960 // an explicit specialization.
6961 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
6963 // Check the scope of this explicit specialization.
6965 CheckTemplateSpecializationScope(*this,
6966 Specialization->getPrimaryTemplate(),
6967 Specialization, FD->getLocation(),
6971 // C++ [temp.expl.spec]p6:
6972 // If a template, a member template or the member of a class template is
6973 // explicitly specialized then that specialization shall be declared
6974 // before the first use of that specialization that would cause an implicit
6975 // instantiation to take place, in every translation unit in which such a
6976 // use occurs; no diagnostic is required.
6977 bool HasNoEffect = false;
6979 CheckSpecializationInstantiationRedecl(FD->getLocation(),
6980 TSK_ExplicitSpecialization,
6982 SpecInfo->getTemplateSpecializationKind(),
6983 SpecInfo->getPointOfInstantiation(),
6987 // Mark the prior declaration as an explicit specialization, so that later
6988 // clients know that this is an explicit specialization.
6990 // Explicit specializations do not inherit '=delete' from their primary
\r
6991 // function template.
\r
6992 if (Specialization->isDeleted()) {
\r
6993 assert(!SpecInfo->isExplicitSpecialization());
\r
6994 assert(Specialization->getCanonicalDecl() == Specialization);
\r
6995 Specialization->setDeletedAsWritten(false);
\r
6997 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
6998 MarkUnusedFileScopedDecl(Specialization);
7001 // Turn the given function declaration into a function template
7002 // specialization, with the template arguments from the previous
7004 // Take copies of (semantic and syntactic) template argument lists.
7005 const TemplateArgumentList* TemplArgs = new (Context)
7006 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
7007 FD->setFunctionTemplateSpecialization(
7008 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
7009 SpecInfo->getTemplateSpecializationKind(),
7010 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
7012 // The "previous declaration" for this function template specialization is
7013 // the prior function template specialization.
7015 Previous.addDecl(Specialization);
7019 /// \brief Perform semantic analysis for the given non-template member
7022 /// This routine performs all of the semantic analysis required for an
7023 /// explicit member function specialization. On successful completion,
7024 /// the function declaration \p FD will become a member function
7027 /// \param Member the member declaration, which will be updated to become a
7030 /// \param Previous the set of declarations, one of which may be specialized
7031 /// by this function specialization; the set will be modified to contain the
7032 /// redeclared member.
7034 Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
7035 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
7037 // Try to find the member we are instantiating.
7038 NamedDecl *FoundInstantiation = nullptr;
7039 NamedDecl *Instantiation = nullptr;
7040 NamedDecl *InstantiatedFrom = nullptr;
7041 MemberSpecializationInfo *MSInfo = nullptr;
7043 if (Previous.empty()) {
7044 // Nowhere to look anyway.
7045 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
7046 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7048 NamedDecl *D = (*I)->getUnderlyingDecl();
7049 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
7050 QualType Adjusted = Function->getType();
7051 if (!hasExplicitCallingConv(Adjusted))
7052 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
7053 if (Context.hasSameType(Adjusted, Method->getType())) {
7054 FoundInstantiation = *I;
7055 Instantiation = Method;
7056 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
7057 MSInfo = Method->getMemberSpecializationInfo();
7062 } else if (isa<VarDecl>(Member)) {
7064 if (Previous.isSingleResult() &&
7065 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
7066 if (PrevVar->isStaticDataMember()) {
7067 FoundInstantiation = Previous.getRepresentativeDecl();
7068 Instantiation = PrevVar;
7069 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
7070 MSInfo = PrevVar->getMemberSpecializationInfo();
7072 } else if (isa<RecordDecl>(Member)) {
7073 CXXRecordDecl *PrevRecord;
7074 if (Previous.isSingleResult() &&
7075 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
7076 FoundInstantiation = Previous.getRepresentativeDecl();
7077 Instantiation = PrevRecord;
7078 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
7079 MSInfo = PrevRecord->getMemberSpecializationInfo();
7081 } else if (isa<EnumDecl>(Member)) {
7083 if (Previous.isSingleResult() &&
7084 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
7085 FoundInstantiation = Previous.getRepresentativeDecl();
7086 Instantiation = PrevEnum;
7087 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
7088 MSInfo = PrevEnum->getMemberSpecializationInfo();
7092 if (!Instantiation) {
7093 // There is no previous declaration that matches. Since member
7094 // specializations are always out-of-line, the caller will complain about
7095 // this mismatch later.
7099 // If this is a friend, just bail out here before we start turning
7100 // things into explicit specializations.
7101 if (Member->getFriendObjectKind() != Decl::FOK_None) {
7102 // Preserve instantiation information.
7103 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
7104 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
7105 cast<CXXMethodDecl>(InstantiatedFrom),
7106 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
7107 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
7108 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
7109 cast<CXXRecordDecl>(InstantiatedFrom),
7110 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
7114 Previous.addDecl(FoundInstantiation);
7118 // Make sure that this is a specialization of a member.
7119 if (!InstantiatedFrom) {
7120 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
7122 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
7126 // C++ [temp.expl.spec]p6:
7127 // If a template, a member template or the member of a class template is
7128 // explicitly specialized then that specialization shall be declared
7129 // before the first use of that specialization that would cause an implicit
7130 // instantiation to take place, in every translation unit in which such a
7131 // use occurs; no diagnostic is required.
7132 assert(MSInfo && "Member specialization info missing?");
7134 bool HasNoEffect = false;
7135 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
7136 TSK_ExplicitSpecialization,
7138 MSInfo->getTemplateSpecializationKind(),
7139 MSInfo->getPointOfInstantiation(),
7143 // Check the scope of this explicit specialization.
7144 if (CheckTemplateSpecializationScope(*this,
7146 Instantiation, Member->getLocation(),
7150 // Note that this is an explicit instantiation of a member.
7151 // the original declaration to note that it is an explicit specialization
7152 // (if it was previously an implicit instantiation). This latter step
7153 // makes bookkeeping easier.
7154 if (isa<FunctionDecl>(Member)) {
7155 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
7156 if (InstantiationFunction->getTemplateSpecializationKind() ==
7157 TSK_ImplicitInstantiation) {
7158 InstantiationFunction->setTemplateSpecializationKind(
7159 TSK_ExplicitSpecialization);
7160 InstantiationFunction->setLocation(Member->getLocation());
7161 // Explicit specializations of member functions of class templates do not
7162 // inherit '=delete' from the member function they are specializing.
7163 if (InstantiationFunction->isDeleted()) {
7164 assert(InstantiationFunction->getCanonicalDecl() ==
7165 InstantiationFunction);
7166 InstantiationFunction->setDeletedAsWritten(false);
\r
7170 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
7171 cast<CXXMethodDecl>(InstantiatedFrom),
7172 TSK_ExplicitSpecialization);
7173 MarkUnusedFileScopedDecl(InstantiationFunction);
7174 } else if (isa<VarDecl>(Member)) {
7175 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
7176 if (InstantiationVar->getTemplateSpecializationKind() ==
7177 TSK_ImplicitInstantiation) {
7178 InstantiationVar->setTemplateSpecializationKind(
7179 TSK_ExplicitSpecialization);
7180 InstantiationVar->setLocation(Member->getLocation());
7183 cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
7184 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
7185 MarkUnusedFileScopedDecl(InstantiationVar);
7186 } else if (isa<CXXRecordDecl>(Member)) {
7187 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
7188 if (InstantiationClass->getTemplateSpecializationKind() ==
7189 TSK_ImplicitInstantiation) {
7190 InstantiationClass->setTemplateSpecializationKind(
7191 TSK_ExplicitSpecialization);
7192 InstantiationClass->setLocation(Member->getLocation());
7195 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
7196 cast<CXXRecordDecl>(InstantiatedFrom),
7197 TSK_ExplicitSpecialization);
7199 assert(isa<EnumDecl>(Member) && "Only member enums remain");
7200 EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
7201 if (InstantiationEnum->getTemplateSpecializationKind() ==
7202 TSK_ImplicitInstantiation) {
7203 InstantiationEnum->setTemplateSpecializationKind(
7204 TSK_ExplicitSpecialization);
7205 InstantiationEnum->setLocation(Member->getLocation());
7208 cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
7209 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
7212 // Save the caller the trouble of having to figure out which declaration
7213 // this specialization matches.
7215 Previous.addDecl(FoundInstantiation);
7219 /// \brief Check the scope of an explicit instantiation.
7221 /// \returns true if a serious error occurs, false otherwise.
7222 static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
7223 SourceLocation InstLoc,
7224 bool WasQualifiedName) {
7225 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
7226 DeclContext *CurContext = S.CurContext->getRedeclContext();
7228 if (CurContext->isRecord()) {
7229 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
7234 // C++11 [temp.explicit]p3:
7235 // An explicit instantiation shall appear in an enclosing namespace of its
7236 // template. If the name declared in the explicit instantiation is an
7237 // unqualified name, the explicit instantiation shall appear in the
7238 // namespace where its template is declared or, if that namespace is inline
7239 // (7.3.1), any namespace from its enclosing namespace set.
7241 // This is DR275, which we do not retroactively apply to C++98/03.
7242 if (WasQualifiedName) {
7243 if (CurContext->Encloses(OrigContext))
7246 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
7250 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
7251 if (WasQualifiedName)
7253 S.getLangOpts().CPlusPlus11?
7254 diag::err_explicit_instantiation_out_of_scope :
7255 diag::warn_explicit_instantiation_out_of_scope_0x)
7259 S.getLangOpts().CPlusPlus11?
7260 diag::err_explicit_instantiation_unqualified_wrong_namespace :
7261 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
7265 S.getLangOpts().CPlusPlus11?
7266 diag::err_explicit_instantiation_must_be_global :
7267 diag::warn_explicit_instantiation_must_be_global_0x)
7269 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
7273 /// \brief Determine whether the given scope specifier has a template-id in it.
7274 static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
7278 // C++11 [temp.explicit]p3:
7279 // If the explicit instantiation is for a member function, a member class
7280 // or a static data member of a class template specialization, the name of
7281 // the class template specialization in the qualified-id for the member
7282 // name shall be a simple-template-id.
7284 // C++98 has the same restriction, just worded differently.
7285 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
7286 NNS = NNS->getPrefix())
7287 if (const Type *T = NNS->getAsType())
7288 if (isa<TemplateSpecializationType>(T))
7294 // Explicit instantiation of a class template specialization
7296 Sema::ActOnExplicitInstantiation(Scope *S,
7297 SourceLocation ExternLoc,
7298 SourceLocation TemplateLoc,
7300 SourceLocation KWLoc,
7301 const CXXScopeSpec &SS,
7302 TemplateTy TemplateD,
7303 SourceLocation TemplateNameLoc,
7304 SourceLocation LAngleLoc,
7305 ASTTemplateArgsPtr TemplateArgsIn,
7306 SourceLocation RAngleLoc,
7307 AttributeList *Attr) {
7308 // Find the class template we're specializing
7309 TemplateName Name = TemplateD.get();
7310 TemplateDecl *TD = Name.getAsTemplateDecl();
7311 // Check that the specialization uses the same tag kind as the
7312 // original template.
7313 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7314 assert(Kind != TTK_Enum &&
7315 "Invalid enum tag in class template explicit instantiation!");
7317 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
7319 if (!ClassTemplate) {
7320 unsigned ErrorKind = 0;
7321 if (isa<TypeAliasTemplateDecl>(TD)) {
7323 } else if (isa<TemplateTemplateParmDecl>(TD)) {
7327 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << ErrorKind;
7328 Diag(TD->getLocation(), diag::note_previous_use);
7332 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
7333 Kind, /*isDefinition*/false, KWLoc,
7334 ClassTemplate->getIdentifier())) {
7335 Diag(KWLoc, diag::err_use_with_wrong_tag)
7337 << FixItHint::CreateReplacement(KWLoc,
7338 ClassTemplate->getTemplatedDecl()->getKindName());
7339 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
7340 diag::note_previous_use);
7341 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7344 // C++0x [temp.explicit]p2:
7345 // There are two forms of explicit instantiation: an explicit instantiation
7346 // definition and an explicit instantiation declaration. An explicit
7347 // instantiation declaration begins with the extern keyword. [...]
7348 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
7349 ? TSK_ExplicitInstantiationDefinition
7350 : TSK_ExplicitInstantiationDeclaration;
7352 if (TSK == TSK_ExplicitInstantiationDeclaration) {
7353 // Check for dllexport class template instantiation declarations.
7354 for (AttributeList *A = Attr; A; A = A->getNext()) {
7355 if (A->getKind() == AttributeList::AT_DLLExport) {
7357 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7358 Diag(A->getLoc(), diag::note_attribute);
7363 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
7365 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7366 Diag(A->getLocation(), diag::note_attribute);
7370 // In MSVC mode, dllimported explicit instantiation definitions are treated as
7371 // instantiation declarations for most purposes.
7372 bool DLLImportExplicitInstantiationDef = false;
7373 if (TSK == TSK_ExplicitInstantiationDefinition &&
7374 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7375 // Check for dllimport class template instantiation definitions.
7377 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
7378 for (AttributeList *A = Attr; A; A = A->getNext()) {
7379 if (A->getKind() == AttributeList::AT_DLLImport)
7381 if (A->getKind() == AttributeList::AT_DLLExport) {
7382 // dllexport trumps dllimport here.
7388 TSK = TSK_ExplicitInstantiationDeclaration;
7389 DLLImportExplicitInstantiationDef = true;
7393 // Translate the parser's template argument list in our AST format.
7394 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
7395 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
7397 // Check that the template argument list is well-formed for this
7399 SmallVector<TemplateArgument, 4> Converted;
7400 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7401 TemplateArgs, false, Converted))
7404 // Find the class template specialization declaration that
7405 // corresponds to these arguments.
7406 void *InsertPos = nullptr;
7407 ClassTemplateSpecializationDecl *PrevDecl
7408 = ClassTemplate->findSpecialization(Converted, InsertPos);
7410 TemplateSpecializationKind PrevDecl_TSK
7411 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
7413 // C++0x [temp.explicit]p2:
7414 // [...] An explicit instantiation shall appear in an enclosing
7415 // namespace of its template. [...]
7417 // This is C++ DR 275.
7418 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
7422 ClassTemplateSpecializationDecl *Specialization = nullptr;
7424 bool HasNoEffect = false;
7426 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
7427 PrevDecl, PrevDecl_TSK,
7428 PrevDecl->getPointOfInstantiation(),
7432 // Even though HasNoEffect == true means that this explicit instantiation
7433 // has no effect on semantics, we go on to put its syntax in the AST.
7435 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
7436 PrevDecl_TSK == TSK_Undeclared) {
7437 // Since the only prior class template specialization with these
7438 // arguments was referenced but not declared, reuse that
7439 // declaration node as our own, updating the source location
7440 // for the template name to reflect our new declaration.
7441 // (Other source locations will be updated later.)
7442 Specialization = PrevDecl;
7443 Specialization->setLocation(TemplateNameLoc);
7447 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
7448 DLLImportExplicitInstantiationDef) {
7449 // The new specialization might add a dllimport attribute.
7450 HasNoEffect = false;
7454 if (!Specialization) {
7455 // Create a new class template specialization declaration node for
7456 // this explicit specialization.
7458 = ClassTemplateSpecializationDecl::Create(Context, Kind,
7459 ClassTemplate->getDeclContext(),
7460 KWLoc, TemplateNameLoc,
7465 SetNestedNameSpecifier(Specialization, SS);
7467 if (!HasNoEffect && !PrevDecl) {
7468 // Insert the new specialization.
7469 ClassTemplate->AddSpecialization(Specialization, InsertPos);
7473 // Build the fully-sugared type for this explicit instantiation as
7474 // the user wrote in the explicit instantiation itself. This means
7475 // that we'll pretty-print the type retrieved from the
7476 // specialization's declaration the way that the user actually wrote
7477 // the explicit instantiation, rather than formatting the name based
7478 // on the "canonical" representation used to store the template
7479 // arguments in the specialization.
7480 TypeSourceInfo *WrittenTy
7481 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7483 Context.getTypeDeclType(Specialization));
7484 Specialization->setTypeAsWritten(WrittenTy);
7486 // Set source locations for keywords.
7487 Specialization->setExternLoc(ExternLoc);
7488 Specialization->setTemplateKeywordLoc(TemplateLoc);
7489 Specialization->setRBraceLoc(SourceLocation());
7492 ProcessDeclAttributeList(S, Specialization, Attr);
7494 // Add the explicit instantiation into its lexical context. However,
7495 // since explicit instantiations are never found by name lookup, we
7496 // just put it into the declaration context directly.
7497 Specialization->setLexicalDeclContext(CurContext);
7498 CurContext->addDecl(Specialization);
7500 // Syntax is now OK, so return if it has no other effect on semantics.
7502 // Set the template specialization kind.
7503 Specialization->setTemplateSpecializationKind(TSK);
7504 return Specialization;
7507 // C++ [temp.explicit]p3:
7508 // A definition of a class template or class member template
7509 // shall be in scope at the point of the explicit instantiation of
7510 // the class template or class member template.
7512 // This check comes when we actually try to perform the
7514 ClassTemplateSpecializationDecl *Def
7515 = cast_or_null<ClassTemplateSpecializationDecl>(
7516 Specialization->getDefinition());
7518 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
7519 else if (TSK == TSK_ExplicitInstantiationDefinition) {
7520 MarkVTableUsed(TemplateNameLoc, Specialization, true);
7521 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
7524 // Instantiate the members of this class template specialization.
7525 Def = cast_or_null<ClassTemplateSpecializationDecl>(
7526 Specialization->getDefinition());
7528 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
7529 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
7530 // TSK_ExplicitInstantiationDefinition
7531 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
7532 (TSK == TSK_ExplicitInstantiationDefinition ||
7533 DLLImportExplicitInstantiationDef)) {
7534 // FIXME: Need to notify the ASTMutationListener that we did this.
7535 Def->setTemplateSpecializationKind(TSK);
7537 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
7538 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7539 // In the MS ABI, an explicit instantiation definition can add a dll
7540 // attribute to a template with a previous instantiation declaration.
7541 // MinGW doesn't allow this.
7542 auto *A = cast<InheritableAttr>(
7543 getDLLAttr(Specialization)->clone(getASTContext()));
7544 A->setInherited(true);
7547 // We reject explicit instantiations in class scope, so there should
7548 // never be any delayed exported classes to worry about.
7549 assert(DelayedDllExportClasses.empty() &&
7550 "delayed exports present at explicit instantiation");
7551 checkClassLevelDLLAttribute(Def);
7552 referenceDLLExportedClassMethods();
7554 // Propagate attribute to base class templates.
7555 for (auto &B : Def->bases()) {
7556 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
7557 B.getType()->getAsCXXRecordDecl()))
7558 propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getLocStart());
7563 // Set the template specialization kind. Make sure it is set before
7564 // instantiating the members which will trigger ASTConsumer callbacks.
7565 Specialization->setTemplateSpecializationKind(TSK);
7566 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
7569 // Set the template specialization kind.
7570 Specialization->setTemplateSpecializationKind(TSK);
7573 return Specialization;
7576 // Explicit instantiation of a member class of a class template.
7578 Sema::ActOnExplicitInstantiation(Scope *S,
7579 SourceLocation ExternLoc,
7580 SourceLocation TemplateLoc,
7582 SourceLocation KWLoc,
7584 IdentifierInfo *Name,
7585 SourceLocation NameLoc,
7586 AttributeList *Attr) {
7589 bool IsDependent = false;
7590 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
7591 KWLoc, SS, Name, NameLoc, Attr, AS_none,
7592 /*ModulePrivateLoc=*/SourceLocation(),
7593 MultiTemplateParamsArg(), Owned, IsDependent,
7594 SourceLocation(), false, TypeResult(),
7595 /*IsTypeSpecifier*/false);
7596 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
7601 TagDecl *Tag = cast<TagDecl>(TagD);
7602 assert(!Tag->isEnum() && "shouldn't see enumerations here");
7604 if (Tag->isInvalidDecl())
7607 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
7608 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
7610 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
7611 << Context.getTypeDeclType(Record);
7612 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
7616 // C++0x [temp.explicit]p2:
7617 // If the explicit instantiation is for a class or member class, the
7618 // elaborated-type-specifier in the declaration shall include a
7619 // simple-template-id.
7621 // C++98 has the same restriction, just worded differently.
7622 if (!ScopeSpecifierHasTemplateId(SS))
7623 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
7624 << Record << SS.getRange();
7626 // C++0x [temp.explicit]p2:
7627 // There are two forms of explicit instantiation: an explicit instantiation
7628 // definition and an explicit instantiation declaration. An explicit
7629 // instantiation declaration begins with the extern keyword. [...]
7630 TemplateSpecializationKind TSK
7631 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7632 : TSK_ExplicitInstantiationDeclaration;
7634 // C++0x [temp.explicit]p2:
7635 // [...] An explicit instantiation shall appear in an enclosing
7636 // namespace of its template. [...]
7638 // This is C++ DR 275.
7639 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
7641 // Verify that it is okay to explicitly instantiate here.
7642 CXXRecordDecl *PrevDecl
7643 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
7644 if (!PrevDecl && Record->getDefinition())
7647 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
7648 bool HasNoEffect = false;
7649 assert(MSInfo && "No member specialization information?");
7650 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
7652 MSInfo->getTemplateSpecializationKind(),
7653 MSInfo->getPointOfInstantiation(),
7660 CXXRecordDecl *RecordDef
7661 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
7663 // C++ [temp.explicit]p3:
7664 // A definition of a member class of a class template shall be in scope
7665 // at the point of an explicit instantiation of the member class.
7667 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
7669 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
7670 << 0 << Record->getDeclName() << Record->getDeclContext();
7671 Diag(Pattern->getLocation(), diag::note_forward_declaration)
7675 if (InstantiateClass(NameLoc, Record, Def,
7676 getTemplateInstantiationArgs(Record),
7680 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
7686 // Instantiate all of the members of the class.
7687 InstantiateClassMembers(NameLoc, RecordDef,
7688 getTemplateInstantiationArgs(Record), TSK);
7690 if (TSK == TSK_ExplicitInstantiationDefinition)
7691 MarkVTableUsed(NameLoc, RecordDef, true);
7693 // FIXME: We don't have any representation for explicit instantiations of
7694 // member classes. Such a representation is not needed for compilation, but it
7695 // should be available for clients that want to see all of the declarations in
7700 DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
7701 SourceLocation ExternLoc,
7702 SourceLocation TemplateLoc,
7704 // Explicit instantiations always require a name.
7705 // TODO: check if/when DNInfo should replace Name.
7706 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7707 DeclarationName Name = NameInfo.getName();
7709 if (!D.isInvalidType())
7710 Diag(D.getDeclSpec().getLocStart(),
7711 diag::err_explicit_instantiation_requires_name)
7712 << D.getDeclSpec().getSourceRange()
7713 << D.getSourceRange();
7718 // The scope passed in may not be a decl scope. Zip up the scope tree until
7719 // we find one that is.
7720 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7721 (S->getFlags() & Scope::TemplateParamScope) != 0)
7724 // Determine the type of the declaration.
7725 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
7726 QualType R = T->getType();
7731 // A storage-class-specifier shall not be specified in [...] an explicit
7732 // instantiation (14.7.2) directive.
7733 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
7734 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
7737 } else if (D.getDeclSpec().getStorageClassSpec()
7738 != DeclSpec::SCS_unspecified) {
7739 // Complain about then remove the storage class specifier.
7740 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
7741 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7743 D.getMutableDeclSpec().ClearStorageClassSpecs();
7746 // C++0x [temp.explicit]p1:
7747 // [...] An explicit instantiation of a function template shall not use the
7748 // inline or constexpr specifiers.
7749 // Presumably, this also applies to member functions of class templates as
7751 if (D.getDeclSpec().isInlineSpecified())
7752 Diag(D.getDeclSpec().getInlineSpecLoc(),
7753 getLangOpts().CPlusPlus11 ?
7754 diag::err_explicit_instantiation_inline :
7755 diag::warn_explicit_instantiation_inline_0x)
7756 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7757 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
7758 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
7759 // not already specified.
7760 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7761 diag::err_explicit_instantiation_constexpr);
7763 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7764 // applied only to the definition of a function template or variable template,
7765 // declared in namespace scope.
7766 if (D.getDeclSpec().isConceptSpecified()) {
7767 Diag(D.getDeclSpec().getConceptSpecLoc(),
7768 diag::err_concept_specified_specialization) << 0;
7772 // C++0x [temp.explicit]p2:
7773 // There are two forms of explicit instantiation: an explicit instantiation
7774 // definition and an explicit instantiation declaration. An explicit
7775 // instantiation declaration begins with the extern keyword. [...]
7776 TemplateSpecializationKind TSK
7777 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7778 : TSK_ExplicitInstantiationDeclaration;
7780 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
7781 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
7783 if (!R->isFunctionType()) {
7784 // C++ [temp.explicit]p1:
7785 // A [...] static data member of a class template can be explicitly
7786 // instantiated from the member definition associated with its class
7788 // C++1y [temp.explicit]p1:
7789 // A [...] variable [...] template specialization can be explicitly
7790 // instantiated from its template.
7791 if (Previous.isAmbiguous())
7794 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
7795 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
7797 if (!PrevTemplate) {
7798 if (!Prev || !Prev->isStaticDataMember()) {
7799 // We expect to see a data data member here.
7800 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
7802 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7804 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
7808 if (!Prev->getInstantiatedFromStaticDataMember()) {
7809 // FIXME: Check for explicit specialization?
7810 Diag(D.getIdentifierLoc(),
7811 diag::err_explicit_instantiation_data_member_not_instantiated)
7813 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
7814 // FIXME: Can we provide a note showing where this was declared?
7818 // Explicitly instantiate a variable template.
7820 // C++1y [dcl.spec.auto]p6:
7821 // ... A program that uses auto or decltype(auto) in a context not
7822 // explicitly allowed in this section is ill-formed.
7824 // This includes auto-typed variable template instantiations.
7825 if (R->isUndeducedType()) {
7826 Diag(T->getTypeLoc().getLocStart(),
7827 diag::err_auto_not_allowed_var_inst);
7831 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7832 // C++1y [temp.explicit]p3:
7833 // If the explicit instantiation is for a variable, the unqualified-id
7834 // in the declaration shall be a template-id.
7835 Diag(D.getIdentifierLoc(),
7836 diag::err_explicit_instantiation_without_template_id)
7838 Diag(PrevTemplate->getLocation(),
7839 diag::note_explicit_instantiation_here);
7843 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
7844 // explicit instantiation (14.8.2) [...] of a concept definition.
7845 if (PrevTemplate->isConcept()) {
7846 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
7847 << 1 /*variable*/ << 0 /*explicitly instantiated*/;
7848 Diag(PrevTemplate->getLocation(), diag::note_previous_declaration);
7852 // Translate the parser's template argument list into our AST format.
7853 TemplateArgumentListInfo TemplateArgs =
7854 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
7856 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
7857 D.getIdentifierLoc(), TemplateArgs);
7858 if (Res.isInvalid())
7861 // Ignore access control bits, we don't need them for redeclaration
7863 Prev = cast<VarDecl>(Res.get());
7866 // C++0x [temp.explicit]p2:
7867 // If the explicit instantiation is for a member function, a member class
7868 // or a static data member of a class template specialization, the name of
7869 // the class template specialization in the qualified-id for the member
7870 // name shall be a simple-template-id.
7872 // C++98 has the same restriction, just worded differently.
7874 // This does not apply to variable template specializations, where the
7875 // template-id is in the unqualified-id instead.
7876 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
7877 Diag(D.getIdentifierLoc(),
7878 diag::ext_explicit_instantiation_without_qualified_id)
7879 << Prev << D.getCXXScopeSpec().getRange();
7881 // Check the scope of this explicit instantiation.
7882 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
7884 // Verify that it is okay to explicitly instantiate here.
7885 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
7886 SourceLocation POI = Prev->getPointOfInstantiation();
7887 bool HasNoEffect = false;
7888 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
7889 PrevTSK, POI, HasNoEffect))
7893 // Instantiate static data member or variable template.
7895 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
7897 // Merge attributes.
7898 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
7899 ProcessDeclAttributeList(S, Prev, Attr);
7901 if (TSK == TSK_ExplicitInstantiationDefinition)
7902 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
7905 // Check the new variable specialization against the parsed input.
7906 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
7907 Diag(T->getTypeLoc().getLocStart(),
7908 diag::err_invalid_var_template_spec_type)
7909 << 0 << PrevTemplate << R << Prev->getType();
7910 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
7911 << 2 << PrevTemplate->getDeclName();
7915 // FIXME: Create an ExplicitInstantiation node?
7916 return (Decl*) nullptr;
7919 // If the declarator is a template-id, translate the parser's template
7920 // argument list into our AST format.
7921 bool HasExplicitTemplateArgs = false;
7922 TemplateArgumentListInfo TemplateArgs;
7923 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7924 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
7925 HasExplicitTemplateArgs = true;
7928 // C++ [temp.explicit]p1:
7929 // A [...] function [...] can be explicitly instantiated from its template.
7930 // A member function [...] of a class template can be explicitly
7931 // instantiated from the member definition associated with its class
7933 UnresolvedSet<8> Matches;
7934 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
7935 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7937 NamedDecl *Prev = *P;
7938 if (!HasExplicitTemplateArgs) {
7939 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
7940 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType());
7941 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
7944 Matches.addDecl(Method, P.getAccess());
7945 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
7951 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
7955 TemplateDeductionInfo Info(FailedCandidates.getLocation());
7956 FunctionDecl *Specialization = nullptr;
7957 if (TemplateDeductionResult TDK
7958 = DeduceTemplateArguments(FunTmpl,
7959 (HasExplicitTemplateArgs ? &TemplateArgs
7961 R, Specialization, Info)) {
7962 // Keep track of almost-matches.
7963 FailedCandidates.addCandidate()
7964 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
7965 MakeDeductionFailureInfo(Context, TDK, Info));
7970 Matches.addDecl(Specialization, P.getAccess());
7973 // Find the most specialized function template specialization.
7974 UnresolvedSetIterator Result = getMostSpecialized(
7975 Matches.begin(), Matches.end(), FailedCandidates,
7976 D.getIdentifierLoc(),
7977 PDiag(diag::err_explicit_instantiation_not_known) << Name,
7978 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
7979 PDiag(diag::note_explicit_instantiation_candidate));
7981 if (Result == Matches.end())
7984 // Ignore access control bits, we don't need them for redeclaration checking.
7985 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
7987 // C++11 [except.spec]p4
7988 // In an explicit instantiation an exception-specification may be specified,
7989 // but is not required.
7990 // If an exception-specification is specified in an explicit instantiation
7991 // directive, it shall be compatible with the exception-specifications of
7992 // other declarations of that function.
7993 if (auto *FPT = R->getAs<FunctionProtoType>())
7994 if (FPT->hasExceptionSpec()) {
7996 diag::err_mismatched_exception_spec_explicit_instantiation;
7997 if (getLangOpts().MicrosoftExt)
7998 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
7999 bool Result = CheckEquivalentExceptionSpec(
8000 PDiag(DiagID) << Specialization->getType(),
8001 PDiag(diag::note_explicit_instantiation_here),
8002 Specialization->getType()->getAs<FunctionProtoType>(),
8003 Specialization->getLocation(), FPT, D.getLocStart());
8004 // In Microsoft mode, mismatching exception specifications just cause a
8006 if (!getLangOpts().MicrosoftExt && Result)
8010 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
8011 Diag(D.getIdentifierLoc(),
8012 diag::err_explicit_instantiation_member_function_not_instantiated)
8014 << (Specialization->getTemplateSpecializationKind() ==
8015 TSK_ExplicitSpecialization);
8016 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
8020 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
8021 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
8022 PrevDecl = Specialization;
8025 bool HasNoEffect = false;
8026 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
8028 PrevDecl->getTemplateSpecializationKind(),
8029 PrevDecl->getPointOfInstantiation(),
8033 // FIXME: We may still want to build some representation of this
8034 // explicit specialization.
8036 return (Decl*) nullptr;
8039 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
8040 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
8042 ProcessDeclAttributeList(S, Specialization, Attr);
8044 if (Specialization->isDefined()) {
8045 // Let the ASTConsumer know that this function has been explicitly
8046 // instantiated now, and its linkage might have changed.
8047 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
8048 } else if (TSK == TSK_ExplicitInstantiationDefinition)
8049 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
8051 // C++0x [temp.explicit]p2:
8052 // If the explicit instantiation is for a member function, a member class
8053 // or a static data member of a class template specialization, the name of
8054 // the class template specialization in the qualified-id for the member
8055 // name shall be a simple-template-id.
8057 // C++98 has the same restriction, just worded differently.
8058 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
8059 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
8060 D.getCXXScopeSpec().isSet() &&
8061 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
8062 Diag(D.getIdentifierLoc(),
8063 diag::ext_explicit_instantiation_without_qualified_id)
8064 << Specialization << D.getCXXScopeSpec().getRange();
8066 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
8067 // explicit instantiation (14.8.2) [...] of a concept definition.
8068 if (FunTmpl && FunTmpl->isConcept() &&
8069 !D.getDeclSpec().isConceptSpecified()) {
8070 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
8071 << 0 /*function*/ << 0 /*explicitly instantiated*/;
8072 Diag(FunTmpl->getLocation(), diag::note_previous_declaration);
8076 CheckExplicitInstantiationScope(*this,
8077 FunTmpl? (NamedDecl *)FunTmpl
8078 : Specialization->getInstantiatedFromMemberFunction(),
8079 D.getIdentifierLoc(),
8080 D.getCXXScopeSpec().isSet());
8082 // FIXME: Create some kind of ExplicitInstantiationDecl here.
8083 return (Decl*) nullptr;
8087 Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
8088 const CXXScopeSpec &SS, IdentifierInfo *Name,
8089 SourceLocation TagLoc, SourceLocation NameLoc) {
8090 // This has to hold, because SS is expected to be defined.
8091 assert(Name && "Expected a name in a dependent tag");
8093 NestedNameSpecifier *NNS = SS.getScopeRep();
8097 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8099 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
8100 Diag(NameLoc, diag::err_dependent_tag_decl)
8101 << (TUK == TUK_Definition) << Kind << SS.getRange();
8105 // Create the resulting type.
8106 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
8107 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
8109 // Create type-source location information for this type.
8111 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
8112 TL.setElaboratedKeywordLoc(TagLoc);
8113 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8114 TL.setNameLoc(NameLoc);
8115 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
8119 Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
8120 const CXXScopeSpec &SS, const IdentifierInfo &II,
8121 SourceLocation IdLoc) {
8125 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
8127 getLangOpts().CPlusPlus11 ?
8128 diag::warn_cxx98_compat_typename_outside_of_template :
8129 diag::ext_typename_outside_of_template)
8130 << FixItHint::CreateRemoval(TypenameLoc);
8132 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
8133 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
8134 TypenameLoc, QualifierLoc, II, IdLoc);
8138 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8139 if (isa<DependentNameType>(T)) {
8140 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
8141 TL.setElaboratedKeywordLoc(TypenameLoc);
8142 TL.setQualifierLoc(QualifierLoc);
8143 TL.setNameLoc(IdLoc);
8145 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
8146 TL.setElaboratedKeywordLoc(TypenameLoc);
8147 TL.setQualifierLoc(QualifierLoc);
8148 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
8151 return CreateParsedType(T, TSI);
8155 Sema::ActOnTypenameType(Scope *S,
8156 SourceLocation TypenameLoc,
8157 const CXXScopeSpec &SS,
8158 SourceLocation TemplateKWLoc,
8159 TemplateTy TemplateIn,
8160 SourceLocation TemplateNameLoc,
8161 SourceLocation LAngleLoc,
8162 ASTTemplateArgsPtr TemplateArgsIn,
8163 SourceLocation RAngleLoc) {
8164 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
8166 getLangOpts().CPlusPlus11 ?
8167 diag::warn_cxx98_compat_typename_outside_of_template :
8168 diag::ext_typename_outside_of_template)
8169 << FixItHint::CreateRemoval(TypenameLoc);
8171 // Translate the parser's template argument list in our AST format.
8172 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
8173 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
8175 TemplateName Template = TemplateIn.get();
8176 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
8177 // Construct a dependent template specialization type.
8178 assert(DTN && "dependent template has non-dependent name?");
8179 assert(DTN->getQualifier() == SS.getScopeRep());
8180 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
8181 DTN->getQualifier(),
8182 DTN->getIdentifier(),
8185 // Create source-location information for this type.
8186 TypeLocBuilder Builder;
8187 DependentTemplateSpecializationTypeLoc SpecTL
8188 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
8189 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
8190 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
8191 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
8192 SpecTL.setTemplateNameLoc(TemplateNameLoc);
8193 SpecTL.setLAngleLoc(LAngleLoc);
8194 SpecTL.setRAngleLoc(RAngleLoc);
8195 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8196 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
8197 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
8200 QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
8204 // Provide source-location information for the template specialization type.
8205 TypeLocBuilder Builder;
8206 TemplateSpecializationTypeLoc SpecTL
8207 = Builder.push<TemplateSpecializationTypeLoc>(T);
8208 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
8209 SpecTL.setTemplateNameLoc(TemplateNameLoc);
8210 SpecTL.setLAngleLoc(LAngleLoc);
8211 SpecTL.setRAngleLoc(RAngleLoc);
8212 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8213 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
8215 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
8216 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
8217 TL.setElaboratedKeywordLoc(TypenameLoc);
8218 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8220 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
8221 return CreateParsedType(T, TSI);
8225 /// Determine whether this failed name lookup should be treated as being
8226 /// disabled by a usage of std::enable_if.
8227 static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
8228 SourceRange &CondRange) {
8229 // We must be looking for a ::type...
8230 if (!II.isStr("type"))
8233 // ... within an explicitly-written template specialization...
8234 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
8236 TypeLoc EnableIfTy = NNS.getTypeLoc();
8237 TemplateSpecializationTypeLoc EnableIfTSTLoc =
8238 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
8239 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
8241 const TemplateSpecializationType *EnableIfTST =
8242 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
8244 // ... which names a complete class template declaration...
8245 const TemplateDecl *EnableIfDecl =
8246 EnableIfTST->getTemplateName().getAsTemplateDecl();
8247 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
8250 // ... called "enable_if".
8251 const IdentifierInfo *EnableIfII =
8252 EnableIfDecl->getDeclName().getAsIdentifierInfo();
8253 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
8256 // Assume the first template argument is the condition.
8257 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
8261 /// \brief Build the type that describes a C++ typename specifier,
8262 /// e.g., "typename T::type".
8264 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
8265 SourceLocation KeywordLoc,
8266 NestedNameSpecifierLoc QualifierLoc,
8267 const IdentifierInfo &II,
8268 SourceLocation IILoc) {
8270 SS.Adopt(QualifierLoc);
8272 DeclContext *Ctx = computeDeclContext(SS);
8274 // If the nested-name-specifier is dependent and couldn't be
8275 // resolved to a type, build a typename type.
8276 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
8277 return Context.getDependentNameType(Keyword,
8278 QualifierLoc.getNestedNameSpecifier(),
8282 // If the nested-name-specifier refers to the current instantiation,
8283 // the "typename" keyword itself is superfluous. In C++03, the
8284 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
8285 // allows such extraneous "typename" keywords, and we retroactively
8286 // apply this DR to C++03 code with only a warning. In any case we continue.
8288 if (RequireCompleteDeclContext(SS, Ctx))
8291 DeclarationName Name(&II);
8292 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
8293 LookupQualifiedName(Result, Ctx, SS);
8294 unsigned DiagID = 0;
8295 Decl *Referenced = nullptr;
8296 switch (Result.getResultKind()) {
8297 case LookupResult::NotFound: {
8298 // If we're looking up 'type' within a template named 'enable_if', produce
8299 // a more specific diagnostic.
8300 SourceRange CondRange;
8301 if (isEnableIf(QualifierLoc, II, CondRange)) {
8302 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
8303 << Ctx << CondRange;
8307 DiagID = diag::err_typename_nested_not_found;
8311 case LookupResult::FoundUnresolvedValue: {
8312 // We found a using declaration that is a value. Most likely, the using
8313 // declaration itself is meant to have the 'typename' keyword.
8314 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
8316 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
8317 << Name << Ctx << FullRange;
8318 if (UnresolvedUsingValueDecl *Using
8319 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
8320 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
8321 Diag(Loc, diag::note_using_value_decl_missing_typename)
8322 << FixItHint::CreateInsertion(Loc, "typename ");
8325 // Fall through to create a dependent typename type, from which we can recover
8328 case LookupResult::NotFoundInCurrentInstantiation:
8329 // Okay, it's a member of an unknown instantiation.
8330 return Context.getDependentNameType(Keyword,
8331 QualifierLoc.getNestedNameSpecifier(),
8334 case LookupResult::Found:
8335 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
8336 // We found a type. Build an ElaboratedType, since the
8337 // typename-specifier was just sugar.
8338 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
8339 return Context.getElaboratedType(ETK_Typename,
8340 QualifierLoc.getNestedNameSpecifier(),
8341 Context.getTypeDeclType(Type));
8344 DiagID = diag::err_typename_nested_not_type;
8345 Referenced = Result.getFoundDecl();
8348 case LookupResult::FoundOverloaded:
8349 DiagID = diag::err_typename_nested_not_type;
8350 Referenced = *Result.begin();
8353 case LookupResult::Ambiguous:
8357 // If we get here, it's because name lookup did not find a
8358 // type. Emit an appropriate diagnostic and return an error.
8359 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
8361 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
8363 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
8369 // See Sema::RebuildTypeInCurrentInstantiation
8370 class CurrentInstantiationRebuilder
8371 : public TreeTransform<CurrentInstantiationRebuilder> {
8373 DeclarationName Entity;
8376 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
8378 CurrentInstantiationRebuilder(Sema &SemaRef,
8380 DeclarationName Entity)
8381 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
8382 Loc(Loc), Entity(Entity) { }
8384 /// \brief Determine whether the given type \p T has already been
8387 /// For the purposes of type reconstruction, a type has already been
8388 /// transformed if it is NULL or if it is not dependent.
8389 bool AlreadyTransformed(QualType T) {
8390 return T.isNull() || !T->isDependentType();
8393 /// \brief Returns the location of the entity whose type is being
8395 SourceLocation getBaseLocation() { return Loc; }
8397 /// \brief Returns the name of the entity whose type is being rebuilt.
8398 DeclarationName getBaseEntity() { return Entity; }
8400 /// \brief Sets the "base" location and entity when that
8401 /// information is known based on another transformation.
8402 void setBase(SourceLocation Loc, DeclarationName Entity) {
8404 this->Entity = Entity;
8407 ExprResult TransformLambdaExpr(LambdaExpr *E) {
8408 // Lambdas never need to be transformed.
8412 } // end anonymous namespace
8414 /// \brief Rebuilds a type within the context of the current instantiation.
8416 /// The type \p T is part of the type of an out-of-line member definition of
8417 /// a class template (or class template partial specialization) that was parsed
8418 /// and constructed before we entered the scope of the class template (or
8419 /// partial specialization thereof). This routine will rebuild that type now
8420 /// that we have entered the declarator's scope, which may produce different
8421 /// canonical types, e.g.,
8424 /// template<typename T>
8426 /// typedef T* pointer;
8430 /// template<typename T>
8431 /// typename X<T>::pointer X<T>::data() { ... }
8434 /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
8435 /// since we do not know that we can look into X<T> when we parsed the type.
8436 /// This function will rebuild the type, performing the lookup of "pointer"
8437 /// in X<T> and returning an ElaboratedType whose canonical type is the same
8438 /// as the canonical type of T*, allowing the return types of the out-of-line
8439 /// definition and the declaration to match.
8440 TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
8442 DeclarationName Name) {
8443 if (!T || !T->getType()->isDependentType())
8446 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
8447 return Rebuilder.TransformType(T);
8450 ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
8451 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
8453 return Rebuilder.TransformExpr(E);
8456 bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
8460 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
8461 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
8463 NestedNameSpecifierLoc Rebuilt
8464 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
8472 /// \brief Rebuild the template parameters now that we know we're in a current
8474 bool Sema::RebuildTemplateParamsInCurrentInstantiation(
8475 TemplateParameterList *Params) {
8476 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8477 Decl *Param = Params->getParam(I);
8479 // There is nothing to rebuild in a type parameter.
8480 if (isa<TemplateTypeParmDecl>(Param))
8483 // Rebuild the template parameter list of a template template parameter.
8484 if (TemplateTemplateParmDecl *TTP
8485 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
8486 if (RebuildTemplateParamsInCurrentInstantiation(
8487 TTP->getTemplateParameters()))
8493 // Rebuild the type of a non-type template parameter.
8494 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
8495 TypeSourceInfo *NewTSI
8496 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
8497 NTTP->getLocation(),
8498 NTTP->getDeclName());
8502 if (NewTSI != NTTP->getTypeSourceInfo()) {
8503 NTTP->setTypeSourceInfo(NewTSI);
8504 NTTP->setType(NewTSI->getType());
8511 /// \brief Produces a formatted string that describes the binding of
8512 /// template parameters to template arguments.
8514 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8515 const TemplateArgumentList &Args) {
8516 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
8520 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8521 const TemplateArgument *Args,
8523 SmallString<128> Str;
8524 llvm::raw_svector_ostream Out(Str);
8526 if (!Params || Params->size() == 0 || NumArgs == 0)
8527 return std::string();
8529 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8538 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
8539 Out << Id->getName();
8545 Args[I].print(getPrintingPolicy(), Out);
8552 void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
8553 CachedTokens &Toks) {
8557 LateParsedTemplate *LPT = new LateParsedTemplate;
8559 // Take tokens to avoid allocations
8560 LPT->Toks.swap(Toks);
8562 LateParsedTemplateMap.insert(std::make_pair(FD, LPT));
8564 FD->setLateTemplateParsed(true);
8567 void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
8570 FD->setLateTemplateParsed(false);
8573 bool Sema::IsInsideALocalClassWithinATemplateFunction() {
8574 DeclContext *DC = CurContext;
8577 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
8578 const FunctionDecl *FD = RD->isLocalClass();
8579 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
8580 } else if (DC->isTranslationUnit() || DC->isNamespace())
8583 DC = DC->getParent();
8588 /// \brief Walk the path from which a declaration was instantiated, and check
8589 /// that every explicit specialization along that path is visible. This enforces
8590 /// C++ [temp.expl.spec]/6:
8592 /// If a template, a member template or a member of a class template is
8593 /// explicitly specialized then that specialization shall be declared before
8594 /// the first use of that specialization that would cause an implicit
8595 /// instantiation to take place, in every translation unit in which such a
8596 /// use occurs; no diagnostic is required.
8598 /// and also C++ [temp.class.spec]/1:
8600 /// A partial specialization shall be declared before the first use of a
8601 /// class template specialization that would make use of the partial
8602 /// specialization as the result of an implicit or explicit instantiation
8603 /// in every translation unit in which such a use occurs; no diagnostic is
8605 class ExplicitSpecializationVisibilityChecker {
8608 llvm::SmallVector<Module *, 8> Modules;
8611 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
8614 void check(NamedDecl *ND) {
8615 if (auto *FD = dyn_cast<FunctionDecl>(ND))
8616 return checkImpl(FD);
8617 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
8618 return checkImpl(RD);
8619 if (auto *VD = dyn_cast<VarDecl>(ND))
8620 return checkImpl(VD);
8621 if (auto *ED = dyn_cast<EnumDecl>(ND))
8622 return checkImpl(ED);
8626 void diagnose(NamedDecl *D, bool IsPartialSpec) {
8627 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
8628 : Sema::MissingImportKind::ExplicitSpecialization;
8629 const bool Recover = true;
8631 // If we got a custom set of modules (because only a subset of the
8632 // declarations are interesting), use them, otherwise let
8633 // diagnoseMissingImport intelligently pick some.
8634 if (Modules.empty())
8635 S.diagnoseMissingImport(Loc, D, Kind, Recover);
8637 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
8640 // Check a specific declaration. There are three problematic cases:
8642 // 1) The declaration is an explicit specialization of a template
8644 // 2) The declaration is an explicit specialization of a member of an
8646 // 3) The declaration is an instantiation of a template, and that template
8647 // is an explicit specialization of a member of a templated class.
8649 // We don't need to go any deeper than that, as the instantiation of the
8650 // surrounding class / etc is not triggered by whatever triggered this
8651 // instantiation, and thus should be checked elsewhere.
8652 template<typename SpecDecl>
8653 void checkImpl(SpecDecl *Spec) {
8654 bool IsHiddenExplicitSpecialization = false;
8655 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
8656 IsHiddenExplicitSpecialization =
8657 Spec->getMemberSpecializationInfo()
8658 ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
8659 : !S.hasVisibleDeclaration(Spec);
8661 checkInstantiated(Spec);
8664 if (IsHiddenExplicitSpecialization)
8665 diagnose(Spec->getMostRecentDecl(), false);
8668 void checkInstantiated(FunctionDecl *FD) {
8669 if (auto *TD = FD->getPrimaryTemplate())
8673 void checkInstantiated(CXXRecordDecl *RD) {
8674 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
8678 auto From = SD->getSpecializedTemplateOrPartial();
8679 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
8682 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
8683 if (!S.hasVisibleDeclaration(TD))
8689 void checkInstantiated(VarDecl *RD) {
8690 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
8694 auto From = SD->getSpecializedTemplateOrPartial();
8695 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
8698 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
8699 if (!S.hasVisibleDeclaration(TD))
8705 void checkInstantiated(EnumDecl *FD) {}
8707 template<typename TemplDecl>
8708 void checkTemplate(TemplDecl *TD) {
8709 if (TD->isMemberSpecialization()) {
8710 if (!S.hasVisibleMemberSpecialization(TD, &Modules))
8711 diagnose(TD->getMostRecentDecl(), false);
8716 void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
8717 if (!getLangOpts().Modules)
8720 ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
8723 /// \brief Check whether a template partial specialization that we've discovered
8724 /// is hidden, and produce suitable diagnostics if so.
8725 void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
8727 llvm::SmallVector<Module *, 8> Modules;
8728 if (!hasVisibleDeclaration(Spec, &Modules))
8729 diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
8730 MissingImportKind::PartialSpecialization,