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 if (!isAddressOfOperand &&
418 isa<CXXMethodDecl>(DC) &&
419 cast<CXXMethodDecl>(DC)->isInstance()) {
420 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
422 // Since the 'this' expression is synthesized, we don't need to
423 // perform the double-lookup check.
424 NamedDecl *FirstQualifierInScope = nullptr;
426 return CXXDependentScopeMemberExpr::Create(
427 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
428 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
429 FirstQualifierInScope, NameInfo, TemplateArgs);
432 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
436 Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
437 SourceLocation TemplateKWLoc,
438 const DeclarationNameInfo &NameInfo,
439 const TemplateArgumentListInfo *TemplateArgs) {
440 return DependentScopeDeclRefExpr::Create(
441 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
445 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
446 /// that the template parameter 'PrevDecl' is being shadowed by a new
447 /// declaration at location Loc. Returns true to indicate that this is
448 /// an error, and false otherwise.
449 void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
450 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
452 // Microsoft Visual C++ permits template parameters to be shadowed.
453 if (getLangOpts().MicrosoftExt)
456 // C++ [temp.local]p4:
457 // A template-parameter shall not be redeclared within its
458 // scope (including nested scopes).
459 Diag(Loc, diag::err_template_param_shadow)
460 << cast<NamedDecl>(PrevDecl)->getDeclName();
461 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
464 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
465 /// the parameter D to reference the templated declaration and return a pointer
466 /// to the template declaration. Otherwise, do nothing to D and return null.
467 TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
468 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
469 D = Temp->getTemplatedDecl();
475 ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
476 SourceLocation EllipsisLoc) const {
477 assert(Kind == Template &&
478 "Only template template arguments can be pack expansions here");
479 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
480 "Template template argument pack expansion without packs");
481 ParsedTemplateArgument Result(*this);
482 Result.EllipsisLoc = EllipsisLoc;
486 static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
487 const ParsedTemplateArgument &Arg) {
489 switch (Arg.getKind()) {
490 case ParsedTemplateArgument::Type: {
492 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
494 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
495 return TemplateArgumentLoc(TemplateArgument(T), DI);
498 case ParsedTemplateArgument::NonType: {
499 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
500 return TemplateArgumentLoc(TemplateArgument(E), E);
503 case ParsedTemplateArgument::Template: {
504 TemplateName Template = Arg.getAsTemplate().get();
505 TemplateArgument TArg;
506 if (Arg.getEllipsisLoc().isValid())
507 TArg = TemplateArgument(Template, Optional<unsigned int>());
510 return TemplateArgumentLoc(TArg,
511 Arg.getScopeSpec().getWithLocInContext(
514 Arg.getEllipsisLoc());
518 llvm_unreachable("Unhandled parsed template argument");
521 /// \brief Translates template arguments as provided by the parser
522 /// into template arguments used by semantic analysis.
523 void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
524 TemplateArgumentListInfo &TemplateArgs) {
525 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
526 TemplateArgs.addArgument(translateTemplateArgument(*this,
530 static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
532 IdentifierInfo *Name) {
533 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
534 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration);
535 if (PrevDecl && PrevDecl->isTemplateParameter())
536 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
539 /// ActOnTypeParameter - Called when a C++ template type parameter
540 /// (e.g., "typename T") has been parsed. Typename specifies whether
541 /// the keyword "typename" was used to declare the type parameter
542 /// (otherwise, "class" was used), and KeyLoc is the location of the
543 /// "class" or "typename" keyword. ParamName is the name of the
544 /// parameter (NULL indicates an unnamed template parameter) and
545 /// ParamNameLoc is the location of the parameter name (if any).
546 /// If the type parameter has a default argument, it will be added
547 /// later via ActOnTypeParameterDefault.
548 Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
549 SourceLocation EllipsisLoc,
550 SourceLocation KeyLoc,
551 IdentifierInfo *ParamName,
552 SourceLocation ParamNameLoc,
553 unsigned Depth, unsigned Position,
554 SourceLocation EqualLoc,
555 ParsedType DefaultArg) {
556 assert(S->isTemplateParamScope() &&
557 "Template type parameter not in template parameter scope!");
558 bool Invalid = false;
560 SourceLocation Loc = ParamNameLoc;
564 bool IsParameterPack = EllipsisLoc.isValid();
565 TemplateTypeParmDecl *Param
566 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
567 KeyLoc, Loc, Depth, Position, ParamName,
568 Typename, IsParameterPack);
569 Param->setAccess(AS_public);
571 Param->setInvalidDecl();
574 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
576 // Add the template parameter into the current scope.
578 IdResolver.AddDecl(Param);
581 // C++0x [temp.param]p9:
582 // A default template-argument may be specified for any kind of
583 // template-parameter that is not a template parameter pack.
584 if (DefaultArg && IsParameterPack) {
585 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
586 DefaultArg = nullptr;
589 // Handle the default argument, if provided.
591 TypeSourceInfo *DefaultTInfo;
592 GetTypeFromParser(DefaultArg, &DefaultTInfo);
594 assert(DefaultTInfo && "expected source information for type");
596 // Check for unexpanded parameter packs.
597 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
598 UPPC_DefaultArgument))
601 // Check the template argument itself.
602 if (CheckTemplateArgument(Param, DefaultTInfo)) {
603 Param->setInvalidDecl();
607 Param->setDefaultArgument(DefaultTInfo);
613 /// \brief Check that the type of a non-type template parameter is
616 /// \returns the (possibly-promoted) parameter type if valid;
617 /// otherwise, produces a diagnostic and returns a NULL type.
619 Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
620 // We don't allow variably-modified types as the type of non-type template
622 if (T->isVariablyModifiedType()) {
623 Diag(Loc, diag::err_variably_modified_nontype_template_param)
628 // C++ [temp.param]p4:
630 // A non-type template-parameter shall have one of the following
631 // (optionally cv-qualified) types:
633 // -- integral or enumeration type,
634 if (T->isIntegralOrEnumerationType() ||
635 // -- pointer to object or pointer to function,
636 T->isPointerType() ||
637 // -- reference to object or reference to function,
638 T->isReferenceType() ||
639 // -- pointer to member,
640 T->isMemberPointerType() ||
641 // -- std::nullptr_t.
642 T->isNullPtrType() ||
643 // If T is a dependent type, we can't do the check now, so we
644 // assume that it is well-formed.
645 T->isDependentType()) {
646 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
647 // are ignored when determining its type.
648 return T.getUnqualifiedType();
651 // C++ [temp.param]p8:
653 // A non-type template-parameter of type "array of T" or
654 // "function returning T" is adjusted to be of type "pointer to
655 // T" or "pointer to function returning T", respectively.
656 else if (T->isArrayType() || T->isFunctionType())
657 return Context.getDecayedType(T);
659 Diag(Loc, diag::err_template_nontype_parm_bad_type)
665 Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
668 SourceLocation EqualLoc,
670 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
671 QualType T = TInfo->getType();
673 assert(S->isTemplateParamScope() &&
674 "Non-type template parameter not in template parameter scope!");
675 bool Invalid = false;
677 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
679 T = Context.IntTy; // Recover with an 'int' type.
683 IdentifierInfo *ParamName = D.getIdentifier();
684 bool IsParameterPack = D.hasEllipsis();
685 NonTypeTemplateParmDecl *Param
686 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
688 D.getIdentifierLoc(),
689 Depth, Position, ParamName, T,
690 IsParameterPack, TInfo);
691 Param->setAccess(AS_public);
694 Param->setInvalidDecl();
697 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
700 // Add the template parameter into the current scope.
702 IdResolver.AddDecl(Param);
705 // C++0x [temp.param]p9:
706 // A default template-argument may be specified for any kind of
707 // template-parameter that is not a template parameter pack.
708 if (Default && IsParameterPack) {
709 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
713 // Check the well-formedness of the default template argument, if provided.
715 // Check for unexpanded parameter packs.
716 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
719 TemplateArgument Converted;
720 ExprResult DefaultRes =
721 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
722 if (DefaultRes.isInvalid()) {
723 Param->setInvalidDecl();
726 Default = DefaultRes.get();
728 Param->setDefaultArgument(Default);
734 /// ActOnTemplateTemplateParameter - Called when a C++ template template
735 /// parameter (e.g. T in template <template \<typename> class T> class array)
736 /// has been parsed. S is the current scope.
737 Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
738 SourceLocation TmpLoc,
739 TemplateParameterList *Params,
740 SourceLocation EllipsisLoc,
741 IdentifierInfo *Name,
742 SourceLocation NameLoc,
745 SourceLocation EqualLoc,
746 ParsedTemplateArgument Default) {
747 assert(S->isTemplateParamScope() &&
748 "Template template parameter not in template parameter scope!");
750 // Construct the parameter object.
751 bool IsParameterPack = EllipsisLoc.isValid();
752 TemplateTemplateParmDecl *Param =
753 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
754 NameLoc.isInvalid()? TmpLoc : NameLoc,
755 Depth, Position, IsParameterPack,
757 Param->setAccess(AS_public);
759 // If the template template parameter has a name, then link the identifier
760 // into the scope and lookup mechanisms.
762 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
765 IdResolver.AddDecl(Param);
768 if (Params->size() == 0) {
769 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
770 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
771 Param->setInvalidDecl();
774 // C++0x [temp.param]p9:
775 // A default template-argument may be specified for any kind of
776 // template-parameter that is not a template parameter pack.
777 if (IsParameterPack && !Default.isInvalid()) {
778 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
779 Default = ParsedTemplateArgument();
782 if (!Default.isInvalid()) {
783 // Check only that we have a template template argument. We don't want to
784 // try to check well-formedness now, because our template template parameter
785 // might have dependent types in its template parameters, which we wouldn't
786 // be able to match now.
788 // If none of the template template parameter's template arguments mention
789 // other template parameters, we could actually perform more checking here.
790 // However, it isn't worth doing.
791 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
792 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
793 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
794 << DefaultArg.getSourceRange();
798 // Check for unexpanded parameter packs.
799 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
800 DefaultArg.getArgument().getAsTemplate(),
801 UPPC_DefaultArgument))
804 Param->setDefaultArgument(Context, DefaultArg);
810 /// ActOnTemplateParameterList - Builds a TemplateParameterList that
811 /// contains the template parameters in Params/NumParams.
812 TemplateParameterList *
813 Sema::ActOnTemplateParameterList(unsigned Depth,
814 SourceLocation ExportLoc,
815 SourceLocation TemplateLoc,
816 SourceLocation LAngleLoc,
817 ArrayRef<Decl *> Params,
818 SourceLocation RAngleLoc) {
819 if (ExportLoc.isValid())
820 Diag(ExportLoc, diag::warn_template_export_unsupported);
822 return TemplateParameterList::Create(
823 Context, TemplateLoc, LAngleLoc,
824 llvm::makeArrayRef((NamedDecl *const *)Params.data(), Params.size()),
828 static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
830 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
834 Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
835 SourceLocation KWLoc, CXXScopeSpec &SS,
836 IdentifierInfo *Name, SourceLocation NameLoc,
838 TemplateParameterList *TemplateParams,
839 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
840 SourceLocation FriendLoc,
841 unsigned NumOuterTemplateParamLists,
842 TemplateParameterList** OuterTemplateParamLists,
843 SkipBodyInfo *SkipBody) {
844 assert(TemplateParams && TemplateParams->size() > 0 &&
845 "No template parameters");
846 assert(TUK != TUK_Reference && "Can only declare or define class templates");
847 bool Invalid = false;
849 // Check that we can declare a template here.
850 if (CheckTemplateDeclScope(S, TemplateParams))
853 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
854 assert(Kind != TTK_Enum && "can't build template of enumerated type");
856 // There is no such thing as an unnamed class template.
858 Diag(KWLoc, diag::err_template_unnamed_class);
862 // Find any previous declaration with this name. For a friend with no
863 // scope explicitly specified, we only look for tag declarations (per
864 // C++11 [basic.lookup.elab]p2).
865 DeclContext *SemanticContext;
866 LookupResult Previous(*this, Name, NameLoc,
867 (SS.isEmpty() && TUK == TUK_Friend)
868 ? LookupTagName : LookupOrdinaryName,
870 if (SS.isNotEmpty() && !SS.isInvalid()) {
871 SemanticContext = computeDeclContext(SS, true);
872 if (!SemanticContext) {
873 // FIXME: Horrible, horrible hack! We can't currently represent this
874 // in the AST, and historically we have just ignored such friend
875 // class templates, so don't complain here.
876 Diag(NameLoc, TUK == TUK_Friend
877 ? diag::warn_template_qualified_friend_ignored
878 : diag::err_template_qualified_declarator_no_match)
879 << SS.getScopeRep() << SS.getRange();
880 return TUK != TUK_Friend;
883 if (RequireCompleteDeclContext(SS, SemanticContext))
886 // If we're adding a template to a dependent context, we may need to
887 // rebuilding some of the types used within the template parameter list,
888 // now that we know what the current instantiation is.
889 if (SemanticContext->isDependentContext()) {
890 ContextRAII SavedContext(*this, SemanticContext);
891 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
893 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
894 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
896 LookupQualifiedName(Previous, SemanticContext);
898 SemanticContext = CurContext;
900 // C++14 [class.mem]p14:
901 // If T is the name of a class, then each of the following shall have a
902 // name different from T:
903 // -- every member template of class T
904 if (TUK != TUK_Friend &&
905 DiagnoseClassNameShadow(SemanticContext,
906 DeclarationNameInfo(Name, NameLoc)))
909 LookupName(Previous, S);
912 if (Previous.isAmbiguous())
915 NamedDecl *PrevDecl = nullptr;
916 if (Previous.begin() != Previous.end())
917 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
919 // If there is a previous declaration with the same name, check
920 // whether this is a valid redeclaration.
921 ClassTemplateDecl *PrevClassTemplate
922 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
924 // We may have found the injected-class-name of a class template,
925 // class template partial specialization, or class template specialization.
926 // In these cases, grab the template that is being defined or specialized.
927 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
928 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
929 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
931 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
932 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
934 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
935 ->getSpecializedTemplate();
939 if (TUK == TUK_Friend) {
940 // C++ [namespace.memdef]p3:
941 // [...] When looking for a prior declaration of a class or a function
942 // declared as a friend, and when the name of the friend class or
943 // function is neither a qualified name nor a template-id, scopes outside
944 // the innermost enclosing namespace scope are not considered.
946 DeclContext *OutermostContext = CurContext;
947 while (!OutermostContext->isFileContext())
948 OutermostContext = OutermostContext->getLookupParent();
951 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
952 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
953 SemanticContext = PrevDecl->getDeclContext();
955 // Declarations in outer scopes don't matter. However, the outermost
956 // context we computed is the semantic context for our new
958 PrevDecl = PrevClassTemplate = nullptr;
959 SemanticContext = OutermostContext;
961 // Check that the chosen semantic context doesn't already contain a
962 // declaration of this name as a non-tag type.
963 Previous.clear(LookupOrdinaryName);
964 DeclContext *LookupContext = SemanticContext;
965 while (LookupContext->isTransparentContext())
966 LookupContext = LookupContext->getLookupParent();
967 LookupQualifiedName(Previous, LookupContext);
969 if (Previous.isAmbiguous())
972 if (Previous.begin() != Previous.end())
973 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
976 } else if (PrevDecl &&
977 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
979 PrevDecl = PrevClassTemplate = nullptr;
981 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
982 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
984 !(PrevClassTemplate &&
985 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
986 SemanticContext->getRedeclContext()))) {
987 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
988 Diag(Shadow->getTargetDecl()->getLocation(),
989 diag::note_using_decl_target);
990 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
991 // Recover by ignoring the old declaration.
992 PrevDecl = PrevClassTemplate = nullptr;
996 if (PrevClassTemplate) {
997 // Ensure that the template parameter lists are compatible. Skip this check
998 // for a friend in a dependent context: the template parameter list itself
999 // could be dependent.
1000 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1001 !TemplateParameterListsAreEqual(TemplateParams,
1002 PrevClassTemplate->getTemplateParameters(),
1007 // C++ [temp.class]p4:
1008 // In a redeclaration, partial specialization, explicit
1009 // specialization or explicit instantiation of a class template,
1010 // the class-key shall agree in kind with the original class
1011 // template declaration (7.1.5.3).
1012 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
1013 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
1014 TUK == TUK_Definition, KWLoc, Name)) {
1015 Diag(KWLoc, diag::err_use_with_wrong_tag)
1017 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
1018 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
1019 Kind = PrevRecordDecl->getTagKind();
1022 // Check for redefinition of this class template.
1023 if (TUK == TUK_Definition) {
1024 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
1025 // If we have a prior definition that is not visible, treat this as
1026 // simply making that previous definition visible.
1027 NamedDecl *Hidden = nullptr;
1028 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
1029 SkipBody->ShouldSkip = true;
1030 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1031 assert(Tmpl && "original definition of a class template is not a "
1033 makeMergedDefinitionVisible(Hidden, KWLoc);
1034 makeMergedDefinitionVisible(Tmpl, KWLoc);
1038 Diag(NameLoc, diag::err_redefinition) << Name;
1039 Diag(Def->getLocation(), diag::note_previous_definition);
1040 // FIXME: Would it make sense to try to "forget" the previous
1041 // definition, as part of error recovery?
1045 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
1046 // Maybe we will complain about the shadowed template parameter.
1047 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1048 // Just pretend that we didn't see the previous declaration.
1050 } else if (PrevDecl) {
1052 // A class template shall not have the same name as any other
1053 // template, class, function, object, enumeration, enumerator,
1054 // namespace, or type in the same scope (3.3), except as specified
1056 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1057 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1061 // Check the template parameter list of this declaration, possibly
1062 // merging in the template parameter list from the previous class
1063 // template declaration. Skip this check for a friend in a dependent
1064 // context, because the template parameter list might be dependent.
1065 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1066 CheckTemplateParameterList(
1068 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1070 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1071 SemanticContext->isDependentContext())
1072 ? TPC_ClassTemplateMember
1073 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1074 : TPC_ClassTemplate))
1078 // If the name of the template was qualified, we must be defining the
1079 // template out-of-line.
1080 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1081 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
1082 : diag::err_member_decl_does_not_match)
1083 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
1088 CXXRecordDecl *NewClass =
1089 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
1091 PrevClassTemplate->getTemplatedDecl() : nullptr,
1092 /*DelayTypeCreation=*/true);
1093 SetNestedNameSpecifier(NewClass, SS);
1094 if (NumOuterTemplateParamLists > 0)
1095 NewClass->setTemplateParameterListsInfo(
1096 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1097 NumOuterTemplateParamLists));
1099 // Add alignment attributes if necessary; these attributes are checked when
1100 // the ASTContext lays out the structure.
1101 if (TUK == TUK_Definition) {
1102 AddAlignmentAttributesForRecord(NewClass);
1103 AddMsStructLayoutForRecord(NewClass);
1106 ClassTemplateDecl *NewTemplate
1107 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1108 DeclarationName(Name), TemplateParams,
1109 NewClass, PrevClassTemplate);
1110 NewClass->setDescribedClassTemplate(NewTemplate);
1112 if (ModulePrivateLoc.isValid())
1113 NewTemplate->setModulePrivate();
1115 // Build the type for the class template declaration now.
1116 QualType T = NewTemplate->getInjectedClassNameSpecialization();
1117 T = Context.getInjectedClassNameType(NewClass, T);
1118 assert(T->isDependentType() && "Class template type is not dependent?");
1121 // If we are providing an explicit specialization of a member that is a
1122 // class template, make a note of that.
1123 if (PrevClassTemplate &&
1124 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1125 PrevClassTemplate->setMemberSpecialization();
1127 // Set the access specifier.
1128 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
1129 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
1131 // Set the lexical context of these templates
1132 NewClass->setLexicalDeclContext(CurContext);
1133 NewTemplate->setLexicalDeclContext(CurContext);
1135 if (TUK == TUK_Definition)
1136 NewClass->startDefinition();
1139 ProcessDeclAttributeList(S, NewClass, Attr);
1141 if (PrevClassTemplate)
1142 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1144 AddPushedVisibilityAttribute(NewClass);
1146 if (TUK != TUK_Friend) {
1147 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1149 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1150 Outer = Outer->getParent();
1151 PushOnScopeChains(NewTemplate, Outer);
1153 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
1154 NewTemplate->setAccess(PrevClassTemplate->getAccess());
1155 NewClass->setAccess(PrevClassTemplate->getAccess());
1158 NewTemplate->setObjectOfFriendDecl();
1160 // Friend templates are visible in fairly strange ways.
1161 if (!CurContext->isDependentContext()) {
1162 DeclContext *DC = SemanticContext->getRedeclContext();
1163 DC->makeDeclVisibleInContext(NewTemplate);
1164 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1165 PushOnScopeChains(NewTemplate, EnclosingScope,
1166 /* AddToContext = */ false);
1169 FriendDecl *Friend = FriendDecl::Create(
1170 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
1171 Friend->setAccess(AS_public);
1172 CurContext->addDecl(Friend);
1176 NewTemplate->setInvalidDecl();
1177 NewClass->setInvalidDecl();
1180 ActOnDocumentableDecl(NewTemplate);
1185 /// \brief Diagnose the presence of a default template argument on a
1186 /// template parameter, which is ill-formed in certain contexts.
1188 /// \returns true if the default template argument should be dropped.
1189 static bool DiagnoseDefaultTemplateArgument(Sema &S,
1190 Sema::TemplateParamListContext TPC,
1191 SourceLocation ParamLoc,
1192 SourceRange DefArgRange) {
1194 case Sema::TPC_ClassTemplate:
1195 case Sema::TPC_VarTemplate:
1196 case Sema::TPC_TypeAliasTemplate:
1199 case Sema::TPC_FunctionTemplate:
1200 case Sema::TPC_FriendFunctionTemplateDefinition:
1201 // C++ [temp.param]p9:
1202 // A default template-argument shall not be specified in a
1203 // function template declaration or a function template
1205 // If a friend function template declaration specifies a default
1206 // template-argument, that declaration shall be a definition and shall be
1207 // the only declaration of the function template in the translation unit.
1208 // (C++98/03 doesn't have this wording; see DR226).
1209 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
1210 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1211 : diag::ext_template_parameter_default_in_function_template)
1215 case Sema::TPC_ClassTemplateMember:
1216 // C++0x [temp.param]p9:
1217 // A default template-argument shall not be specified in the
1218 // template-parameter-lists of the definition of a member of a
1219 // class template that appears outside of the member's class.
1220 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1224 case Sema::TPC_FriendClassTemplate:
1225 case Sema::TPC_FriendFunctionTemplate:
1226 // C++ [temp.param]p9:
1227 // A default template-argument shall not be specified in a
1228 // friend template declaration.
1229 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1233 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1234 // for friend function templates if there is only a single
1235 // declaration (and it is a definition). Strange!
1238 llvm_unreachable("Invalid TemplateParamListContext!");
1241 /// \brief Check for unexpanded parameter packs within the template parameters
1242 /// of a template template parameter, recursively.
1243 static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1244 TemplateTemplateParmDecl *TTP) {
1245 // A template template parameter which is a parameter pack is also a pack
1247 if (TTP->isParameterPack())
1250 TemplateParameterList *Params = TTP->getTemplateParameters();
1251 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1252 NamedDecl *P = Params->getParam(I);
1253 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
1254 if (!NTTP->isParameterPack() &&
1255 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
1256 NTTP->getTypeSourceInfo(),
1257 Sema::UPPC_NonTypeTemplateParameterType))
1263 if (TemplateTemplateParmDecl *InnerTTP
1264 = dyn_cast<TemplateTemplateParmDecl>(P))
1265 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1272 /// \brief Checks the validity of a template parameter list, possibly
1273 /// considering the template parameter list from a previous
1276 /// If an "old" template parameter list is provided, it must be
1277 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
1278 /// template parameter list.
1280 /// \param NewParams Template parameter list for a new template
1281 /// declaration. This template parameter list will be updated with any
1282 /// default arguments that are carried through from the previous
1283 /// template parameter list.
1285 /// \param OldParams If provided, template parameter list from a
1286 /// previous declaration of the same template. Default template
1287 /// arguments will be merged from the old template parameter list to
1288 /// the new template parameter list.
1290 /// \param TPC Describes the context in which we are checking the given
1291 /// template parameter list.
1293 /// \returns true if an error occurred, false otherwise.
1294 bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
1295 TemplateParameterList *OldParams,
1296 TemplateParamListContext TPC) {
1297 bool Invalid = false;
1299 // C++ [temp.param]p10:
1300 // The set of default template-arguments available for use with a
1301 // template declaration or definition is obtained by merging the
1302 // default arguments from the definition (if in scope) and all
1303 // declarations in scope in the same way default function
1304 // arguments are (8.3.6).
1305 bool SawDefaultArgument = false;
1306 SourceLocation PreviousDefaultArgLoc;
1308 // Dummy initialization to avoid warnings.
1309 TemplateParameterList::iterator OldParam = NewParams->end();
1311 OldParam = OldParams->begin();
1313 bool RemoveDefaultArguments = false;
1314 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1315 NewParamEnd = NewParams->end();
1316 NewParam != NewParamEnd; ++NewParam) {
1317 // Variables used to diagnose redundant default arguments
1318 bool RedundantDefaultArg = false;
1319 SourceLocation OldDefaultLoc;
1320 SourceLocation NewDefaultLoc;
1322 // Variable used to diagnose missing default arguments
1323 bool MissingDefaultArg = false;
1325 // Variable used to diagnose non-final parameter packs
1326 bool SawParameterPack = false;
1328 if (TemplateTypeParmDecl *NewTypeParm
1329 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
1330 // Check the presence of a default argument here.
1331 if (NewTypeParm->hasDefaultArgument() &&
1332 DiagnoseDefaultTemplateArgument(*this, TPC,
1333 NewTypeParm->getLocation(),
1334 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1336 NewTypeParm->removeDefaultArgument();
1338 // Merge default arguments for template type parameters.
1339 TemplateTypeParmDecl *OldTypeParm
1340 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
1341 if (NewTypeParm->isParameterPack()) {
1342 assert(!NewTypeParm->hasDefaultArgument() &&
1343 "Parameter packs can't have a default argument!");
1344 SawParameterPack = true;
1345 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
1346 NewTypeParm->hasDefaultArgument()) {
1347 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1348 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1349 SawDefaultArgument = true;
1350 RedundantDefaultArg = true;
1351 PreviousDefaultArgLoc = NewDefaultLoc;
1352 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1353 // Merge the default argument from the old declaration to the
1355 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
1356 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1357 } else if (NewTypeParm->hasDefaultArgument()) {
1358 SawDefaultArgument = true;
1359 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1360 } else if (SawDefaultArgument)
1361 MissingDefaultArg = true;
1362 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
1363 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
1364 // Check for unexpanded parameter packs.
1365 if (!NewNonTypeParm->isParameterPack() &&
1366 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
1367 NewNonTypeParm->getTypeSourceInfo(),
1368 UPPC_NonTypeTemplateParameterType)) {
1373 // Check the presence of a default argument here.
1374 if (NewNonTypeParm->hasDefaultArgument() &&
1375 DiagnoseDefaultTemplateArgument(*this, TPC,
1376 NewNonTypeParm->getLocation(),
1377 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1378 NewNonTypeParm->removeDefaultArgument();
1381 // Merge default arguments for non-type template parameters
1382 NonTypeTemplateParmDecl *OldNonTypeParm
1383 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
1384 if (NewNonTypeParm->isParameterPack()) {
1385 assert(!NewNonTypeParm->hasDefaultArgument() &&
1386 "Parameter packs can't have a default argument!");
1387 if (!NewNonTypeParm->isPackExpansion())
1388 SawParameterPack = true;
1389 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
1390 NewNonTypeParm->hasDefaultArgument()) {
1391 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1392 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1393 SawDefaultArgument = true;
1394 RedundantDefaultArg = true;
1395 PreviousDefaultArgLoc = NewDefaultLoc;
1396 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1397 // Merge the default argument from the old declaration to the
1399 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
1400 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1401 } else if (NewNonTypeParm->hasDefaultArgument()) {
1402 SawDefaultArgument = true;
1403 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1404 } else if (SawDefaultArgument)
1405 MissingDefaultArg = true;
1407 TemplateTemplateParmDecl *NewTemplateParm
1408 = cast<TemplateTemplateParmDecl>(*NewParam);
1410 // Check for unexpanded parameter packs, recursively.
1411 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
1416 // Check the presence of a default argument here.
1417 if (NewTemplateParm->hasDefaultArgument() &&
1418 DiagnoseDefaultTemplateArgument(*this, TPC,
1419 NewTemplateParm->getLocation(),
1420 NewTemplateParm->getDefaultArgument().getSourceRange()))
1421 NewTemplateParm->removeDefaultArgument();
1423 // Merge default arguments for template template parameters
1424 TemplateTemplateParmDecl *OldTemplateParm
1425 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
1426 if (NewTemplateParm->isParameterPack()) {
1427 assert(!NewTemplateParm->hasDefaultArgument() &&
1428 "Parameter packs can't have a default argument!");
1429 if (!NewTemplateParm->isPackExpansion())
1430 SawParameterPack = true;
1431 } else if (OldTemplateParm &&
1432 hasVisibleDefaultArgument(OldTemplateParm) &&
1433 NewTemplateParm->hasDefaultArgument()) {
1434 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1435 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
1436 SawDefaultArgument = true;
1437 RedundantDefaultArg = true;
1438 PreviousDefaultArgLoc = NewDefaultLoc;
1439 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1440 // Merge the default argument from the old declaration to the
1442 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
1443 PreviousDefaultArgLoc
1444 = OldTemplateParm->getDefaultArgument().getLocation();
1445 } else if (NewTemplateParm->hasDefaultArgument()) {
1446 SawDefaultArgument = true;
1447 PreviousDefaultArgLoc
1448 = NewTemplateParm->getDefaultArgument().getLocation();
1449 } else if (SawDefaultArgument)
1450 MissingDefaultArg = true;
1453 // C++11 [temp.param]p11:
1454 // If a template parameter of a primary class template or alias template
1455 // is a template parameter pack, it shall be the last template parameter.
1456 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
1457 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
1458 TPC == TPC_TypeAliasTemplate)) {
1459 Diag((*NewParam)->getLocation(),
1460 diag::err_template_param_pack_must_be_last_template_parameter);
1464 if (RedundantDefaultArg) {
1465 // C++ [temp.param]p12:
1466 // A template-parameter shall not be given default arguments
1467 // by two different declarations in the same scope.
1468 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1469 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1471 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
1472 // C++ [temp.param]p11:
1473 // If a template-parameter of a class template has a default
1474 // template-argument, each subsequent template-parameter shall either
1475 // have a default template-argument supplied or be a template parameter
1477 Diag((*NewParam)->getLocation(),
1478 diag::err_template_param_default_arg_missing);
1479 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1481 RemoveDefaultArguments = true;
1484 // If we have an old template parameter list that we're merging
1485 // in, move on to the next parameter.
1490 // We were missing some default arguments at the end of the list, so remove
1491 // all of the default arguments.
1492 if (RemoveDefaultArguments) {
1493 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1494 NewParamEnd = NewParams->end();
1495 NewParam != NewParamEnd; ++NewParam) {
1496 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1497 TTP->removeDefaultArgument();
1498 else if (NonTypeTemplateParmDecl *NTTP
1499 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1500 NTTP->removeDefaultArgument();
1502 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1511 /// A class which looks for a use of a certain level of template
1513 struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1514 typedef RecursiveASTVisitor<DependencyChecker> super;
1518 SourceLocation MatchLoc;
1520 DependencyChecker(unsigned Depth) : Depth(Depth), Match(false) {}
1522 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1523 NamedDecl *ND = Params->getParam(0);
1524 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1525 Depth = PD->getDepth();
1526 } else if (NonTypeTemplateParmDecl *PD =
1527 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1528 Depth = PD->getDepth();
1530 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1534 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
1535 if (ParmDepth >= Depth) {
1543 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1544 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
1547 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1548 return !Matches(T->getDepth());
1551 bool TraverseTemplateName(TemplateName N) {
1552 if (TemplateTemplateParmDecl *PD =
1553 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
1554 if (Matches(PD->getDepth()))
1556 return super::TraverseTemplateName(N);
1559 bool VisitDeclRefExpr(DeclRefExpr *E) {
1560 if (NonTypeTemplateParmDecl *PD =
1561 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
1562 if (Matches(PD->getDepth(), E->getExprLoc()))
1564 return super::VisitDeclRefExpr(E);
1567 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1568 return TraverseType(T->getReplacementType());
1572 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
1573 return TraverseTemplateArgument(T->getArgumentPack());
1576 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1577 return TraverseType(T->getInjectedSpecializationType());
1580 } // end anonymous namespace
1582 /// Determines whether a given type depends on the given parameter
1585 DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
1586 DependencyChecker Checker(Params);
1587 Checker.TraverseType(T);
1588 return Checker.Match;
1591 // Find the source range corresponding to the named type in the given
1592 // nested-name-specifier, if any.
1593 static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
1595 const CXXScopeSpec &SS) {
1596 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
1597 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1598 if (const Type *CurType = NNS->getAsType()) {
1599 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1600 return NNSLoc.getTypeLoc().getSourceRange();
1604 NNSLoc = NNSLoc.getPrefix();
1607 return SourceRange();
1610 /// \brief Match the given template parameter lists to the given scope
1611 /// specifier, returning the template parameter list that applies to the
1614 /// \param DeclStartLoc the start of the declaration that has a scope
1615 /// specifier or a template parameter list.
1617 /// \param DeclLoc The location of the declaration itself.
1619 /// \param SS the scope specifier that will be matched to the given template
1620 /// parameter lists. This scope specifier precedes a qualified name that is
1623 /// \param TemplateId The template-id following the scope specifier, if there
1624 /// is one. Used to check for a missing 'template<>'.
1626 /// \param ParamLists the template parameter lists, from the outermost to the
1627 /// innermost template parameter lists.
1629 /// \param IsFriend Whether to apply the slightly different rules for
1630 /// matching template parameters to scope specifiers in friend
1633 /// \param IsExplicitSpecialization will be set true if the entity being
1634 /// declared is an explicit specialization, false otherwise.
1636 /// \returns the template parameter list, if any, that corresponds to the
1637 /// name that is preceded by the scope specifier @p SS. This template
1638 /// parameter list may have template parameters (if we're declaring a
1639 /// template) or may have no template parameters (if we're declaring a
1640 /// template specialization), or may be NULL (if what we're declaring isn't
1641 /// itself a template).
1642 TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
1643 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
1644 TemplateIdAnnotation *TemplateId,
1645 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
1646 bool &IsExplicitSpecialization, bool &Invalid) {
1647 IsExplicitSpecialization = false;
1650 // The sequence of nested types to which we will match up the template
1651 // parameter lists. We first build this list by starting with the type named
1652 // by the nested-name-specifier and walking out until we run out of types.
1653 SmallVector<QualType, 4> NestedTypes;
1655 if (SS.getScopeRep()) {
1656 if (CXXRecordDecl *Record
1657 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1658 T = Context.getTypeDeclType(Record);
1660 T = QualType(SS.getScopeRep()->getAsType(), 0);
1663 // If we found an explicit specialization that prevents us from needing
1664 // 'template<>' headers, this will be set to the location of that
1665 // explicit specialization.
1666 SourceLocation ExplicitSpecLoc;
1668 while (!T.isNull()) {
1669 NestedTypes.push_back(T);
1671 // Retrieve the parent of a record type.
1672 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1673 // If this type is an explicit specialization, we're done.
1674 if (ClassTemplateSpecializationDecl *Spec
1675 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1676 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
1677 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1678 ExplicitSpecLoc = Spec->getLocation();
1681 } else if (Record->getTemplateSpecializationKind()
1682 == TSK_ExplicitSpecialization) {
1683 ExplicitSpecLoc = Record->getLocation();
1687 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1688 T = Context.getTypeDeclType(Parent);
1694 if (const TemplateSpecializationType *TST
1695 = T->getAs<TemplateSpecializationType>()) {
1696 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1697 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1698 T = Context.getTypeDeclType(Parent);
1705 // Look one step prior in a dependent template specialization type.
1706 if (const DependentTemplateSpecializationType *DependentTST
1707 = T->getAs<DependentTemplateSpecializationType>()) {
1708 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1709 T = QualType(NNS->getAsType(), 0);
1715 // Look one step prior in a dependent name type.
1716 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1717 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1718 T = QualType(NNS->getAsType(), 0);
1724 // Retrieve the parent of an enumeration type.
1725 if (const EnumType *EnumT = T->getAs<EnumType>()) {
1726 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1728 EnumDecl *Enum = EnumT->getDecl();
1730 // Get to the parent type.
1731 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1732 T = Context.getTypeDeclType(Parent);
1740 // Reverse the nested types list, since we want to traverse from the outermost
1741 // to the innermost while checking template-parameter-lists.
1742 std::reverse(NestedTypes.begin(), NestedTypes.end());
1744 // C++0x [temp.expl.spec]p17:
1745 // A member or a member template may be nested within many
1746 // enclosing class templates. In an explicit specialization for
1747 // such a member, the member declaration shall be preceded by a
1748 // template<> for each enclosing class template that is
1749 // explicitly specialized.
1750 bool SawNonEmptyTemplateParameterList = false;
1752 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
1753 if (SawNonEmptyTemplateParameterList) {
1754 Diag(DeclLoc, diag::err_specialize_member_of_template)
1755 << !Recovery << Range;
1757 IsExplicitSpecialization = false;
1764 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
1765 // Check that we can have an explicit specialization here.
1766 if (CheckExplicitSpecialization(Range, true))
1769 // We don't have a template header, but we should.
1770 SourceLocation ExpectedTemplateLoc;
1771 if (!ParamLists.empty())
1772 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
1774 ExpectedTemplateLoc = DeclStartLoc;
1776 Diag(DeclLoc, diag::err_template_spec_needs_header)
1778 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
1782 unsigned ParamIdx = 0;
1783 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
1785 T = NestedTypes[TypeIdx];
1787 // Whether we expect a 'template<>' header.
1788 bool NeedEmptyTemplateHeader = false;
1790 // Whether we expect a template header with parameters.
1791 bool NeedNonemptyTemplateHeader = false;
1793 // For a dependent type, the set of template parameters that we
1795 TemplateParameterList *ExpectedTemplateParams = nullptr;
1797 // C++0x [temp.expl.spec]p15:
1798 // A member or a member template may be nested within many enclosing
1799 // class templates. In an explicit specialization for such a member, the
1800 // member declaration shall be preceded by a template<> for each
1801 // enclosing class template that is explicitly specialized.
1802 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1803 if (ClassTemplatePartialSpecializationDecl *Partial
1804 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1805 ExpectedTemplateParams = Partial->getTemplateParameters();
1806 NeedNonemptyTemplateHeader = true;
1807 } else if (Record->isDependentType()) {
1808 if (Record->getDescribedClassTemplate()) {
1809 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1810 ->getTemplateParameters();
1811 NeedNonemptyTemplateHeader = true;
1813 } else if (ClassTemplateSpecializationDecl *Spec
1814 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1815 // C++0x [temp.expl.spec]p4:
1816 // Members of an explicitly specialized class template are defined
1817 // in the same manner as members of normal classes, and not using
1818 // the template<> syntax.
1819 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
1820 NeedEmptyTemplateHeader = true;
1823 } else if (Record->getTemplateSpecializationKind()) {
1824 if (Record->getTemplateSpecializationKind()
1825 != TSK_ExplicitSpecialization &&
1826 TypeIdx == NumTypes - 1)
1827 IsExplicitSpecialization = true;
1831 } else if (const TemplateSpecializationType *TST
1832 = T->getAs<TemplateSpecializationType>()) {
1833 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1834 ExpectedTemplateParams = Template->getTemplateParameters();
1835 NeedNonemptyTemplateHeader = true;
1837 } else if (T->getAs<DependentTemplateSpecializationType>()) {
1838 // FIXME: We actually could/should check the template arguments here
1839 // against the corresponding template parameter list.
1840 NeedNonemptyTemplateHeader = false;
1843 // C++ [temp.expl.spec]p16:
1844 // In an explicit specialization declaration for a member of a class
1845 // template or a member template that ap- pears in namespace scope, the
1846 // member template and some of its enclosing class templates may remain
1847 // unspecialized, except that the declaration shall not explicitly
1848 // specialize a class member template if its en- closing class templates
1849 // are not explicitly specialized as well.
1850 if (ParamIdx < ParamLists.size()) {
1851 if (ParamLists[ParamIdx]->size() == 0) {
1852 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1856 SawNonEmptyTemplateParameterList = true;
1859 if (NeedEmptyTemplateHeader) {
1860 // If we're on the last of the types, and we need a 'template<>' header
1861 // here, then it's an explicit specialization.
1862 if (TypeIdx == NumTypes - 1)
1863 IsExplicitSpecialization = true;
1865 if (ParamIdx < ParamLists.size()) {
1866 if (ParamLists[ParamIdx]->size() > 0) {
1867 // The header has template parameters when it shouldn't. Complain.
1868 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1869 diag::err_template_param_list_matches_nontemplate)
1871 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
1872 ParamLists[ParamIdx]->getRAngleLoc())
1873 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1878 // Consume this template header.
1884 if (DiagnoseMissingExplicitSpecialization(
1885 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
1891 if (NeedNonemptyTemplateHeader) {
1892 // In friend declarations we can have template-ids which don't
1893 // depend on the corresponding template parameter lists. But
1894 // assume that empty parameter lists are supposed to match this
1896 if (IsFriend && T->isDependentType()) {
1897 if (ParamIdx < ParamLists.size() &&
1898 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
1899 ExpectedTemplateParams = nullptr;
1904 if (ParamIdx < ParamLists.size()) {
1905 // Check the template parameter list, if we can.
1906 if (ExpectedTemplateParams &&
1907 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
1908 ExpectedTemplateParams,
1909 true, TPL_TemplateMatch))
1913 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
1914 TPC_ClassTemplateMember))
1921 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
1923 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1929 // If there were at least as many template-ids as there were template
1930 // parameter lists, then there are no template parameter lists remaining for
1931 // the declaration itself.
1932 if (ParamIdx >= ParamLists.size()) {
1933 if (TemplateId && !IsFriend) {
1934 // We don't have a template header for the declaration itself, but we
1936 IsExplicitSpecialization = true;
1937 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
1938 TemplateId->RAngleLoc));
1940 // Fabricate an empty template parameter list for the invented header.
1941 return TemplateParameterList::Create(Context, SourceLocation(),
1942 SourceLocation(), None,
1949 // If there were too many template parameter lists, complain about that now.
1950 if (ParamIdx < ParamLists.size() - 1) {
1951 bool HasAnyExplicitSpecHeader = false;
1952 bool AllExplicitSpecHeaders = true;
1953 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
1954 if (ParamLists[I]->size() == 0)
1955 HasAnyExplicitSpecHeader = true;
1957 AllExplicitSpecHeaders = false;
1960 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1961 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
1962 : diag::err_template_spec_extra_headers)
1963 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1964 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
1966 // If there was a specialization somewhere, such that 'template<>' is
1967 // not required, and there were any 'template<>' headers, note where the
1968 // specialization occurred.
1969 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
1970 Diag(ExplicitSpecLoc,
1971 diag::note_explicit_template_spec_does_not_need_header)
1972 << NestedTypes.back();
1974 // We have a template parameter list with no corresponding scope, which
1975 // means that the resulting template declaration can't be instantiated
1976 // properly (we'll end up with dependent nodes when we shouldn't).
1977 if (!AllExplicitSpecHeaders)
1981 // C++ [temp.expl.spec]p16:
1982 // In an explicit specialization declaration for a member of a class
1983 // template or a member template that ap- pears in namespace scope, the
1984 // member template and some of its enclosing class templates may remain
1985 // unspecialized, except that the declaration shall not explicitly
1986 // specialize a class member template if its en- closing class templates
1987 // are not explicitly specialized as well.
1988 if (ParamLists.back()->size() == 0 &&
1989 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1993 // Return the last template parameter list, which corresponds to the
1994 // entity being declared.
1995 return ParamLists.back();
1998 void Sema::NoteAllFoundTemplates(TemplateName Name) {
1999 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2000 Diag(Template->getLocation(), diag::note_template_declared_here)
2001 << (isa<FunctionTemplateDecl>(Template)
2003 : isa<ClassTemplateDecl>(Template)
2005 : isa<VarTemplateDecl>(Template)
2007 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2008 << Template->getDeclName();
2012 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
2013 for (OverloadedTemplateStorage::iterator I = OST->begin(),
2016 Diag((*I)->getLocation(), diag::note_template_declared_here)
2017 << 0 << (*I)->getDeclName();
2024 checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
2025 const SmallVectorImpl<TemplateArgument> &Converted,
2026 SourceLocation TemplateLoc,
2027 TemplateArgumentListInfo &TemplateArgs) {
2028 ASTContext &Context = SemaRef.getASTContext();
2029 switch (BTD->getBuiltinTemplateKind()) {
2030 case BTK__make_integer_seq:
2031 // Specializations of __make_integer_seq<S, T, N> are treated like
2032 // S<T, 0, ..., N-1>.
2034 // C++14 [inteseq.intseq]p1:
2035 // T shall be an integer type.
2036 if (!Converted[1].getAsType()->isIntegralType(Context)) {
2037 SemaRef.Diag(TemplateArgs[1].getLocation(),
2038 diag::err_integer_sequence_integral_element_type);
2042 // C++14 [inteseq.make]p1:
2043 // If N is negative the program is ill-formed.
2044 TemplateArgument NumArgsArg = Converted[2];
2045 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2047 SemaRef.Diag(TemplateArgs[2].getLocation(),
2048 diag::err_integer_sequence_negative_length);
2052 QualType ArgTy = NumArgsArg.getIntegralType();
2053 TemplateArgumentListInfo SyntheticTemplateArgs;
2054 // The type argument gets reused as the first template argument in the
2055 // synthetic template argument list.
2056 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2057 // Expand N into 0 ... N-1.
2058 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2060 TemplateArgument TA(Context, I, ArgTy);
2061 Expr *E = SemaRef.BuildExpressionFromIntegralTemplateArgument(
2062 TA, TemplateArgs[2].getLocation())
2064 SyntheticTemplateArgs.addArgument(
2065 TemplateArgumentLoc(TemplateArgument(E), E));
2067 // The first template argument will be reused as the template decl that
2068 // our synthetic template arguments will be applied to.
2069 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2070 TemplateLoc, SyntheticTemplateArgs);
2072 llvm_unreachable("unexpected BuiltinTemplateDecl!");
2075 QualType Sema::CheckTemplateIdType(TemplateName Name,
2076 SourceLocation TemplateLoc,
2077 TemplateArgumentListInfo &TemplateArgs) {
2078 DependentTemplateName *DTN
2079 = Name.getUnderlying().getAsDependentTemplateName();
2080 if (DTN && DTN->isIdentifier())
2081 // When building a template-id where the template-name is dependent,
2082 // assume the template is a type template. Either our assumption is
2083 // correct, or the code is ill-formed and will be diagnosed when the
2084 // dependent name is substituted.
2085 return Context.getDependentTemplateSpecializationType(ETK_None,
2086 DTN->getQualifier(),
2087 DTN->getIdentifier(),
2090 TemplateDecl *Template = Name.getAsTemplateDecl();
2091 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2092 isa<VarTemplateDecl>(Template)) {
2093 // We might have a substituted template template parameter pack. If so,
2094 // build a template specialization type for it.
2095 if (Name.getAsSubstTemplateTemplateParmPack())
2096 return Context.getTemplateSpecializationType(Name, TemplateArgs);
2098 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2100 NoteAllFoundTemplates(Name);
2104 // Check that the template argument list is well-formed for this
2106 SmallVector<TemplateArgument, 4> Converted;
2107 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
2113 bool InstantiationDependent = false;
2114 if (TypeAliasTemplateDecl *AliasTemplate =
2115 dyn_cast<TypeAliasTemplateDecl>(Template)) {
2116 // Find the canonical type for this type alias template specialization.
2117 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2118 if (Pattern->isInvalidDecl())
2121 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2122 Converted.data(), Converted.size());
2124 // Only substitute for the innermost template argument list.
2125 MultiLevelTemplateArgumentList TemplateArgLists;
2126 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
2127 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2128 for (unsigned I = 0; I < Depth; ++I)
2129 TemplateArgLists.addOuterTemplateArguments(None);
2131 LocalInstantiationScope Scope(*this);
2132 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
2133 if (Inst.isInvalid())
2136 CanonType = SubstType(Pattern->getUnderlyingType(),
2137 TemplateArgLists, AliasTemplate->getLocation(),
2138 AliasTemplate->getDeclName());
2139 if (CanonType.isNull())
2141 } else if (Name.isDependent() ||
2142 TemplateSpecializationType::anyDependentTemplateArguments(
2143 TemplateArgs, InstantiationDependent)) {
2144 // This class template specialization is a dependent
2145 // type. Therefore, its canonical type is another class template
2146 // specialization type that contains all of the converted
2147 // arguments in canonical form. This ensures that, e.g., A<T> and
2148 // A<T, T> have identical types when A is declared as:
2150 // template<typename T, typename U = T> struct A;
2151 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
2152 CanonType = Context.getTemplateSpecializationType(CanonName,
2156 // FIXME: CanonType is not actually the canonical type, and unfortunately
2157 // it is a TemplateSpecializationType that we will never use again.
2158 // In the future, we need to teach getTemplateSpecializationType to only
2159 // build the canonical type and return that to us.
2160 CanonType = Context.getCanonicalType(CanonType);
2162 // This might work out to be a current instantiation, in which
2163 // case the canonical type needs to be the InjectedClassNameType.
2165 // TODO: in theory this could be a simple hashtable lookup; most
2166 // changes to CurContext don't change the set of current
2168 if (isa<ClassTemplateDecl>(Template)) {
2169 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2170 // If we get out to a namespace, we're done.
2171 if (Ctx->isFileContext()) break;
2173 // If this isn't a record, keep looking.
2174 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2175 if (!Record) continue;
2177 // Look for one of the two cases with InjectedClassNameTypes
2178 // and check whether it's the same template.
2179 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2180 !Record->getDescribedClassTemplate())
2183 // Fetch the injected class name type and check whether its
2184 // injected type is equal to the type we just built.
2185 QualType ICNT = Context.getTypeDeclType(Record);
2186 QualType Injected = cast<InjectedClassNameType>(ICNT)
2187 ->getInjectedSpecializationType();
2189 if (CanonType != Injected->getCanonicalTypeInternal())
2192 // If so, the canonical type of this TST is the injected
2193 // class name type of the record we just found.
2194 assert(ICNT.isCanonical());
2199 } else if (ClassTemplateDecl *ClassTemplate
2200 = dyn_cast<ClassTemplateDecl>(Template)) {
2201 // Find the class template specialization declaration that
2202 // corresponds to these arguments.
2203 void *InsertPos = nullptr;
2204 ClassTemplateSpecializationDecl *Decl
2205 = ClassTemplate->findSpecialization(Converted, InsertPos);
2207 // This is the first time we have referenced this class template
2208 // specialization. Create the canonical declaration and add it to
2209 // the set of specializations.
2210 Decl = ClassTemplateSpecializationDecl::Create(Context,
2211 ClassTemplate->getTemplatedDecl()->getTagKind(),
2212 ClassTemplate->getDeclContext(),
2213 ClassTemplate->getTemplatedDecl()->getLocStart(),
2214 ClassTemplate->getLocation(),
2217 Converted.size(), nullptr);
2218 ClassTemplate->AddSpecialization(Decl, InsertPos);
2219 if (ClassTemplate->isOutOfLine())
2220 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
2223 // Diagnose uses of this specialization.
2224 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2226 CanonType = Context.getTypeDeclType(Decl);
2227 assert(isa<RecordType>(CanonType) &&
2228 "type of non-dependent specialization is not a RecordType");
2229 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
2230 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
2234 // Build the fully-sugared type for this class template
2235 // specialization, which refers back to the class template
2236 // specialization we created or found.
2237 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
2241 Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
2242 TemplateTy TemplateD, SourceLocation TemplateLoc,
2243 SourceLocation LAngleLoc,
2244 ASTTemplateArgsPtr TemplateArgsIn,
2245 SourceLocation RAngleLoc,
2246 bool IsCtorOrDtorName) {
2250 TemplateName Template = TemplateD.get();
2252 // Translate the parser's template argument list in our AST format.
2253 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2254 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2256 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2258 = Context.getDependentTemplateSpecializationType(ETK_None,
2259 DTN->getQualifier(),
2260 DTN->getIdentifier(),
2262 // Build type-source information.
2264 DependentTemplateSpecializationTypeLoc SpecTL
2265 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2266 SpecTL.setElaboratedKeywordLoc(SourceLocation());
2267 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
2268 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2269 SpecTL.setTemplateNameLoc(TemplateLoc);
2270 SpecTL.setLAngleLoc(LAngleLoc);
2271 SpecTL.setRAngleLoc(RAngleLoc);
2272 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2273 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2274 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2277 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2279 if (Result.isNull())
2282 // Build type-source information.
2284 TemplateSpecializationTypeLoc SpecTL
2285 = TLB.push<TemplateSpecializationTypeLoc>(Result);
2286 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2287 SpecTL.setTemplateNameLoc(TemplateLoc);
2288 SpecTL.setLAngleLoc(LAngleLoc);
2289 SpecTL.setRAngleLoc(RAngleLoc);
2290 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2291 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
2293 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2294 // constructor or destructor name (in such a case, the scope specifier
2295 // will be attached to the enclosing Decl or Expr node).
2296 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
2297 // Create an elaborated-type-specifier containing the nested-name-specifier.
2298 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2299 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
2300 ElabTL.setElaboratedKeywordLoc(SourceLocation());
2301 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2304 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
2307 TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
2308 TypeSpecifierType TagSpec,
2309 SourceLocation TagLoc,
2311 SourceLocation TemplateKWLoc,
2312 TemplateTy TemplateD,
2313 SourceLocation TemplateLoc,
2314 SourceLocation LAngleLoc,
2315 ASTTemplateArgsPtr TemplateArgsIn,
2316 SourceLocation RAngleLoc) {
2317 TemplateName Template = TemplateD.get();
2319 // Translate the parser's template argument list in our AST format.
2320 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2321 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2323 // Determine the tag kind
2324 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
2325 ElaboratedTypeKeyword Keyword
2326 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
2328 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2329 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
2330 DTN->getQualifier(),
2331 DTN->getIdentifier(),
2334 // Build type-source information.
2336 DependentTemplateSpecializationTypeLoc SpecTL
2337 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2338 SpecTL.setElaboratedKeywordLoc(TagLoc);
2339 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
2340 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2341 SpecTL.setTemplateNameLoc(TemplateLoc);
2342 SpecTL.setLAngleLoc(LAngleLoc);
2343 SpecTL.setRAngleLoc(RAngleLoc);
2344 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2345 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2346 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2349 if (TypeAliasTemplateDecl *TAT =
2350 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2351 // C++0x [dcl.type.elab]p2:
2352 // If the identifier resolves to a typedef-name or the simple-template-id
2353 // resolves to an alias template specialization, the
2354 // elaborated-type-specifier is ill-formed.
2355 Diag(TemplateLoc, diag::err_tag_reference_non_tag) << 4;
2356 Diag(TAT->getLocation(), diag::note_declared_at);
2359 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2360 if (Result.isNull())
2361 return TypeResult(true);
2363 // Check the tag kind
2364 if (const RecordType *RT = Result->getAs<RecordType>()) {
2365 RecordDecl *D = RT->getDecl();
2367 IdentifierInfo *Id = D->getIdentifier();
2368 assert(Id && "templated class must have an identifier");
2370 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
2372 Diag(TagLoc, diag::err_use_with_wrong_tag)
2374 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
2375 Diag(D->getLocation(), diag::note_previous_use);
2379 // Provide source-location information for the template specialization.
2381 TemplateSpecializationTypeLoc SpecTL
2382 = TLB.push<TemplateSpecializationTypeLoc>(Result);
2383 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2384 SpecTL.setTemplateNameLoc(TemplateLoc);
2385 SpecTL.setLAngleLoc(LAngleLoc);
2386 SpecTL.setRAngleLoc(RAngleLoc);
2387 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2388 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
2390 // Construct an elaborated type containing the nested-name-specifier (if any)
2392 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2393 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
2394 ElabTL.setElaboratedKeywordLoc(TagLoc);
2395 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2396 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
2399 static bool CheckTemplatePartialSpecializationArgs(
2400 Sema &S, SourceLocation NameLoc, TemplateParameterList *TemplateParams,
2401 unsigned ExplicitArgs, SmallVectorImpl<TemplateArgument> &TemplateArgs);
2403 static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
2404 NamedDecl *PrevDecl,
2406 bool IsPartialSpecialization);
2408 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
2410 static bool isTemplateArgumentTemplateParameter(
2411 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
2412 switch (Arg.getKind()) {
2413 case TemplateArgument::Null:
2414 case TemplateArgument::NullPtr:
2415 case TemplateArgument::Integral:
2416 case TemplateArgument::Declaration:
2417 case TemplateArgument::Pack:
2418 case TemplateArgument::TemplateExpansion:
2421 case TemplateArgument::Type: {
2422 QualType Type = Arg.getAsType();
2423 const TemplateTypeParmType *TPT =
2424 Arg.getAsType()->getAs<TemplateTypeParmType>();
2425 return TPT && !Type.hasQualifiers() &&
2426 TPT->getDepth() == Depth && TPT->getIndex() == Index;
2429 case TemplateArgument::Expression: {
2430 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
2431 if (!DRE || !DRE->getDecl())
2433 const NonTypeTemplateParmDecl *NTTP =
2434 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2435 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
2438 case TemplateArgument::Template:
2439 const TemplateTemplateParmDecl *TTP =
2440 dyn_cast_or_null<TemplateTemplateParmDecl>(
2441 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
2442 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
2444 llvm_unreachable("unexpected kind of template argument");
2447 static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
2448 ArrayRef<TemplateArgument> Args) {
2449 if (Params->size() != Args.size())
2452 unsigned Depth = Params->getDepth();
2454 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2455 TemplateArgument Arg = Args[I];
2457 // If the parameter is a pack expansion, the argument must be a pack
2458 // whose only element is a pack expansion.
2459 if (Params->getParam(I)->isParameterPack()) {
2460 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
2461 !Arg.pack_begin()->isPackExpansion())
2463 Arg = Arg.pack_begin()->getPackExpansionPattern();
2466 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
2473 /// Convert the parser's template argument list representation into our form.
2474 static TemplateArgumentListInfo
2475 makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
2476 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
2477 TemplateId.RAngleLoc);
2478 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
2479 TemplateId.NumArgs);
2480 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
2481 return TemplateArgs;
2484 DeclResult Sema::ActOnVarTemplateSpecialization(
2485 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
2486 TemplateParameterList *TemplateParams, StorageClass SC,
2487 bool IsPartialSpecialization) {
2488 // D must be variable template id.
2489 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
2490 "Variable template specialization is declared with a template it.");
2492 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
2493 TemplateArgumentListInfo TemplateArgs =
2494 makeTemplateArgumentListInfo(*this, *TemplateId);
2495 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
2496 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
2497 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
2499 TemplateName Name = TemplateId->Template.get();
2501 // The template-id must name a variable template.
2502 VarTemplateDecl *VarTemplate =
2503 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
2505 NamedDecl *FnTemplate;
2506 if (auto *OTS = Name.getAsOverloadedTemplate())
2507 FnTemplate = *OTS->begin();
2509 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
2511 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
2512 << FnTemplate->getDeclName();
2513 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
2514 << IsPartialSpecialization;
2517 // Check for unexpanded parameter packs in any of the template arguments.
2518 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2519 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
2520 UPPC_PartialSpecialization))
2523 // Check that the template argument list is well-formed for this
2525 SmallVector<TemplateArgument, 4> Converted;
2526 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
2530 // Find the variable template (partial) specialization declaration that
2531 // corresponds to these arguments.
2532 if (IsPartialSpecialization) {
2533 if (CheckTemplatePartialSpecializationArgs(
2534 *this, TemplateNameLoc, VarTemplate->getTemplateParameters(),
2535 TemplateArgs.size(), Converted))
2538 bool InstantiationDependent;
2539 if (!Name.isDependent() &&
2540 !TemplateSpecializationType::anyDependentTemplateArguments(
2541 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
2542 InstantiationDependent)) {
2543 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
2544 << VarTemplate->getDeclName();
2545 IsPartialSpecialization = false;
2548 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
2550 // C++ [temp.class.spec]p9b3:
2552 // -- The argument list of the specialization shall not be identical
2553 // to the implicit argument list of the primary template.
2554 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2555 << /*variable template*/ 1
2556 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
2557 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
2558 // FIXME: Recover from this by treating the declaration as a redeclaration
2559 // of the primary template.
2564 void *InsertPos = nullptr;
2565 VarTemplateSpecializationDecl *PrevDecl = nullptr;
2567 if (IsPartialSpecialization)
2568 // FIXME: Template parameter list matters too
2569 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
2571 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
2573 VarTemplateSpecializationDecl *Specialization = nullptr;
2575 // Check whether we can declare a variable template specialization in
2576 // the current scope.
2577 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
2579 IsPartialSpecialization))
2582 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2583 // Since the only prior variable template specialization with these
2584 // arguments was referenced but not declared, reuse that
2585 // declaration node as our own, updating its source location and
2586 // the list of outer template parameters to reflect our new declaration.
2587 Specialization = PrevDecl;
2588 Specialization->setLocation(TemplateNameLoc);
2590 } else if (IsPartialSpecialization) {
2591 // Create a new class template partial specialization declaration node.
2592 VarTemplatePartialSpecializationDecl *PrevPartial =
2593 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
2594 VarTemplatePartialSpecializationDecl *Partial =
2595 VarTemplatePartialSpecializationDecl::Create(
2596 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
2597 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
2598 Converted.data(), Converted.size(), TemplateArgs);
2601 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
2602 Specialization = Partial;
2604 // If we are providing an explicit specialization of a member variable
2605 // template specialization, make a note of that.
2606 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
2607 PrevPartial->setMemberSpecialization();
2609 // Check that all of the template parameters of the variable template
2610 // partial specialization are deducible from the template
2611 // arguments. If not, this variable template partial specialization
2612 // will never be used.
2613 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
2614 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2615 TemplateParams->getDepth(), DeducibleParams);
2617 if (!DeducibleParams.all()) {
2618 unsigned NumNonDeducible =
2619 DeducibleParams.size() - DeducibleParams.count();
2620 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2621 << /*variable template*/ 1 << (NumNonDeducible > 1)
2622 << SourceRange(TemplateNameLoc, RAngleLoc);
2623 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2624 if (!DeducibleParams[I]) {
2625 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2626 if (Param->getDeclName())
2627 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2628 << Param->getDeclName();
2630 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2636 // Create a new class template specialization declaration node for
2637 // this explicit specialization or friend declaration.
2638 Specialization = VarTemplateSpecializationDecl::Create(
2639 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
2640 VarTemplate, DI->getType(), DI, SC, Converted.data(), Converted.size());
2641 Specialization->setTemplateArgsInfo(TemplateArgs);
2644 VarTemplate->AddSpecialization(Specialization, InsertPos);
2647 // C++ [temp.expl.spec]p6:
2648 // If a template, a member template or the member of a class template is
2649 // explicitly specialized then that specialization shall be declared
2650 // before the first use of that specialization that would cause an implicit
2651 // instantiation to take place, in every translation unit in which such a
2652 // use occurs; no diagnostic is required.
2653 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
2655 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
2656 // Is there any previous explicit specialization declaration?
2657 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
2664 SourceRange Range(TemplateNameLoc, RAngleLoc);
2665 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
2668 Diag(PrevDecl->getPointOfInstantiation(),
2669 diag::note_instantiation_required_here)
2670 << (PrevDecl->getTemplateSpecializationKind() !=
2671 TSK_ImplicitInstantiation);
2676 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
2677 Specialization->setLexicalDeclContext(CurContext);
2679 // Add the specialization into its lexical context, so that it can
2680 // be seen when iterating through the list of declarations in that
2681 // context. However, specializations are not found by name lookup.
2682 CurContext->addDecl(Specialization);
2684 // Note that this is an explicit specialization.
2685 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2688 // Check that this isn't a redefinition of this specialization,
2689 // merging with previous declarations.
2690 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
2692 PrevSpec.addDecl(PrevDecl);
2693 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
2694 } else if (Specialization->isStaticDataMember() &&
2695 Specialization->isOutOfLine()) {
2696 Specialization->setAccess(VarTemplate->getAccess());
2699 // Link instantiations of static data members back to the template from
2700 // which they were instantiated.
2701 if (Specialization->isStaticDataMember())
2702 Specialization->setInstantiationOfStaticDataMember(
2703 VarTemplate->getTemplatedDecl(),
2704 Specialization->getSpecializationKind());
2706 return Specialization;
2710 /// \brief A partial specialization whose template arguments have matched
2711 /// a given template-id.
2712 struct PartialSpecMatchResult {
2713 VarTemplatePartialSpecializationDecl *Partial;
2714 TemplateArgumentList *Args;
2716 } // end anonymous namespace
2719 Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
2720 SourceLocation TemplateNameLoc,
2721 const TemplateArgumentListInfo &TemplateArgs) {
2722 assert(Template && "A variable template id without template?");
2724 // Check that the template argument list is well-formed for this template.
2725 SmallVector<TemplateArgument, 4> Converted;
2726 if (CheckTemplateArgumentList(
2727 Template, TemplateNameLoc,
2728 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
2732 // Find the variable template specialization declaration that
2733 // corresponds to these arguments.
2734 void *InsertPos = nullptr;
2735 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
2736 Converted, InsertPos))
2737 // If we already have a variable template specialization, return it.
2740 // This is the first time we have referenced this variable template
2741 // specialization. Create the canonical declaration and add it to
2742 // the set of specializations, based on the closest partial specialization
2743 // that it represents. That is,
2744 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
2745 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
2746 Converted.data(), Converted.size());
2747 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
2748 bool AmbiguousPartialSpec = false;
2749 typedef PartialSpecMatchResult MatchResult;
2750 SmallVector<MatchResult, 4> Matched;
2751 SourceLocation PointOfInstantiation = TemplateNameLoc;
2752 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
2753 /*ForTakingAddress=*/false);
2755 // 1. Attempt to find the closest partial specialization that this
2756 // specializes, if any.
2757 // If any of the template arguments is dependent, then this is probably
2758 // a placeholder for an incomplete declarative context; which must be
2759 // complete by instantiation time. Thus, do not search through the partial
2760 // specializations yet.
2761 // TODO: Unify with InstantiateClassTemplateSpecialization()?
2762 // Perhaps better after unification of DeduceTemplateArguments() and
2763 // getMoreSpecializedPartialSpecialization().
2764 bool InstantiationDependent = false;
2765 if (!TemplateSpecializationType::anyDependentTemplateArguments(
2766 TemplateArgs, InstantiationDependent)) {
2768 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2769 Template->getPartialSpecializations(PartialSpecs);
2771 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2772 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2773 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2775 if (TemplateDeductionResult Result =
2776 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
2777 // Store the failed-deduction information for use in diagnostics, later.
2778 // TODO: Actually use the failed-deduction info?
2779 FailedCandidates.addCandidate()
2780 .set(Partial, MakeDeductionFailureInfo(Context, Result, Info));
2783 Matched.push_back(PartialSpecMatchResult());
2784 Matched.back().Partial = Partial;
2785 Matched.back().Args = Info.take();
2789 if (Matched.size() >= 1) {
2790 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
2791 if (Matched.size() == 1) {
2792 // -- If exactly one matching specialization is found, the
2793 // instantiation is generated from that specialization.
2794 // We don't need to do anything for this.
2796 // -- If more than one matching specialization is found, the
2797 // partial order rules (14.5.4.2) are used to determine
2798 // whether one of the specializations is more specialized
2799 // than the others. If none of the specializations is more
2800 // specialized than all of the other matching
2801 // specializations, then the use of the variable template is
2802 // ambiguous and the program is ill-formed.
2803 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
2804 PEnd = Matched.end();
2806 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2807 PointOfInstantiation) ==
2812 // Determine if the best partial specialization is more specialized than
2814 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2815 PEnd = Matched.end();
2817 if (P != Best && getMoreSpecializedPartialSpecialization(
2818 P->Partial, Best->Partial,
2819 PointOfInstantiation) != Best->Partial) {
2820 AmbiguousPartialSpec = true;
2826 // Instantiate using the best variable template partial specialization.
2827 InstantiationPattern = Best->Partial;
2828 InstantiationArgs = Best->Args;
2830 // -- If no match is found, the instantiation is generated
2831 // from the primary template.
2832 // InstantiationPattern = Template->getTemplatedDecl();
2836 // 2. Create the canonical declaration.
2837 // Note that we do not instantiate the variable just yet, since
2838 // instantiation is handled in DoMarkVarDeclReferenced().
2839 // FIXME: LateAttrs et al.?
2840 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
2841 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
2842 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
2846 if (AmbiguousPartialSpec) {
2847 // Partial ordering did not produce a clear winner. Complain.
2848 Decl->setInvalidDecl();
2849 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2852 // Print the matching partial specializations.
2853 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2854 PEnd = Matched.end();
2856 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2857 << getTemplateArgumentBindingsText(
2858 P->Partial->getTemplateParameters(), *P->Args);
2862 if (VarTemplatePartialSpecializationDecl *D =
2863 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
2864 Decl->setInstantiationOf(D, InstantiationArgs);
2866 assert(Decl && "No variable template specialization?");
2871 Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
2872 const DeclarationNameInfo &NameInfo,
2873 VarTemplateDecl *Template, SourceLocation TemplateLoc,
2874 const TemplateArgumentListInfo *TemplateArgs) {
2876 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
2878 if (Decl.isInvalid())
2881 VarDecl *Var = cast<VarDecl>(Decl.get());
2882 if (!Var->getTemplateSpecializationKind())
2883 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
2886 // Build an ordinary singleton decl ref.
2887 return BuildDeclarationNameExpr(SS, NameInfo, Var,
2888 /*FoundD=*/nullptr, TemplateArgs);
2891 ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
2892 SourceLocation TemplateKWLoc,
2895 const TemplateArgumentListInfo *TemplateArgs) {
2896 // FIXME: Can we do any checking at this point? I guess we could check the
2897 // template arguments that we have against the template name, if the template
2898 // name refers to a single template. That's not a terribly common case,
2900 // foo<int> could identify a single function unambiguously
2901 // This approach does NOT work, since f<int>(1);
2902 // gets resolved prior to resorting to overload resolution
2903 // i.e., template<class T> void f(double);
2904 // vs template<class T, class U> void f(U);
2906 // These should be filtered out by our callers.
2907 assert(!R.empty() && "empty lookup results when building templateid");
2908 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
2910 // In C++1y, check variable template ids.
2911 bool InstantiationDependent;
2912 if (R.getAsSingle<VarTemplateDecl>() &&
2913 !TemplateSpecializationType::anyDependentTemplateArguments(
2914 *TemplateArgs, InstantiationDependent)) {
2915 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
2916 R.getAsSingle<VarTemplateDecl>(),
2917 TemplateKWLoc, TemplateArgs);
2920 // We don't want lookup warnings at this point.
2921 R.suppressDiagnostics();
2923 UnresolvedLookupExpr *ULE
2924 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2925 SS.getWithLocInContext(Context),
2927 R.getLookupNameInfo(),
2928 RequiresADL, TemplateArgs,
2929 R.begin(), R.end());
2934 // We actually only call this from template instantiation.
2936 Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
2937 SourceLocation TemplateKWLoc,
2938 const DeclarationNameInfo &NameInfo,
2939 const TemplateArgumentListInfo *TemplateArgs) {
2941 assert(TemplateArgs || TemplateKWLoc.isValid());
2943 if (!(DC = computeDeclContext(SS, false)) ||
2944 DC->isDependentContext() ||
2945 RequireCompleteDeclContext(SS, DC))
2946 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
2948 bool MemberOfUnknownSpecialization;
2949 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2950 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
2951 MemberOfUnknownSpecialization);
2953 if (R.isAmbiguous())
2957 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
2958 << NameInfo.getName() << SS.getRange();
2962 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
2963 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
2965 << NameInfo.getName().getAsString() << SS.getRange();
2966 Diag(Temp->getLocation(), diag::note_referenced_class_template);
2970 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
2973 /// \brief Form a dependent template name.
2975 /// This action forms a dependent template name given the template
2976 /// name and its (presumably dependent) scope specifier. For
2977 /// example, given "MetaFun::template apply", the scope specifier \p
2978 /// SS will be "MetaFun::", \p TemplateKWLoc contains the location
2979 /// of the "template" keyword, and "apply" is the \p Name.
2980 TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
2982 SourceLocation TemplateKWLoc,
2983 UnqualifiedId &Name,
2984 ParsedType ObjectType,
2985 bool EnteringContext,
2986 TemplateTy &Result) {
2987 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
2989 getLangOpts().CPlusPlus11 ?
2990 diag::warn_cxx98_compat_template_outside_of_template :
2991 diag::ext_template_outside_of_template)
2992 << FixItHint::CreateRemoval(TemplateKWLoc);
2994 DeclContext *LookupCtx = nullptr;
2996 LookupCtx = computeDeclContext(SS, EnteringContext);
2997 if (!LookupCtx && ObjectType)
2998 LookupCtx = computeDeclContext(ObjectType.get());
3000 // C++0x [temp.names]p5:
3001 // If a name prefixed by the keyword template is not the name of
3002 // a template, the program is ill-formed. [Note: the keyword
3003 // template may not be applied to non-template members of class
3004 // templates. -end note ] [ Note: as is the case with the
3005 // typename prefix, the template prefix is allowed in cases
3006 // where it is not strictly necessary; i.e., when the
3007 // nested-name-specifier or the expression on the left of the ->
3008 // or . is not dependent on a template-parameter, or the use
3009 // does not appear in the scope of a template. -end note]
3011 // Note: C++03 was more strict here, because it banned the use of
3012 // the "template" keyword prior to a template-name that was not a
3013 // dependent name. C++ DR468 relaxed this requirement (the
3014 // "template" keyword is now permitted). We follow the C++0x
3015 // rules, even in C++03 mode with a warning, retroactively applying the DR.
3016 bool MemberOfUnknownSpecialization;
3017 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
3018 ObjectType, EnteringContext, Result,
3019 MemberOfUnknownSpecialization);
3020 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
3021 isa<CXXRecordDecl>(LookupCtx) &&
3022 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
3023 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
3024 // This is a dependent template. Handle it below.
3025 } else if (TNK == TNK_Non_template) {
3026 Diag(Name.getLocStart(),
3027 diag::err_template_kw_refers_to_non_template)
3028 << GetNameFromUnqualifiedId(Name).getName()
3029 << Name.getSourceRange()
3031 return TNK_Non_template;
3033 // We found something; return it.
3038 NestedNameSpecifier *Qualifier = SS.getScopeRep();
3040 switch (Name.getKind()) {
3041 case UnqualifiedId::IK_Identifier:
3042 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
3044 return TNK_Dependent_template_name;
3046 case UnqualifiedId::IK_OperatorFunctionId:
3047 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
3048 Name.OperatorFunctionId.Operator));
3049 return TNK_Function_template;
3051 case UnqualifiedId::IK_LiteralOperatorId:
3052 llvm_unreachable("literal operator id cannot have a dependent scope");
3058 Diag(Name.getLocStart(),
3059 diag::err_template_kw_refers_to_non_template)
3060 << GetNameFromUnqualifiedId(Name).getName()
3061 << Name.getSourceRange()
3063 return TNK_Non_template;
3066 bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
3067 TemplateArgumentLoc &AL,
3068 SmallVectorImpl<TemplateArgument> &Converted) {
3069 const TemplateArgument &Arg = AL.getArgument();
3071 TypeSourceInfo *TSI = nullptr;
3073 // Check template type parameter.
3074 switch(Arg.getKind()) {
3075 case TemplateArgument::Type:
3076 // C++ [temp.arg.type]p1:
3077 // A template-argument for a template-parameter which is a
3078 // type shall be a type-id.
3079 ArgType = Arg.getAsType();
3080 TSI = AL.getTypeSourceInfo();
3082 case TemplateArgument::Template: {
3083 // We have a template type parameter but the template argument
3084 // is a template without any arguments.
3085 SourceRange SR = AL.getSourceRange();
3086 TemplateName Name = Arg.getAsTemplate();
3087 Diag(SR.getBegin(), diag::err_template_missing_args)
3089 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3090 Diag(Decl->getLocation(), diag::note_template_decl_here);
3094 case TemplateArgument::Expression: {
3095 // We have a template type parameter but the template argument is an
3096 // expression; see if maybe it is missing the "typename" keyword.
3098 DeclarationNameInfo NameInfo;
3100 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3101 SS.Adopt(ArgExpr->getQualifierLoc());
3102 NameInfo = ArgExpr->getNameInfo();
3103 } else if (DependentScopeDeclRefExpr *ArgExpr =
3104 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3105 SS.Adopt(ArgExpr->getQualifierLoc());
3106 NameInfo = ArgExpr->getNameInfo();
3107 } else if (CXXDependentScopeMemberExpr *ArgExpr =
3108 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
3109 if (ArgExpr->isImplicitAccess()) {
3110 SS.Adopt(ArgExpr->getQualifierLoc());
3111 NameInfo = ArgExpr->getMemberNameInfo();
3115 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
3116 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3117 LookupParsedName(Result, CurScope, &SS);
3119 if (Result.getAsSingle<TypeDecl>() ||
3120 Result.getResultKind() ==
3121 LookupResult::NotFoundInCurrentInstantiation) {
3122 // Suggest that the user add 'typename' before the NNS.
3123 SourceLocation Loc = AL.getSourceRange().getBegin();
3124 Diag(Loc, getLangOpts().MSVCCompat
3125 ? diag::ext_ms_template_type_arg_missing_typename
3126 : diag::err_template_arg_must_be_type_suggest)
3127 << FixItHint::CreateInsertion(Loc, "typename ");
3128 Diag(Param->getLocation(), diag::note_template_param_here);
3130 // Recover by synthesizing a type using the location information that we
3133 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
3135 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
3136 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
3137 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3138 TL.setNameLoc(NameInfo.getLoc());
3139 TSI = TLB.getTypeSourceInfo(Context, ArgType);
3141 // Overwrite our input TemplateArgumentLoc so that we can recover
3143 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
3144 TemplateArgumentLocInfo(TSI));
3152 // We have a template type parameter but the template argument
3154 SourceRange SR = AL.getSourceRange();
3155 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
3156 Diag(Param->getLocation(), diag::note_template_param_here);
3162 if (CheckTemplateArgument(Param, TSI))
3165 // Add the converted template type argument.
3166 ArgType = Context.getCanonicalType(ArgType);
3169 // If an explicitly-specified template argument type is a lifetime type
3170 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
3171 if (getLangOpts().ObjCAutoRefCount &&
3172 ArgType->isObjCLifetimeType() &&
3173 !ArgType.getObjCLifetime()) {
3175 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
3176 ArgType = Context.getQualifiedType(ArgType, Qs);
3179 Converted.push_back(TemplateArgument(ArgType));
3183 /// \brief Substitute template arguments into the default template argument for
3184 /// the given template type parameter.
3186 /// \param SemaRef the semantic analysis object for which we are performing
3187 /// the substitution.
3189 /// \param Template the template that we are synthesizing template arguments
3192 /// \param TemplateLoc the location of the template name that started the
3193 /// template-id we are checking.
3195 /// \param RAngleLoc the location of the right angle bracket ('>') that
3196 /// terminates the template-id.
3198 /// \param Param the template template parameter whose default we are
3199 /// substituting into.
3201 /// \param Converted the list of template arguments provided for template
3202 /// parameters that precede \p Param in the template parameter list.
3203 /// \returns the substituted template argument, or NULL if an error occurred.
3204 static TypeSourceInfo *
3205 SubstDefaultTemplateArgument(Sema &SemaRef,
3206 TemplateDecl *Template,
3207 SourceLocation TemplateLoc,
3208 SourceLocation RAngleLoc,
3209 TemplateTypeParmDecl *Param,
3210 SmallVectorImpl<TemplateArgument> &Converted) {
3211 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
3213 // If the argument type is dependent, instantiate it now based
3214 // on the previously-computed template arguments.
3215 if (ArgType->getType()->isDependentType()) {
3216 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
3217 Template, Converted,
3218 SourceRange(TemplateLoc, RAngleLoc));
3219 if (Inst.isInvalid())
3222 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3223 Converted.data(), Converted.size());
3225 // Only substitute for the innermost template argument list.
3226 MultiLevelTemplateArgumentList TemplateArgLists;
3227 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3228 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3229 TemplateArgLists.addOuterTemplateArguments(None);
3231 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
3233 SemaRef.SubstType(ArgType, TemplateArgLists,
3234 Param->getDefaultArgumentLoc(), Param->getDeclName());
3240 /// \brief Substitute template arguments into the default template argument for
3241 /// the given non-type template parameter.
3243 /// \param SemaRef the semantic analysis object for which we are performing
3244 /// the substitution.
3246 /// \param Template the template that we are synthesizing template arguments
3249 /// \param TemplateLoc the location of the template name that started the
3250 /// template-id we are checking.
3252 /// \param RAngleLoc the location of the right angle bracket ('>') that
3253 /// terminates the template-id.
3255 /// \param Param the non-type template parameter whose default we are
3256 /// substituting into.
3258 /// \param Converted the list of template arguments provided for template
3259 /// parameters that precede \p Param in the template parameter list.
3261 /// \returns the substituted template argument, or NULL if an error occurred.
3263 SubstDefaultTemplateArgument(Sema &SemaRef,
3264 TemplateDecl *Template,
3265 SourceLocation TemplateLoc,
3266 SourceLocation RAngleLoc,
3267 NonTypeTemplateParmDecl *Param,
3268 SmallVectorImpl<TemplateArgument> &Converted) {
3269 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
3270 Template, Converted,
3271 SourceRange(TemplateLoc, RAngleLoc));
3272 if (Inst.isInvalid())
3275 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3276 Converted.data(), Converted.size());
3278 // Only substitute for the innermost template argument list.
3279 MultiLevelTemplateArgumentList TemplateArgLists;
3280 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3281 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3282 TemplateArgLists.addOuterTemplateArguments(None);
3284 EnterExpressionEvaluationContext ConstantEvaluated(SemaRef,
3285 Sema::ConstantEvaluated);
3286 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
3289 /// \brief Substitute template arguments into the default template argument for
3290 /// the given template template parameter.
3292 /// \param SemaRef the semantic analysis object for which we are performing
3293 /// the substitution.
3295 /// \param Template the template that we are synthesizing template arguments
3298 /// \param TemplateLoc the location of the template name that started the
3299 /// template-id we are checking.
3301 /// \param RAngleLoc the location of the right angle bracket ('>') that
3302 /// terminates the template-id.
3304 /// \param Param the template template parameter whose default we are
3305 /// substituting into.
3307 /// \param Converted the list of template arguments provided for template
3308 /// parameters that precede \p Param in the template parameter list.
3310 /// \param QualifierLoc Will be set to the nested-name-specifier (with
3311 /// source-location information) that precedes the template name.
3313 /// \returns the substituted template argument, or NULL if an error occurred.
3315 SubstDefaultTemplateArgument(Sema &SemaRef,
3316 TemplateDecl *Template,
3317 SourceLocation TemplateLoc,
3318 SourceLocation RAngleLoc,
3319 TemplateTemplateParmDecl *Param,
3320 SmallVectorImpl<TemplateArgument> &Converted,
3321 NestedNameSpecifierLoc &QualifierLoc) {
3322 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Template, Converted,
3323 SourceRange(TemplateLoc, RAngleLoc));
3324 if (Inst.isInvalid())
3325 return TemplateName();
3327 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3328 Converted.data(), Converted.size());
3330 // Only substitute for the innermost template argument list.
3331 MultiLevelTemplateArgumentList TemplateArgLists;
3332 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3333 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3334 TemplateArgLists.addOuterTemplateArguments(None);
3336 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
3337 // Substitute into the nested-name-specifier first,
3338 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
3341 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
3343 return TemplateName();
3346 return SemaRef.SubstTemplateName(
3348 Param->getDefaultArgument().getArgument().getAsTemplate(),
3349 Param->getDefaultArgument().getTemplateNameLoc(),
3353 /// \brief If the given template parameter has a default template
3354 /// argument, substitute into that default template argument and
3355 /// return the corresponding template argument.
3357 Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
3358 SourceLocation TemplateLoc,
3359 SourceLocation RAngleLoc,
3361 SmallVectorImpl<TemplateArgument>
3363 bool &HasDefaultArg) {
3364 HasDefaultArg = false;
3366 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
3367 if (!hasVisibleDefaultArgument(TypeParm))
3368 return TemplateArgumentLoc();
3370 HasDefaultArg = true;
3371 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
3377 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3379 return TemplateArgumentLoc();
3382 if (NonTypeTemplateParmDecl *NonTypeParm
3383 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3384 if (!hasVisibleDefaultArgument(NonTypeParm))
3385 return TemplateArgumentLoc();
3387 HasDefaultArg = true;
3388 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
3393 if (Arg.isInvalid())
3394 return TemplateArgumentLoc();
3396 Expr *ArgE = Arg.getAs<Expr>();
3397 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
3400 TemplateTemplateParmDecl *TempTempParm
3401 = cast<TemplateTemplateParmDecl>(Param);
3402 if (!hasVisibleDefaultArgument(TempTempParm))
3403 return TemplateArgumentLoc();
3405 HasDefaultArg = true;
3406 NestedNameSpecifierLoc QualifierLoc;
3407 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
3414 return TemplateArgumentLoc();
3416 return TemplateArgumentLoc(TemplateArgument(TName),
3417 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
3418 TempTempParm->getDefaultArgument().getTemplateNameLoc());
3421 /// \brief Check that the given template argument corresponds to the given
3422 /// template parameter.
3424 /// \param Param The template parameter against which the argument will be
3427 /// \param Arg The template argument, which may be updated due to conversions.
3429 /// \param Template The template in which the template argument resides.
3431 /// \param TemplateLoc The location of the template name for the template
3432 /// whose argument list we're matching.
3434 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
3435 /// the template argument list.
3437 /// \param ArgumentPackIndex The index into the argument pack where this
3438 /// argument will be placed. Only valid if the parameter is a parameter pack.
3440 /// \param Converted The checked, converted argument will be added to the
3441 /// end of this small vector.
3443 /// \param CTAK Describes how we arrived at this particular template argument:
3444 /// explicitly written, deduced, etc.
3446 /// \returns true on error, false otherwise.
3447 bool Sema::CheckTemplateArgument(NamedDecl *Param,
3448 TemplateArgumentLoc &Arg,
3449 NamedDecl *Template,
3450 SourceLocation TemplateLoc,
3451 SourceLocation RAngleLoc,
3452 unsigned ArgumentPackIndex,
3453 SmallVectorImpl<TemplateArgument> &Converted,
3454 CheckTemplateArgumentKind CTAK) {
3455 // Check template type parameters.
3456 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3457 return CheckTemplateTypeArgument(TTP, Arg, Converted);
3459 // Check non-type template parameters.
3460 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3461 // Do substitution on the type of the non-type template parameter
3462 // with the template arguments we've seen thus far. But if the
3463 // template has a dependent context then we cannot substitute yet.
3464 QualType NTTPType = NTTP->getType();
3465 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
3466 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
3468 if (NTTPType->isDependentType() &&
3469 !isa<TemplateTemplateParmDecl>(Template) &&
3470 !Template->getDeclContext()->isDependentContext()) {
3471 // Do substitution on the type of the non-type template parameter.
3472 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
3474 SourceRange(TemplateLoc, RAngleLoc));
3475 if (Inst.isInvalid())
3478 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3479 Converted.data(), Converted.size());
3480 NTTPType = SubstType(NTTPType,
3481 MultiLevelTemplateArgumentList(TemplateArgs),
3482 NTTP->getLocation(),
3483 NTTP->getDeclName());
3484 // If that worked, check the non-type template parameter type
3486 if (!NTTPType.isNull())
3487 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
3488 NTTP->getLocation());
3489 if (NTTPType.isNull())
3493 switch (Arg.getArgument().getKind()) {
3494 case TemplateArgument::Null:
3495 llvm_unreachable("Should never see a NULL template argument here");
3497 case TemplateArgument::Expression: {
3498 TemplateArgument Result;
3500 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
3502 if (Res.isInvalid())
3505 // If the resulting expression is new, then use it in place of the
3506 // old expression in the template argument.
3507 if (Res.get() != Arg.getArgument().getAsExpr()) {
3508 TemplateArgument TA(Res.get());
3509 Arg = TemplateArgumentLoc(TA, Res.get());
3512 Converted.push_back(Result);
3516 case TemplateArgument::Declaration:
3517 case TemplateArgument::Integral:
3518 case TemplateArgument::NullPtr:
3519 // We've already checked this template argument, so just copy
3520 // it to the list of converted arguments.
3521 Converted.push_back(Arg.getArgument());
3524 case TemplateArgument::Template:
3525 case TemplateArgument::TemplateExpansion:
3526 // We were given a template template argument. It may not be ill-formed;
3528 if (DependentTemplateName *DTN
3529 = Arg.getArgument().getAsTemplateOrTemplatePattern()
3530 .getAsDependentTemplateName()) {
3531 // We have a template argument such as \c T::template X, which we
3532 // parsed as a template template argument. However, since we now
3533 // know that we need a non-type template argument, convert this
3534 // template name into an expression.
3536 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
3537 Arg.getTemplateNameLoc());
3540 SS.Adopt(Arg.getTemplateQualifierLoc());
3541 // FIXME: the template-template arg was a DependentTemplateName,
3542 // so it was provided with a template keyword. However, its source
3543 // location is not stored in the template argument structure.
3544 SourceLocation TemplateKWLoc;
3545 ExprResult E = DependentScopeDeclRefExpr::Create(
3546 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
3549 // If we parsed the template argument as a pack expansion, create a
3550 // pack expansion expression.
3551 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
3552 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
3557 TemplateArgument Result;
3558 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
3562 Converted.push_back(Result);
3566 // We have a template argument that actually does refer to a class
3567 // template, alias template, or template template parameter, and
3568 // therefore cannot be a non-type template argument.
3569 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
3570 << Arg.getSourceRange();
3572 Diag(Param->getLocation(), diag::note_template_param_here);
3575 case TemplateArgument::Type: {
3576 // We have a non-type template parameter but the template
3577 // argument is a type.
3579 // C++ [temp.arg]p2:
3580 // In a template-argument, an ambiguity between a type-id and
3581 // an expression is resolved to a type-id, regardless of the
3582 // form of the corresponding template-parameter.
3584 // We warn specifically about this case, since it can be rather
3585 // confusing for users.
3586 QualType T = Arg.getArgument().getAsType();
3587 SourceRange SR = Arg.getSourceRange();
3588 if (T->isFunctionType())
3589 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
3591 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
3592 Diag(Param->getLocation(), diag::note_template_param_here);
3596 case TemplateArgument::Pack:
3597 llvm_unreachable("Caller must expand template argument packs");
3604 // Check template template parameters.
3605 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
3607 // Substitute into the template parameter list of the template
3608 // template parameter, since previously-supplied template arguments
3609 // may appear within the template template parameter.
3611 // Set up a template instantiation context.
3612 LocalInstantiationScope Scope(*this);
3613 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
3614 TempParm, Converted,
3615 SourceRange(TemplateLoc, RAngleLoc));
3616 if (Inst.isInvalid())
3619 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3620 Converted.data(), Converted.size());
3621 TempParm = cast_or_null<TemplateTemplateParmDecl>(
3622 SubstDecl(TempParm, CurContext,
3623 MultiLevelTemplateArgumentList(TemplateArgs)));
3628 switch (Arg.getArgument().getKind()) {
3629 case TemplateArgument::Null:
3630 llvm_unreachable("Should never see a NULL template argument here");
3632 case TemplateArgument::Template:
3633 case TemplateArgument::TemplateExpansion:
3634 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
3637 Converted.push_back(Arg.getArgument());
3640 case TemplateArgument::Expression:
3641 case TemplateArgument::Type:
3642 // We have a template template parameter but the template
3643 // argument does not refer to a template.
3644 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
3645 << getLangOpts().CPlusPlus11;
3648 case TemplateArgument::Declaration:
3649 llvm_unreachable("Declaration argument with template template parameter");
3650 case TemplateArgument::Integral:
3651 llvm_unreachable("Integral argument with template template parameter");
3652 case TemplateArgument::NullPtr:
3653 llvm_unreachable("Null pointer argument with template template parameter");
3655 case TemplateArgument::Pack:
3656 llvm_unreachable("Caller must expand template argument packs");
3662 /// \brief Diagnose an arity mismatch in the
3663 static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
3664 SourceLocation TemplateLoc,
3665 TemplateArgumentListInfo &TemplateArgs) {
3666 TemplateParameterList *Params = Template->getTemplateParameters();
3667 unsigned NumParams = Params->size();
3668 unsigned NumArgs = TemplateArgs.size();
3671 if (NumArgs > NumParams)
3672 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
3673 TemplateArgs.getRAngleLoc());
3674 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3675 << (NumArgs > NumParams)
3676 << (isa<ClassTemplateDecl>(Template)? 0 :
3677 isa<FunctionTemplateDecl>(Template)? 1 :
3678 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3679 << Template << Range;
3680 S.Diag(Template->getLocation(), diag::note_template_decl_here)
3681 << Params->getSourceRange();
3685 /// \brief Check whether the template parameter is a pack expansion, and if so,
3686 /// determine the number of parameters produced by that expansion. For instance:
3689 /// template<typename ...Ts> struct A {
3690 /// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
3694 /// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
3695 /// is not a pack expansion, so returns an empty Optional.
3696 static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
3697 if (NonTypeTemplateParmDecl *NTTP
3698 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3699 if (NTTP->isExpandedParameterPack())
3700 return NTTP->getNumExpansionTypes();
3703 if (TemplateTemplateParmDecl *TTP
3704 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3705 if (TTP->isExpandedParameterPack())
3706 return TTP->getNumExpansionTemplateParameters();
3712 /// Diagnose a missing template argument.
3713 template<typename TemplateParmDecl>
3714 static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
3716 const TemplateParmDecl *D,
3717 TemplateArgumentListInfo &Args) {
3718 // Dig out the most recent declaration of the template parameter; there may be
3719 // declarations of the template that are more recent than TD.
3720 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
3721 ->getTemplateParameters()
3722 ->getParam(D->getIndex()));
3724 // If there's a default argument that's not visible, diagnose that we're
3725 // missing a module import.
3726 llvm::SmallVector<Module*, 8> Modules;
3727 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
3728 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
3729 D->getDefaultArgumentLoc(), Modules,
3730 Sema::MissingImportKind::DefaultArgument,
3735 // FIXME: If there's a more recent default argument that *is* visible,
3736 // diagnose that it was declared too late.
3738 return diagnoseArityMismatch(S, TD, Loc, Args);
3741 /// \brief Check that the given template argument list is well-formed
3742 /// for specializing the given template.
3743 bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
3744 SourceLocation TemplateLoc,
3745 TemplateArgumentListInfo &TemplateArgs,
3746 bool PartialTemplateArgs,
3747 SmallVectorImpl<TemplateArgument> &Converted) {
3748 // Make a copy of the template arguments for processing. Only make the
3749 // changes at the end when successful in matching the arguments to the
3751 TemplateArgumentListInfo NewArgs = TemplateArgs;
3753 TemplateParameterList *Params = Template->getTemplateParameters();
3755 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
3757 // C++ [temp.arg]p1:
3758 // [...] The type and form of each template-argument specified in
3759 // a template-id shall match the type and form specified for the
3760 // corresponding parameter declared by the template in its
3761 // template-parameter-list.
3762 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
3763 SmallVector<TemplateArgument, 2> ArgumentPack;
3764 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
3765 LocalInstantiationScope InstScope(*this, true);
3766 for (TemplateParameterList::iterator Param = Params->begin(),
3767 ParamEnd = Params->end();
3768 Param != ParamEnd; /* increment in loop */) {
3769 // If we have an expanded parameter pack, make sure we don't have too
3771 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
3772 if (*Expansions == ArgumentPack.size()) {
3773 // We're done with this parameter pack. Pack up its arguments and add
3774 // them to the list.
3775 Converted.push_back(
3776 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
3777 ArgumentPack.clear();
3779 // This argument is assigned to the next parameter.
3782 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
3783 // Not enough arguments for this parameter pack.
3784 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3786 << (isa<ClassTemplateDecl>(Template)? 0 :
3787 isa<FunctionTemplateDecl>(Template)? 1 :
3788 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3790 Diag(Template->getLocation(), diag::note_template_decl_here)
3791 << Params->getSourceRange();
3796 if (ArgIdx < NumArgs) {
3797 // Check the template argument we were given.
3798 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
3799 TemplateLoc, RAngleLoc,
3800 ArgumentPack.size(), Converted))
3803 bool PackExpansionIntoNonPack =
3804 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
3805 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
3806 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
3807 // Core issue 1430: we have a pack expansion as an argument to an
3808 // alias template, and it's not part of a parameter pack. This
3809 // can't be canonicalized, so reject it now.
3810 Diag(NewArgs[ArgIdx].getLocation(),
3811 diag::err_alias_template_expansion_into_fixed_list)
3812 << NewArgs[ArgIdx].getSourceRange();
3813 Diag((*Param)->getLocation(), diag::note_template_param_here);
3817 // We're now done with this argument.
3820 if ((*Param)->isTemplateParameterPack()) {
3821 // The template parameter was a template parameter pack, so take the
3822 // deduced argument and place it on the argument pack. Note that we
3823 // stay on the same template parameter so that we can deduce more
3825 ArgumentPack.push_back(Converted.pop_back_val());
3827 // Move to the next template parameter.
3831 // If we just saw a pack expansion into a non-pack, then directly convert
3832 // the remaining arguments, because we don't know what parameters they'll
3834 if (PackExpansionIntoNonPack) {
3835 if (!ArgumentPack.empty()) {
3836 // If we were part way through filling in an expanded parameter pack,
3837 // fall back to just producing individual arguments.
3838 Converted.insert(Converted.end(),
3839 ArgumentPack.begin(), ArgumentPack.end());
3840 ArgumentPack.clear();
3843 while (ArgIdx < NumArgs) {
3844 Converted.push_back(NewArgs[ArgIdx].getArgument());
3854 // If we're checking a partial template argument list, we're done.
3855 if (PartialTemplateArgs) {
3856 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
3857 Converted.push_back(
3858 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
3863 // If we have a template parameter pack with no more corresponding
3864 // arguments, just break out now and we'll fill in the argument pack below.
3865 if ((*Param)->isTemplateParameterPack()) {
3866 assert(!getExpandedPackSize(*Param) &&
3867 "Should have dealt with this already");
3869 // A non-expanded parameter pack before the end of the parameter list
3870 // only occurs for an ill-formed template parameter list, unless we've
3871 // got a partial argument list for a function template, so just bail out.
3872 if (Param + 1 != ParamEnd)
3875 Converted.push_back(
3876 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
3877 ArgumentPack.clear();
3883 // Check whether we have a default argument.
3884 TemplateArgumentLoc Arg;
3886 // Retrieve the default template argument from the template
3887 // parameter. For each kind of template parameter, we substitute the
3888 // template arguments provided thus far and any "outer" template arguments
3889 // (when the template parameter was part of a nested template) into
3890 // the default argument.
3891 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
3892 if (!hasVisibleDefaultArgument(TTP))
3893 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
3896 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
3905 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
3907 } else if (NonTypeTemplateParmDecl *NTTP
3908 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
3909 if (!hasVisibleDefaultArgument(NTTP))
3910 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
3913 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
3921 Expr *Ex = E.getAs<Expr>();
3922 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
3924 TemplateTemplateParmDecl *TempParm
3925 = cast<TemplateTemplateParmDecl>(*Param);
3927 if (!hasVisibleDefaultArgument(TempParm))
3928 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
3931 NestedNameSpecifierLoc QualifierLoc;
3932 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
3941 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
3942 TempParm->getDefaultArgument().getTemplateNameLoc());
3945 // Introduce an instantiation record that describes where we are using
3946 // the default template argument.
3947 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
3948 SourceRange(TemplateLoc, RAngleLoc));
3949 if (Inst.isInvalid())
3952 // Check the default template argument.
3953 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
3954 RAngleLoc, 0, Converted))
3957 // Core issue 150 (assumed resolution): if this is a template template
3958 // parameter, keep track of the default template arguments from the
3959 // template definition.
3960 if (isTemplateTemplateParameter)
3961 NewArgs.addArgument(Arg);
3963 // Move to the next template parameter and argument.
3968 // If we're performing a partial argument substitution, allow any trailing
3969 // pack expansions; they might be empty. This can happen even if
3970 // PartialTemplateArgs is false (the list of arguments is complete but
3971 // still dependent).
3972 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
3973 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
3974 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
3975 Converted.push_back(NewArgs[ArgIdx++].getArgument());
3978 // If we have any leftover arguments, then there were too many arguments.
3979 // Complain and fail.
3980 if (ArgIdx < NumArgs)
3981 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
3983 // No problems found with the new argument list, propagate changes back
3985 TemplateArgs = std::move(NewArgs);
3991 class UnnamedLocalNoLinkageFinder
3992 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
3997 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
4000 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
4002 bool Visit(QualType T) {
4003 return inherited::Visit(T.getTypePtr());
4006 #define TYPE(Class, Parent) \
4007 bool Visit##Class##Type(const Class##Type *);
4008 #define ABSTRACT_TYPE(Class, Parent) \
4009 bool Visit##Class##Type(const Class##Type *) { return false; }
4010 #define NON_CANONICAL_TYPE(Class, Parent) \
4011 bool Visit##Class##Type(const Class##Type *) { return false; }
4012 #include "clang/AST/TypeNodes.def"
4014 bool VisitTagDecl(const TagDecl *Tag);
4015 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
4017 } // end anonymous namespace
4019 bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
4023 bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
4024 return Visit(T->getElementType());
4027 bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
4028 return Visit(T->getPointeeType());
4031 bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
4032 const BlockPointerType* T) {
4033 return Visit(T->getPointeeType());
4036 bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
4037 const LValueReferenceType* T) {
4038 return Visit(T->getPointeeType());
4041 bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
4042 const RValueReferenceType* T) {
4043 return Visit(T->getPointeeType());
4046 bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
4047 const MemberPointerType* T) {
4048 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
4051 bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
4052 const ConstantArrayType* T) {
4053 return Visit(T->getElementType());
4056 bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
4057 const IncompleteArrayType* T) {
4058 return Visit(T->getElementType());
4061 bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
4062 const VariableArrayType* T) {
4063 return Visit(T->getElementType());
4066 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
4067 const DependentSizedArrayType* T) {
4068 return Visit(T->getElementType());
4071 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
4072 const DependentSizedExtVectorType* T) {
4073 return Visit(T->getElementType());
4076 bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
4077 return Visit(T->getElementType());
4080 bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
4081 return Visit(T->getElementType());
4084 bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
4085 const FunctionProtoType* T) {
4086 for (const auto &A : T->param_types()) {
4091 return Visit(T->getReturnType());
4094 bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
4095 const FunctionNoProtoType* T) {
4096 return Visit(T->getReturnType());
4099 bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
4100 const UnresolvedUsingType*) {
4104 bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
4108 bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
4109 return Visit(T->getUnderlyingType());
4112 bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
4116 bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
4117 const UnaryTransformType*) {
4121 bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
4122 return Visit(T->getDeducedType());
4125 bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
4126 return VisitTagDecl(T->getDecl());
4129 bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
4130 return VisitTagDecl(T->getDecl());
4133 bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
4134 const TemplateTypeParmType*) {
4138 bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
4139 const SubstTemplateTypeParmPackType *) {
4143 bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
4144 const TemplateSpecializationType*) {
4148 bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
4149 const InjectedClassNameType* T) {
4150 return VisitTagDecl(T->getDecl());
4153 bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
4154 const DependentNameType* T) {
4155 return VisitNestedNameSpecifier(T->getQualifier());
4158 bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
4159 const DependentTemplateSpecializationType* T) {
4160 return VisitNestedNameSpecifier(T->getQualifier());
4163 bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
4164 const PackExpansionType* T) {
4165 return Visit(T->getPattern());
4168 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
4172 bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
4173 const ObjCInterfaceType *) {
4177 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
4178 const ObjCObjectPointerType *) {
4182 bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
4183 return Visit(T->getValueType());
4186 bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
4190 bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
4191 if (Tag->getDeclContext()->isFunctionOrMethod()) {
4192 S.Diag(SR.getBegin(),
4193 S.getLangOpts().CPlusPlus11 ?
4194 diag::warn_cxx98_compat_template_arg_local_type :
4195 diag::ext_template_arg_local_type)
4196 << S.Context.getTypeDeclType(Tag) << SR;
4200 if (!Tag->hasNameForLinkage()) {
4201 S.Diag(SR.getBegin(),
4202 S.getLangOpts().CPlusPlus11 ?
4203 diag::warn_cxx98_compat_template_arg_unnamed_type :
4204 diag::ext_template_arg_unnamed_type) << SR;
4205 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
4212 bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
4213 NestedNameSpecifier *NNS) {
4214 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
4217 switch (NNS->getKind()) {
4218 case NestedNameSpecifier::Identifier:
4219 case NestedNameSpecifier::Namespace:
4220 case NestedNameSpecifier::NamespaceAlias:
4221 case NestedNameSpecifier::Global:
4222 case NestedNameSpecifier::Super:
4225 case NestedNameSpecifier::TypeSpec:
4226 case NestedNameSpecifier::TypeSpecWithTemplate:
4227 return Visit(QualType(NNS->getAsType(), 0));
4229 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
4232 /// \brief Check a template argument against its corresponding
4233 /// template type parameter.
4235 /// This routine implements the semantics of C++ [temp.arg.type]. It
4236 /// returns true if an error occurred, and false otherwise.
4237 bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
4238 TypeSourceInfo *ArgInfo) {
4239 assert(ArgInfo && "invalid TypeSourceInfo");
4240 QualType Arg = ArgInfo->getType();
4241 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
4243 if (Arg->isVariablyModifiedType()) {
4244 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
4245 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
4246 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
4249 // C++03 [temp.arg.type]p2:
4250 // A local type, a type with no linkage, an unnamed type or a type
4251 // compounded from any of these types shall not be used as a
4252 // template-argument for a template type-parameter.
4254 // C++11 allows these, and even in C++03 we allow them as an extension with
4257 if (LangOpts.CPlusPlus11)
4259 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_unnamed_type,
4261 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_local_type,
4264 NeedsCheck = Arg->hasUnnamedOrLocalType();
4267 UnnamedLocalNoLinkageFinder Finder(*this, SR);
4268 (void)Finder.Visit(Context.getCanonicalType(Arg));
4274 enum NullPointerValueKind {
4280 /// \brief Determine whether the given template argument is a null pointer
4281 /// value of the appropriate type.
4282 static NullPointerValueKind
4283 isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
4284 QualType ParamType, Expr *Arg) {
4285 if (Arg->isValueDependent() || Arg->isTypeDependent())
4286 return NPV_NotNullPointer;
4288 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
4290 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
4292 if (!S.getLangOpts().CPlusPlus11)
4293 return NPV_NotNullPointer;
4295 // Determine whether we have a constant expression.
4296 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
4297 if (ArgRV.isInvalid())
4301 Expr::EvalResult EvalResult;
4302 SmallVector<PartialDiagnosticAt, 8> Notes;
4303 EvalResult.Diag = &Notes;
4304 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
4305 EvalResult.HasSideEffects) {
4306 SourceLocation DiagLoc = Arg->getExprLoc();
4308 // If our only note is the usual "invalid subexpression" note, just point
4309 // the caret at its location rather than producing an essentially
4311 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
4312 diag::note_invalid_subexpr_in_const_expr) {
4313 DiagLoc = Notes[0].first;
4317 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
4318 << Arg->getType() << Arg->getSourceRange();
4319 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
4320 S.Diag(Notes[I].first, Notes[I].second);
4322 S.Diag(Param->getLocation(), diag::note_template_param_here);
4326 // C++11 [temp.arg.nontype]p1:
4327 // - an address constant expression of type std::nullptr_t
4328 if (Arg->getType()->isNullPtrType())
4329 return NPV_NullPointer;
4331 // - a constant expression that evaluates to a null pointer value (4.10); or
4332 // - a constant expression that evaluates to a null member pointer value
4334 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
4335 (EvalResult.Val.isMemberPointer() &&
4336 !EvalResult.Val.getMemberPointerDecl())) {
4337 // If our expression has an appropriate type, we've succeeded.
4338 bool ObjCLifetimeConversion;
4339 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
4340 S.IsQualificationConversion(Arg->getType(), ParamType, false,
4341 ObjCLifetimeConversion))
4342 return NPV_NullPointer;
4344 // The types didn't match, but we know we got a null pointer; complain,
4345 // then recover as if the types were correct.
4346 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
4347 << Arg->getType() << ParamType << Arg->getSourceRange();
4348 S.Diag(Param->getLocation(), diag::note_template_param_here);
4349 return NPV_NullPointer;
4352 // If we don't have a null pointer value, but we do have a NULL pointer
4353 // constant, suggest a cast to the appropriate type.
4354 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
4355 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
4356 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
4357 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
4358 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
4360 S.Diag(Param->getLocation(), diag::note_template_param_here);
4361 return NPV_NullPointer;
4364 // FIXME: If we ever want to support general, address-constant expressions
4365 // as non-type template arguments, we should return the ExprResult here to
4366 // be interpreted by the caller.
4367 return NPV_NotNullPointer;
4370 /// \brief Checks whether the given template argument is compatible with its
4371 /// template parameter.
4372 static bool CheckTemplateArgumentIsCompatibleWithParameter(
4373 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
4374 Expr *Arg, QualType ArgType) {
4375 bool ObjCLifetimeConversion;
4376 if (ParamType->isPointerType() &&
4377 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
4378 S.IsQualificationConversion(ArgType, ParamType, false,
4379 ObjCLifetimeConversion)) {
4380 // For pointer-to-object types, qualification conversions are
4383 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
4384 if (!ParamRef->getPointeeType()->isFunctionType()) {
4385 // C++ [temp.arg.nontype]p5b3:
4386 // For a non-type template-parameter of type reference to
4387 // object, no conversions apply. The type referred to by the
4388 // reference may be more cv-qualified than the (otherwise
4389 // identical) type of the template- argument. The
4390 // template-parameter is bound directly to the
4391 // template-argument, which shall be an lvalue.
4393 // FIXME: Other qualifiers?
4394 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
4395 unsigned ArgQuals = ArgType.getCVRQualifiers();
4397 if ((ParamQuals | ArgQuals) != ParamQuals) {
4398 S.Diag(Arg->getLocStart(),
4399 diag::err_template_arg_ref_bind_ignores_quals)
4400 << ParamType << Arg->getType() << Arg->getSourceRange();
4401 S.Diag(Param->getLocation(), diag::note_template_param_here);
4407 // At this point, the template argument refers to an object or
4408 // function with external linkage. We now need to check whether the
4409 // argument and parameter types are compatible.
4410 if (!S.Context.hasSameUnqualifiedType(ArgType,
4411 ParamType.getNonReferenceType())) {
4412 // We can't perform this conversion or binding.
4413 if (ParamType->isReferenceType())
4414 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
4415 << ParamType << ArgIn->getType() << Arg->getSourceRange();
4417 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4418 << ArgIn->getType() << ParamType << Arg->getSourceRange();
4419 S.Diag(Param->getLocation(), diag::note_template_param_here);
4427 /// \brief Checks whether the given template argument is the address
4428 /// of an object or function according to C++ [temp.arg.nontype]p1.
4430 CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
4431 NonTypeTemplateParmDecl *Param,
4434 TemplateArgument &Converted) {
4435 bool Invalid = false;
4437 QualType ArgType = Arg->getType();
4439 bool AddressTaken = false;
4440 SourceLocation AddrOpLoc;
4441 if (S.getLangOpts().MicrosoftExt) {
4442 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
4443 // dereference and address-of operators.
4444 Arg = Arg->IgnoreParenCasts();
4446 bool ExtWarnMSTemplateArg = false;
4447 UnaryOperatorKind FirstOpKind;
4448 SourceLocation FirstOpLoc;
4449 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4450 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
4451 if (UnOpKind == UO_Deref)
4452 ExtWarnMSTemplateArg = true;
4453 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
4454 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
4455 if (!AddrOpLoc.isValid()) {
4456 FirstOpKind = UnOpKind;
4457 FirstOpLoc = UnOp->getOperatorLoc();
4462 if (FirstOpLoc.isValid()) {
4463 if (ExtWarnMSTemplateArg)
4464 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
4465 << ArgIn->getSourceRange();
4467 if (FirstOpKind == UO_AddrOf)
4468 AddressTaken = true;
4469 else if (Arg->getType()->isPointerType()) {
4470 // We cannot let pointers get dereferenced here, that is obviously not a
4471 // constant expression.
4472 assert(FirstOpKind == UO_Deref);
4473 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4474 << Arg->getSourceRange();
4478 // See through any implicit casts we added to fix the type.
4479 Arg = Arg->IgnoreImpCasts();
4481 // C++ [temp.arg.nontype]p1:
4483 // A template-argument for a non-type, non-template
4484 // template-parameter shall be one of: [...]
4486 // -- the address of an object or function with external
4487 // linkage, including function templates and function
4488 // template-ids but excluding non-static class members,
4489 // expressed as & id-expression where the & is optional if
4490 // the name refers to a function or array, or if the
4491 // corresponding template-parameter is a reference; or
4493 // In C++98/03 mode, give an extension warning on any extra parentheses.
4494 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4495 bool ExtraParens = false;
4496 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4497 if (!Invalid && !ExtraParens) {
4498 S.Diag(Arg->getLocStart(),
4499 S.getLangOpts().CPlusPlus11
4500 ? diag::warn_cxx98_compat_template_arg_extra_parens
4501 : diag::ext_template_arg_extra_parens)
4502 << Arg->getSourceRange();
4506 Arg = Parens->getSubExpr();
4509 while (SubstNonTypeTemplateParmExpr *subst =
4510 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4511 Arg = subst->getReplacement()->IgnoreImpCasts();
4513 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4514 if (UnOp->getOpcode() == UO_AddrOf) {
4515 Arg = UnOp->getSubExpr();
4516 AddressTaken = true;
4517 AddrOpLoc = UnOp->getOperatorLoc();
4521 while (SubstNonTypeTemplateParmExpr *subst =
4522 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4523 Arg = subst->getReplacement()->IgnoreImpCasts();
4526 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
4527 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
4529 // If our parameter has pointer type, check for a null template value.
4530 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
4531 NullPointerValueKind NPV;
4532 // dllimport'd entities aren't constant but are available inside of template
4534 if (Entity && Entity->hasAttr<DLLImportAttr>())
4535 NPV = NPV_NotNullPointer;
4537 NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
4539 case NPV_NullPointer:
4540 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
4541 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4542 /*isNullPtr=*/true);
4548 case NPV_NotNullPointer:
4553 // Stop checking the precise nature of the argument if it is value dependent,
4554 // it should be checked when instantiated.
4555 if (Arg->isValueDependent()) {
4556 Converted = TemplateArgument(ArgIn);
4560 if (isa<CXXUuidofExpr>(Arg)) {
4561 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
4562 ArgIn, Arg, ArgType))
4565 Converted = TemplateArgument(ArgIn);
4570 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4571 << Arg->getSourceRange();
4572 S.Diag(Param->getLocation(), diag::note_template_param_here);
4576 // Cannot refer to non-static data members
4577 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
4578 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
4579 << Entity << Arg->getSourceRange();
4580 S.Diag(Param->getLocation(), diag::note_template_param_here);
4584 // Cannot refer to non-static member functions
4585 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
4586 if (!Method->isStatic()) {
4587 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
4588 << Method << Arg->getSourceRange();
4589 S.Diag(Param->getLocation(), diag::note_template_param_here);
4594 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
4595 VarDecl *Var = dyn_cast<VarDecl>(Entity);
4597 // A non-type template argument must refer to an object or function.
4598 if (!Func && !Var) {
4599 // We found something, but we don't know specifically what it is.
4600 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
4601 << Arg->getSourceRange();
4602 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4606 // Address / reference template args must have external linkage in C++98.
4607 if (Entity->getFormalLinkage() == InternalLinkage) {
4608 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
4609 diag::warn_cxx98_compat_template_arg_object_internal :
4610 diag::ext_template_arg_object_internal)
4611 << !Func << Entity << Arg->getSourceRange();
4612 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4614 } else if (!Entity->hasLinkage()) {
4615 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
4616 << !Func << Entity << Arg->getSourceRange();
4617 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4623 // If the template parameter has pointer type, the function decays.
4624 if (ParamType->isPointerType() && !AddressTaken)
4625 ArgType = S.Context.getPointerType(Func->getType());
4626 else if (AddressTaken && ParamType->isReferenceType()) {
4627 // If we originally had an address-of operator, but the
4628 // parameter has reference type, complain and (if things look
4629 // like they will work) drop the address-of operator.
4630 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
4631 ParamType.getNonReferenceType())) {
4632 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4634 S.Diag(Param->getLocation(), diag::note_template_param_here);
4638 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4640 << FixItHint::CreateRemoval(AddrOpLoc);
4641 S.Diag(Param->getLocation(), diag::note_template_param_here);
4643 ArgType = Func->getType();
4646 // A value of reference type is not an object.
4647 if (Var->getType()->isReferenceType()) {
4648 S.Diag(Arg->getLocStart(),
4649 diag::err_template_arg_reference_var)
4650 << Var->getType() << Arg->getSourceRange();
4651 S.Diag(Param->getLocation(), diag::note_template_param_here);
4655 // A template argument must have static storage duration.
4656 if (Var->getTLSKind()) {
4657 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
4658 << Arg->getSourceRange();
4659 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
4663 // If the template parameter has pointer type, we must have taken
4664 // the address of this object.
4665 if (ParamType->isReferenceType()) {
4667 // If we originally had an address-of operator, but the
4668 // parameter has reference type, complain and (if things look
4669 // like they will work) drop the address-of operator.
4670 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
4671 ParamType.getNonReferenceType())) {
4672 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4674 S.Diag(Param->getLocation(), diag::note_template_param_here);
4678 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4680 << FixItHint::CreateRemoval(AddrOpLoc);
4681 S.Diag(Param->getLocation(), diag::note_template_param_here);
4683 ArgType = Var->getType();
4685 } else if (!AddressTaken && ParamType->isPointerType()) {
4686 if (Var->getType()->isArrayType()) {
4687 // Array-to-pointer decay.
4688 ArgType = S.Context.getArrayDecayedType(Var->getType());
4690 // If the template parameter has pointer type but the address of
4691 // this object was not taken, complain and (possibly) recover by
4692 // taking the address of the entity.
4693 ArgType = S.Context.getPointerType(Var->getType());
4694 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
4695 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4697 S.Diag(Param->getLocation(), diag::note_template_param_here);
4701 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4703 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
4705 S.Diag(Param->getLocation(), diag::note_template_param_here);
4710 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
4714 // Create the template argument.
4716 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
4717 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
4721 /// \brief Checks whether the given template argument is a pointer to
4722 /// member constant according to C++ [temp.arg.nontype]p1.
4723 static bool CheckTemplateArgumentPointerToMember(Sema &S,
4724 NonTypeTemplateParmDecl *Param,
4727 TemplateArgument &Converted) {
4728 bool Invalid = false;
4730 // Check for a null pointer value.
4731 Expr *Arg = ResultArg;
4732 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
4735 case NPV_NullPointer:
4736 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
4737 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4740 case NPV_NotNullPointer:
4744 bool ObjCLifetimeConversion;
4745 if (S.IsQualificationConversion(Arg->getType(),
4746 ParamType.getNonReferenceType(),
4747 false, ObjCLifetimeConversion)) {
4748 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
4749 Arg->getValueKind()).get();
4751 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
4752 ParamType.getNonReferenceType())) {
4753 // We can't perform this conversion.
4754 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4755 << Arg->getType() << ParamType << Arg->getSourceRange();
4756 S.Diag(Param->getLocation(), diag::note_template_param_here);
4760 // See through any implicit casts we added to fix the type.
4761 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
4762 Arg = Cast->getSubExpr();
4764 // C++ [temp.arg.nontype]p1:
4766 // A template-argument for a non-type, non-template
4767 // template-parameter shall be one of: [...]
4769 // -- a pointer to member expressed as described in 5.3.1.
4770 DeclRefExpr *DRE = nullptr;
4772 // In C++98/03 mode, give an extension warning on any extra parentheses.
4773 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4774 bool ExtraParens = false;
4775 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4776 if (!Invalid && !ExtraParens) {
4777 S.Diag(Arg->getLocStart(),
4778 S.getLangOpts().CPlusPlus11 ?
4779 diag::warn_cxx98_compat_template_arg_extra_parens :
4780 diag::ext_template_arg_extra_parens)
4781 << Arg->getSourceRange();
4785 Arg = Parens->getSubExpr();
4788 while (SubstNonTypeTemplateParmExpr *subst =
4789 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4790 Arg = subst->getReplacement()->IgnoreImpCasts();
4792 // A pointer-to-member constant written &Class::member.
4793 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4794 if (UnOp->getOpcode() == UO_AddrOf) {
4795 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
4796 if (DRE && !DRE->getQualifier())
4800 // A constant of pointer-to-member type.
4801 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
4802 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
4803 if (VD->getType()->isMemberPointerType()) {
4804 if (isa<NonTypeTemplateParmDecl>(VD)) {
4805 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
4806 Converted = TemplateArgument(Arg);
4808 VD = cast<ValueDecl>(VD->getCanonicalDecl());
4809 Converted = TemplateArgument(VD, ParamType);
4820 return S.Diag(Arg->getLocStart(),
4821 diag::err_template_arg_not_pointer_to_member_form)
4822 << Arg->getSourceRange();
4824 if (isa<FieldDecl>(DRE->getDecl()) ||
4825 isa<IndirectFieldDecl>(DRE->getDecl()) ||
4826 isa<CXXMethodDecl>(DRE->getDecl())) {
4827 assert((isa<FieldDecl>(DRE->getDecl()) ||
4828 isa<IndirectFieldDecl>(DRE->getDecl()) ||
4829 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
4830 "Only non-static member pointers can make it here");
4832 // Okay: this is the address of a non-static member, and therefore
4833 // a member pointer constant.
4834 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
4835 Converted = TemplateArgument(Arg);
4837 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
4838 Converted = TemplateArgument(D, ParamType);
4843 // We found something else, but we don't know specifically what it is.
4844 S.Diag(Arg->getLocStart(),
4845 diag::err_template_arg_not_pointer_to_member_form)
4846 << Arg->getSourceRange();
4847 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4851 /// \brief Check a template argument against its corresponding
4852 /// non-type template parameter.
4854 /// This routine implements the semantics of C++ [temp.arg.nontype].
4855 /// If an error occurred, it returns ExprError(); otherwise, it
4856 /// returns the converted template argument. \p ParamType is the
4857 /// type of the non-type template parameter after it has been instantiated.
4858 ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
4859 QualType ParamType, Expr *Arg,
4860 TemplateArgument &Converted,
4861 CheckTemplateArgumentKind CTAK) {
4862 SourceLocation StartLoc = Arg->getLocStart();
4864 // If either the parameter has a dependent type or the argument is
4865 // type-dependent, there's nothing we can check now.
4866 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
4867 // FIXME: Produce a cloned, canonical expression?
4868 Converted = TemplateArgument(Arg);
4872 // We should have already dropped all cv-qualifiers by now.
4873 assert(!ParamType.hasQualifiers() &&
4874 "non-type template parameter type cannot be qualified");
4876 if (CTAK == CTAK_Deduced &&
4877 !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) {
4878 // C++ [temp.deduct.type]p17:
4879 // If, in the declaration of a function template with a non-type
4880 // template-parameter, the non-type template-parameter is used
4881 // in an expression in the function parameter-list and, if the
4882 // corresponding template-argument is deduced, the
4883 // template-argument type shall match the type of the
4884 // template-parameter exactly, except that a template-argument
4885 // deduced from an array bound may be of any integral type.
4886 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
4887 << Arg->getType().getUnqualifiedType()
4888 << ParamType.getUnqualifiedType();
4889 Diag(Param->getLocation(), diag::note_template_param_here);
4893 if (getLangOpts().CPlusPlus1z) {
4894 // FIXME: We can do some limited checking for a value-dependent but not
4895 // type-dependent argument.
4896 if (Arg->isValueDependent()) {
4897 Converted = TemplateArgument(Arg);
4901 // C++1z [temp.arg.nontype]p1:
4902 // A template-argument for a non-type template parameter shall be
4903 // a converted constant expression of the type of the template-parameter.
4905 ExprResult ArgResult = CheckConvertedConstantExpression(
4906 Arg, ParamType, Value, CCEK_TemplateArg);
4907 if (ArgResult.isInvalid())
4910 QualType CanonParamType = Context.getCanonicalType(ParamType);
4912 // Convert the APValue to a TemplateArgument.
4913 switch (Value.getKind()) {
4914 case APValue::Uninitialized:
4915 assert(ParamType->isNullPtrType());
4916 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
4919 assert(ParamType->isIntegralOrEnumerationType());
4920 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
4922 case APValue::MemberPointer: {
4923 assert(ParamType->isMemberPointerType());
4925 // FIXME: We need TemplateArgument representation and mangling for these.
4926 if (!Value.getMemberPointerPath().empty()) {
4927 Diag(Arg->getLocStart(),
4928 diag::err_template_arg_member_ptr_base_derived_not_supported)
4929 << Value.getMemberPointerDecl() << ParamType
4930 << Arg->getSourceRange();
4934 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
4935 Converted = VD ? TemplateArgument(VD, CanonParamType)
4936 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
4939 case APValue::LValue: {
4940 // For a non-type template-parameter of pointer or reference type,
4941 // the value of the constant expression shall not refer to
4942 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
4943 ParamType->isNullPtrType());
4944 // -- a temporary object
4945 // -- a string literal
4946 // -- the result of a typeid expression, or
4947 // -- a predefind __func__ variable
4948 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
4949 if (isa<CXXUuidofExpr>(E)) {
4950 Converted = TemplateArgument(const_cast<Expr*>(E));
4953 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4954 << Arg->getSourceRange();
4957 auto *VD = const_cast<ValueDecl *>(
4958 Value.getLValueBase().dyn_cast<const ValueDecl *>());
4960 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
4961 VD && VD->getType()->isArrayType() &&
4962 Value.getLValuePath()[0].ArrayIndex == 0 &&
4963 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
4964 // Per defect report (no number yet):
4965 // ... other than a pointer to the first element of a complete array
4967 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
4968 Value.isLValueOnePastTheEnd()) {
4969 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
4970 << Value.getAsString(Context, ParamType);
4973 assert((VD || !ParamType->isReferenceType()) &&
4974 "null reference should not be a constant expression");
4975 assert((!VD || !ParamType->isNullPtrType()) &&
4976 "non-null value of type nullptr_t?");
4977 Converted = VD ? TemplateArgument(VD, CanonParamType)
4978 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
4981 case APValue::AddrLabelDiff:
4982 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
4983 case APValue::Float:
4984 case APValue::ComplexInt:
4985 case APValue::ComplexFloat:
4986 case APValue::Vector:
4987 case APValue::Array:
4988 case APValue::Struct:
4989 case APValue::Union:
4990 llvm_unreachable("invalid kind for template argument");
4993 return ArgResult.get();
4996 // C++ [temp.arg.nontype]p5:
4997 // The following conversions are performed on each expression used
4998 // as a non-type template-argument. If a non-type
4999 // template-argument cannot be converted to the type of the
5000 // corresponding template-parameter then the program is
5002 if (ParamType->isIntegralOrEnumerationType()) {
5004 // -- for a non-type template-parameter of integral or
5005 // enumeration type, conversions permitted in a converted
5006 // constant expression are applied.
5009 // -- for a non-type template-parameter of integral or
5010 // enumeration type, integral promotions (4.5) and integral
5011 // conversions (4.7) are applied.
5013 if (getLangOpts().CPlusPlus11) {
5014 // We can't check arbitrary value-dependent arguments.
5015 // FIXME: If there's no viable conversion to the template parameter type,
5016 // we should be able to diagnose that prior to instantiation.
5017 if (Arg->isValueDependent()) {
5018 Converted = TemplateArgument(Arg);
5022 // C++ [temp.arg.nontype]p1:
5023 // A template-argument for a non-type, non-template template-parameter
5026 // -- for a non-type template-parameter of integral or enumeration
5027 // type, a converted constant expression of the type of the
5028 // template-parameter; or
5030 ExprResult ArgResult =
5031 CheckConvertedConstantExpression(Arg, ParamType, Value,
5033 if (ArgResult.isInvalid())
5036 // Widen the argument value to sizeof(parameter type). This is almost
5037 // always a no-op, except when the parameter type is bool. In
5038 // that case, this may extend the argument from 1 bit to 8 bits.
5039 QualType IntegerType = ParamType;
5040 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
5041 IntegerType = Enum->getDecl()->getIntegerType();
5042 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
5044 Converted = TemplateArgument(Context, Value,
5045 Context.getCanonicalType(ParamType));
5049 ExprResult ArgResult = DefaultLvalueConversion(Arg);
5050 if (ArgResult.isInvalid())
5052 Arg = ArgResult.get();
5054 QualType ArgType = Arg->getType();
5056 // C++ [temp.arg.nontype]p1:
5057 // A template-argument for a non-type, non-template
5058 // template-parameter shall be one of:
5060 // -- an integral constant-expression of integral or enumeration
5062 // -- the name of a non-type template-parameter; or
5063 SourceLocation NonConstantLoc;
5065 if (!ArgType->isIntegralOrEnumerationType()) {
5066 Diag(Arg->getLocStart(),
5067 diag::err_template_arg_not_integral_or_enumeral)
5068 << ArgType << Arg->getSourceRange();
5069 Diag(Param->getLocation(), diag::note_template_param_here);
5071 } else if (!Arg->isValueDependent()) {
5072 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
5076 TmplArgICEDiagnoser(QualType T) : T(T) { }
5078 void diagnoseNotICE(Sema &S, SourceLocation Loc,
5079 SourceRange SR) override {
5080 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
5082 } Diagnoser(ArgType);
5084 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
5090 // From here on out, all we care about is the unqualified form
5091 // of the argument type.
5092 ArgType = ArgType.getUnqualifiedType();
5094 // Try to convert the argument to the parameter's type.
5095 if (Context.hasSameType(ParamType, ArgType)) {
5096 // Okay: no conversion necessary
5097 } else if (ParamType->isBooleanType()) {
5098 // This is an integral-to-boolean conversion.
5099 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
5100 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
5101 !ParamType->isEnumeralType()) {
5102 // This is an integral promotion or conversion.
5103 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
5105 // We can't perform this conversion.
5106 Diag(Arg->getLocStart(),
5107 diag::err_template_arg_not_convertible)
5108 << Arg->getType() << ParamType << Arg->getSourceRange();
5109 Diag(Param->getLocation(), diag::note_template_param_here);
5113 // Add the value of this argument to the list of converted
5114 // arguments. We use the bitwidth and signedness of the template
5116 if (Arg->isValueDependent()) {
5117 // The argument is value-dependent. Create a new
5118 // TemplateArgument with the converted expression.
5119 Converted = TemplateArgument(Arg);
5123 QualType IntegerType = Context.getCanonicalType(ParamType);
5124 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
5125 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
5127 if (ParamType->isBooleanType()) {
5128 // Value must be zero or one.
5130 unsigned AllowedBits = Context.getTypeSize(IntegerType);
5131 if (Value.getBitWidth() != AllowedBits)
5132 Value = Value.extOrTrunc(AllowedBits);
5133 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
5135 llvm::APSInt OldValue = Value;
5137 // Coerce the template argument's value to the value it will have
5138 // based on the template parameter's type.
5139 unsigned AllowedBits = Context.getTypeSize(IntegerType);
5140 if (Value.getBitWidth() != AllowedBits)
5141 Value = Value.extOrTrunc(AllowedBits);
5142 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
5144 // Complain if an unsigned parameter received a negative value.
5145 if (IntegerType->isUnsignedIntegerOrEnumerationType()
5146 && (OldValue.isSigned() && OldValue.isNegative())) {
5147 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
5148 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5149 << Arg->getSourceRange();
5150 Diag(Param->getLocation(), diag::note_template_param_here);
5153 // Complain if we overflowed the template parameter's type.
5154 unsigned RequiredBits;
5155 if (IntegerType->isUnsignedIntegerOrEnumerationType())
5156 RequiredBits = OldValue.getActiveBits();
5157 else if (OldValue.isUnsigned())
5158 RequiredBits = OldValue.getActiveBits() + 1;
5160 RequiredBits = OldValue.getMinSignedBits();
5161 if (RequiredBits > AllowedBits) {
5162 Diag(Arg->getLocStart(),
5163 diag::warn_template_arg_too_large)
5164 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5165 << Arg->getSourceRange();
5166 Diag(Param->getLocation(), diag::note_template_param_here);
5170 Converted = TemplateArgument(Context, Value,
5171 ParamType->isEnumeralType()
5172 ? Context.getCanonicalType(ParamType)
5177 QualType ArgType = Arg->getType();
5178 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
5180 // Handle pointer-to-function, reference-to-function, and
5181 // pointer-to-member-function all in (roughly) the same way.
5182 if (// -- For a non-type template-parameter of type pointer to
5183 // function, only the function-to-pointer conversion (4.3) is
5184 // applied. If the template-argument represents a set of
5185 // overloaded functions (or a pointer to such), the matching
5186 // function is selected from the set (13.4).
5187 (ParamType->isPointerType() &&
5188 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
5189 // -- For a non-type template-parameter of type reference to
5190 // function, no conversions apply. If the template-argument
5191 // represents a set of overloaded functions, the matching
5192 // function is selected from the set (13.4).
5193 (ParamType->isReferenceType() &&
5194 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
5195 // -- For a non-type template-parameter of type pointer to
5196 // member function, no conversions apply. If the
5197 // template-argument represents a set of overloaded member
5198 // functions, the matching member function is selected from
5200 (ParamType->isMemberPointerType() &&
5201 ParamType->getAs<MemberPointerType>()->getPointeeType()
5202 ->isFunctionType())) {
5204 if (Arg->getType() == Context.OverloadTy) {
5205 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
5208 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
5211 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5212 ArgType = Arg->getType();
5217 if (!ParamType->isMemberPointerType()) {
5218 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5225 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5231 if (ParamType->isPointerType()) {
5232 // -- for a non-type template-parameter of type pointer to
5233 // object, qualification conversions (4.4) and the
5234 // array-to-pointer conversion (4.2) are applied.
5235 // C++0x also allows a value of std::nullptr_t.
5236 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
5237 "Only object pointers allowed here");
5239 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5246 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
5247 // -- For a non-type template-parameter of type reference to
5248 // object, no conversions apply. The type referred to by the
5249 // reference may be more cv-qualified than the (otherwise
5250 // identical) type of the template-argument. The
5251 // template-parameter is bound directly to the
5252 // template-argument, which must be an lvalue.
5253 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
5254 "Only object references allowed here");
5256 if (Arg->getType() == Context.OverloadTy) {
5257 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
5258 ParamRefType->getPointeeType(),
5261 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
5264 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5265 ArgType = Arg->getType();
5270 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5277 // Deal with parameters of type std::nullptr_t.
5278 if (ParamType->isNullPtrType()) {
5279 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5280 Converted = TemplateArgument(Arg);
5284 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
5285 case NPV_NotNullPointer:
5286 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
5287 << Arg->getType() << ParamType;
5288 Diag(Param->getLocation(), diag::note_template_param_here);
5294 case NPV_NullPointer:
5295 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
5296 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
5302 // -- For a non-type template-parameter of type pointer to data
5303 // member, qualification conversions (4.4) are applied.
5304 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
5306 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5312 /// \brief Check a template argument against its corresponding
5313 /// template template parameter.
5315 /// This routine implements the semantics of C++ [temp.arg.template].
5316 /// It returns true if an error occurred, and false otherwise.
5317 bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
5318 TemplateArgumentLoc &Arg,
5319 unsigned ArgumentPackIndex) {
5320 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
5321 TemplateDecl *Template = Name.getAsTemplateDecl();
5323 // Any dependent template name is fine.
5324 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
5328 // C++0x [temp.arg.template]p1:
5329 // A template-argument for a template template-parameter shall be
5330 // the name of a class template or an alias template, expressed as an
5331 // id-expression. When the template-argument names a class template, only
5332 // primary class templates are considered when matching the
5333 // template template argument with the corresponding parameter;
5334 // partial specializations are not considered even if their
5335 // parameter lists match that of the template template parameter.
5337 // Note that we also allow template template parameters here, which
5338 // will happen when we are dealing with, e.g., class template
5339 // partial specializations.
5340 if (!isa<ClassTemplateDecl>(Template) &&
5341 !isa<TemplateTemplateParmDecl>(Template) &&
5342 !isa<TypeAliasTemplateDecl>(Template)) {
5343 assert(isa<FunctionTemplateDecl>(Template) &&
5344 "Only function templates are possible here");
5345 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
5346 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
5350 TemplateParameterList *Params = Param->getTemplateParameters();
5351 if (Param->isExpandedParameterPack())
5352 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
5354 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
5357 TPL_TemplateTemplateArgumentMatch,
5361 /// \brief Given a non-type template argument that refers to a
5362 /// declaration and the type of its corresponding non-type template
5363 /// parameter, produce an expression that properly refers to that
5366 Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5368 SourceLocation Loc) {
5369 // C++ [temp.param]p8:
5371 // A non-type template-parameter of type "array of T" or
5372 // "function returning T" is adjusted to be of type "pointer to
5373 // T" or "pointer to function returning T", respectively.
5374 if (ParamType->isArrayType())
5375 ParamType = Context.getArrayDecayedType(ParamType);
5376 else if (ParamType->isFunctionType())
5377 ParamType = Context.getPointerType(ParamType);
5379 // For a NULL non-type template argument, return nullptr casted to the
5380 // parameter's type.
5381 if (Arg.getKind() == TemplateArgument::NullPtr) {
5382 return ImpCastExprToType(
5383 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
5385 ParamType->getAs<MemberPointerType>()
5386 ? CK_NullToMemberPointer
5387 : CK_NullToPointer);
5389 assert(Arg.getKind() == TemplateArgument::Declaration &&
5390 "Only declaration template arguments permitted here");
5392 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
5394 if (VD->getDeclContext()->isRecord() &&
5395 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
5396 isa<IndirectFieldDecl>(VD))) {
5397 // If the value is a class member, we might have a pointer-to-member.
5398 // Determine whether the non-type template template parameter is of
5399 // pointer-to-member type. If so, we need to build an appropriate
5400 // expression for a pointer-to-member, since a "normal" DeclRefExpr
5401 // would refer to the member itself.
5402 if (ParamType->isMemberPointerType()) {
5404 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
5405 NestedNameSpecifier *Qualifier
5406 = NestedNameSpecifier::Create(Context, nullptr, false,
5407 ClassType.getTypePtr());
5409 SS.MakeTrivial(Context, Qualifier, Loc);
5411 // The actual value-ness of this is unimportant, but for
5412 // internal consistency's sake, references to instance methods
5414 ExprValueKind VK = VK_LValue;
5415 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
5418 ExprResult RefExpr = BuildDeclRefExpr(VD,
5419 VD->getType().getNonReferenceType(),
5423 if (RefExpr.isInvalid())
5426 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
5428 // We might need to perform a trailing qualification conversion, since
5429 // the element type on the parameter could be more qualified than the
5430 // element type in the expression we constructed.
5431 bool ObjCLifetimeConversion;
5432 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
5433 ParamType.getUnqualifiedType(), false,
5434 ObjCLifetimeConversion))
5435 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
5437 assert(!RefExpr.isInvalid() &&
5438 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
5439 ParamType.getUnqualifiedType()));
5444 QualType T = VD->getType().getNonReferenceType();
5446 if (ParamType->isPointerType()) {
5447 // When the non-type template parameter is a pointer, take the
5448 // address of the declaration.
5449 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
5450 if (RefExpr.isInvalid())
5453 if (T->isFunctionType() || T->isArrayType()) {
5454 // Decay functions and arrays.
5455 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
5456 if (RefExpr.isInvalid())
5462 // Take the address of everything else
5463 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
5466 ExprValueKind VK = VK_RValue;
5468 // If the non-type template parameter has reference type, qualify the
5469 // resulting declaration reference with the extra qualifiers on the
5470 // type that the reference refers to.
5471 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
5473 T = Context.getQualifiedType(T,
5474 TargetRef->getPointeeType().getQualifiers());
5475 } else if (isa<FunctionDecl>(VD)) {
5476 // References to functions are always lvalues.
5480 return BuildDeclRefExpr(VD, T, VK, Loc);
5483 /// \brief Construct a new expression that refers to the given
5484 /// integral template argument with the given source-location
5487 /// This routine takes care of the mapping from an integral template
5488 /// argument (which may have any integral type) to the appropriate
5491 Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5492 SourceLocation Loc) {
5493 assert(Arg.getKind() == TemplateArgument::Integral &&
5494 "Operation is only valid for integral template arguments");
5495 QualType OrigT = Arg.getIntegralType();
5497 // If this is an enum type that we're instantiating, we need to use an integer
5498 // type the same size as the enumerator. We don't want to build an
5499 // IntegerLiteral with enum type. The integer type of an enum type can be of
5500 // any integral type with C++11 enum classes, make sure we create the right
5501 // type of literal for it.
5503 if (const EnumType *ET = OrigT->getAs<EnumType>())
5504 T = ET->getDecl()->getIntegerType();
5507 if (T->isAnyCharacterType()) {
5508 // This does not need to handle u8 character literals because those are
5509 // of type char, and so can also be covered by an ASCII character literal.
5510 CharacterLiteral::CharacterKind Kind;
5511 if (T->isWideCharType())
5512 Kind = CharacterLiteral::Wide;
5513 else if (T->isChar16Type())
5514 Kind = CharacterLiteral::UTF16;
5515 else if (T->isChar32Type())
5516 Kind = CharacterLiteral::UTF32;
5518 Kind = CharacterLiteral::Ascii;
5520 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
5522 } else if (T->isBooleanType()) {
5523 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
5525 } else if (T->isNullPtrType()) {
5526 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
5528 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
5531 if (OrigT->isEnumeralType()) {
5532 // FIXME: This is a hack. We need a better way to handle substituted
5533 // non-type template parameters.
5534 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
5536 Context.getTrivialTypeSourceInfo(OrigT, Loc),
5543 /// \brief Match two template parameters within template parameter lists.
5544 static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
5546 Sema::TemplateParameterListEqualKind Kind,
5547 SourceLocation TemplateArgLoc) {
5548 // Check the actual kind (type, non-type, template).
5549 if (Old->getKind() != New->getKind()) {
5551 unsigned NextDiag = diag::err_template_param_different_kind;
5552 if (TemplateArgLoc.isValid()) {
5553 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5554 NextDiag = diag::note_template_param_different_kind;
5556 S.Diag(New->getLocation(), NextDiag)
5557 << (Kind != Sema::TPL_TemplateMatch);
5558 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
5559 << (Kind != Sema::TPL_TemplateMatch);
5565 // Check that both are parameter packs are neither are parameter packs.
5566 // However, if we are matching a template template argument to a
5567 // template template parameter, the template template parameter can have
5568 // a parameter pack where the template template argument does not.
5569 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
5570 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5571 Old->isTemplateParameterPack())) {
5573 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
5574 if (TemplateArgLoc.isValid()) {
5575 S.Diag(TemplateArgLoc,
5576 diag::err_template_arg_template_params_mismatch);
5577 NextDiag = diag::note_template_parameter_pack_non_pack;
5580 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
5581 : isa<NonTypeTemplateParmDecl>(New)? 1
5583 S.Diag(New->getLocation(), NextDiag)
5584 << ParamKind << New->isParameterPack();
5585 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
5586 << ParamKind << Old->isParameterPack();
5592 // For non-type template parameters, check the type of the parameter.
5593 if (NonTypeTemplateParmDecl *OldNTTP
5594 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
5595 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
5597 // If we are matching a template template argument to a template
5598 // template parameter and one of the non-type template parameter types
5599 // is dependent, then we must wait until template instantiation time
5600 // to actually compare the arguments.
5601 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5602 (OldNTTP->getType()->isDependentType() ||
5603 NewNTTP->getType()->isDependentType()))
5606 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
5608 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
5609 if (TemplateArgLoc.isValid()) {
5610 S.Diag(TemplateArgLoc,
5611 diag::err_template_arg_template_params_mismatch);
5612 NextDiag = diag::note_template_nontype_parm_different_type;
5614 S.Diag(NewNTTP->getLocation(), NextDiag)
5615 << NewNTTP->getType()
5616 << (Kind != Sema::TPL_TemplateMatch);
5617 S.Diag(OldNTTP->getLocation(),
5618 diag::note_template_nontype_parm_prev_declaration)
5619 << OldNTTP->getType();
5628 // For template template parameters, check the template parameter types.
5629 // The template parameter lists of template template
5630 // parameters must agree.
5631 if (TemplateTemplateParmDecl *OldTTP
5632 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
5633 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
5634 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
5635 OldTTP->getTemplateParameters(),
5637 (Kind == Sema::TPL_TemplateMatch
5638 ? Sema::TPL_TemplateTemplateParmMatch
5646 /// \brief Diagnose a known arity mismatch when comparing template argument
5649 void DiagnoseTemplateParameterListArityMismatch(Sema &S,
5650 TemplateParameterList *New,
5651 TemplateParameterList *Old,
5652 Sema::TemplateParameterListEqualKind Kind,
5653 SourceLocation TemplateArgLoc) {
5654 unsigned NextDiag = diag::err_template_param_list_different_arity;
5655 if (TemplateArgLoc.isValid()) {
5656 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5657 NextDiag = diag::note_template_param_list_different_arity;
5659 S.Diag(New->getTemplateLoc(), NextDiag)
5660 << (New->size() > Old->size())
5661 << (Kind != Sema::TPL_TemplateMatch)
5662 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
5663 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
5664 << (Kind != Sema::TPL_TemplateMatch)
5665 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
5668 /// \brief Determine whether the given template parameter lists are
5671 /// \param New The new template parameter list, typically written in the
5672 /// source code as part of a new template declaration.
5674 /// \param Old The old template parameter list, typically found via
5675 /// name lookup of the template declared with this template parameter
5678 /// \param Complain If true, this routine will produce a diagnostic if
5679 /// the template parameter lists are not equivalent.
5681 /// \param Kind describes how we are to match the template parameter lists.
5683 /// \param TemplateArgLoc If this source location is valid, then we
5684 /// are actually checking the template parameter list of a template
5685 /// argument (New) against the template parameter list of its
5686 /// corresponding template template parameter (Old). We produce
5687 /// slightly different diagnostics in this scenario.
5689 /// \returns True if the template parameter lists are equal, false
5692 Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
5693 TemplateParameterList *Old,
5695 TemplateParameterListEqualKind Kind,
5696 SourceLocation TemplateArgLoc) {
5697 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
5699 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5705 // C++0x [temp.arg.template]p3:
5706 // A template-argument matches a template template-parameter (call it P)
5707 // when each of the template parameters in the template-parameter-list of
5708 // the template-argument's corresponding class template or alias template
5709 // (call it A) matches the corresponding template parameter in the
5710 // template-parameter-list of P. [...]
5711 TemplateParameterList::iterator NewParm = New->begin();
5712 TemplateParameterList::iterator NewParmEnd = New->end();
5713 for (TemplateParameterList::iterator OldParm = Old->begin(),
5714 OldParmEnd = Old->end();
5715 OldParm != OldParmEnd; ++OldParm) {
5716 if (Kind != TPL_TemplateTemplateArgumentMatch ||
5717 !(*OldParm)->isTemplateParameterPack()) {
5718 if (NewParm == NewParmEnd) {
5720 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5726 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5727 Kind, TemplateArgLoc))
5734 // C++0x [temp.arg.template]p3:
5735 // [...] When P's template- parameter-list contains a template parameter
5736 // pack (14.5.3), the template parameter pack will match zero or more
5737 // template parameters or template parameter packs in the
5738 // template-parameter-list of A with the same type and form as the
5739 // template parameter pack in P (ignoring whether those template
5740 // parameters are template parameter packs).
5741 for (; NewParm != NewParmEnd; ++NewParm) {
5742 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5743 Kind, TemplateArgLoc))
5748 // Make sure we exhausted all of the arguments.
5749 if (NewParm != NewParmEnd) {
5751 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5760 /// \brief Check whether a template can be declared within this scope.
5762 /// If the template declaration is valid in this scope, returns
5763 /// false. Otherwise, issues a diagnostic and returns true.
5765 Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
5769 // Find the nearest enclosing declaration scope.
5770 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5771 (S->getFlags() & Scope::TemplateParamScope) != 0)
5775 // A template [...] shall not have C linkage.
5776 DeclContext *Ctx = S->getEntity();
5777 if (Ctx && Ctx->isExternCContext())
5778 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
5779 << TemplateParams->getSourceRange();
5781 while (Ctx && isa<LinkageSpecDecl>(Ctx))
5782 Ctx = Ctx->getParent();
5785 // A template-declaration can appear only as a namespace scope or
5786 // class scope declaration.
5788 if (Ctx->isFileContext())
5790 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
5791 // C++ [temp.mem]p2:
5792 // A local class shall not have member templates.
5793 if (RD->isLocalClass())
5794 return Diag(TemplateParams->getTemplateLoc(),
5795 diag::err_template_inside_local_class)
5796 << TemplateParams->getSourceRange();
5802 return Diag(TemplateParams->getTemplateLoc(),
5803 diag::err_template_outside_namespace_or_class_scope)
5804 << TemplateParams->getSourceRange();
5807 /// \brief Determine what kind of template specialization the given declaration
5809 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
5811 return TSK_Undeclared;
5813 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
5814 return Record->getTemplateSpecializationKind();
5815 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
5816 return Function->getTemplateSpecializationKind();
5817 if (VarDecl *Var = dyn_cast<VarDecl>(D))
5818 return Var->getTemplateSpecializationKind();
5820 return TSK_Undeclared;
5823 /// \brief Check whether a specialization is well-formed in the current
5826 /// This routine determines whether a template specialization can be declared
5827 /// in the current context (C++ [temp.expl.spec]p2).
5829 /// \param S the semantic analysis object for which this check is being
5832 /// \param Specialized the entity being specialized or instantiated, which
5833 /// may be a kind of template (class template, function template, etc.) or
5834 /// a member of a class template (member function, static data member,
5837 /// \param PrevDecl the previous declaration of this entity, if any.
5839 /// \param Loc the location of the explicit specialization or instantiation of
5842 /// \param IsPartialSpecialization whether this is a partial specialization of
5843 /// a class template.
5845 /// \returns true if there was an error that we cannot recover from, false
5847 static bool CheckTemplateSpecializationScope(Sema &S,
5848 NamedDecl *Specialized,
5849 NamedDecl *PrevDecl,
5851 bool IsPartialSpecialization) {
5852 // Keep these "kind" numbers in sync with the %select statements in the
5853 // various diagnostics emitted by this routine.
5855 if (isa<ClassTemplateDecl>(Specialized))
5856 EntityKind = IsPartialSpecialization? 1 : 0;
5857 else if (isa<VarTemplateDecl>(Specialized))
5858 EntityKind = IsPartialSpecialization ? 3 : 2;
5859 else if (isa<FunctionTemplateDecl>(Specialized))
5861 else if (isa<CXXMethodDecl>(Specialized))
5863 else if (isa<VarDecl>(Specialized))
5865 else if (isa<RecordDecl>(Specialized))
5867 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
5870 S.Diag(Loc, diag::err_template_spec_unknown_kind)
5871 << S.getLangOpts().CPlusPlus11;
5872 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5876 // C++ [temp.expl.spec]p2:
5877 // An explicit specialization shall be declared in the namespace
5878 // of which the template is a member, or, for member templates, in
5879 // the namespace of which the enclosing class or enclosing class
5880 // template is a member. An explicit specialization of a member
5881 // function, member class or static data member of a class
5882 // template shall be declared in the namespace of which the class
5883 // template is a member. Such a declaration may also be a
5884 // definition. If the declaration is not a definition, the
5885 // specialization may be defined later in the name- space in which
5886 // the explicit specialization was declared, or in a namespace
5887 // that encloses the one in which the explicit specialization was
5889 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
5890 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
5895 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
5896 if (S.getLangOpts().MicrosoftExt) {
5897 // Do not warn for class scope explicit specialization during
5898 // instantiation, warning was already emitted during pattern
5899 // semantic analysis.
5900 if (!S.ActiveTemplateInstantiations.size())
5901 S.Diag(Loc, diag::ext_function_specialization_in_class)
5904 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5910 if (S.CurContext->isRecord() &&
5911 !S.CurContext->Equals(Specialized->getDeclContext())) {
5912 // Make sure that we're specializing in the right record context.
5913 // Otherwise, things can go horribly wrong.
5914 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5919 // C++ [temp.class.spec]p6:
5920 // A class template partial specialization may be declared or redeclared
5921 // in any namespace scope in which its definition may be defined (14.5.1
5923 DeclContext *SpecializedContext
5924 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
5925 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
5927 // Make sure that this redeclaration (or definition) occurs in an enclosing
5929 // Note that HandleDeclarator() performs this check for explicit
5930 // specializations of function templates, static data members, and member
5931 // functions, so we skip the check here for those kinds of entities.
5932 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
5933 // Should we refactor that check, so that it occurs later?
5934 if (!DC->Encloses(SpecializedContext) &&
5935 !(isa<FunctionTemplateDecl>(Specialized) ||
5936 isa<FunctionDecl>(Specialized) ||
5937 isa<VarTemplateDecl>(Specialized) ||
5938 isa<VarDecl>(Specialized))) {
5939 if (isa<TranslationUnitDecl>(SpecializedContext))
5940 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
5941 << EntityKind << Specialized;
5942 else if (isa<NamespaceDecl>(SpecializedContext)) {
5943 int Diag = diag::err_template_spec_redecl_out_of_scope;
5944 if (S.getLangOpts().MicrosoftExt)
5945 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
5946 S.Diag(Loc, Diag) << EntityKind << Specialized
5947 << cast<NamedDecl>(SpecializedContext);
5949 llvm_unreachable("unexpected namespace context for specialization");
5951 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5952 } else if ((!PrevDecl ||
5953 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
5954 getTemplateSpecializationKind(PrevDecl) ==
5955 TSK_ImplicitInstantiation)) {
5956 // C++ [temp.exp.spec]p2:
5957 // An explicit specialization shall be declared in the namespace of which
5958 // the template is a member, or, for member templates, in the namespace
5959 // of which the enclosing class or enclosing class template is a member.
5960 // An explicit specialization of a member function, member class or
5961 // static data member of a class template shall be declared in the
5962 // namespace of which the class template is a member.
5964 // C++11 [temp.expl.spec]p2:
5965 // An explicit specialization shall be declared in a namespace enclosing
5966 // the specialized template.
5967 // C++11 [temp.explicit]p3:
5968 // An explicit instantiation shall appear in an enclosing namespace of its
5970 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
5971 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
5972 if (isa<TranslationUnitDecl>(SpecializedContext)) {
5973 assert(!IsCPlusPlus11Extension &&
5974 "DC encloses TU but isn't in enclosing namespace set");
5975 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
5976 << EntityKind << Specialized;
5977 } else if (isa<NamespaceDecl>(SpecializedContext)) {
5979 if (!IsCPlusPlus11Extension)
5980 Diag = diag::err_template_spec_decl_out_of_scope;
5981 else if (!S.getLangOpts().CPlusPlus11)
5982 Diag = diag::ext_template_spec_decl_out_of_scope;
5984 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
5986 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
5989 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5996 static SourceRange findTemplateParameter(unsigned Depth, Expr *E) {
5997 if (!E->isInstantiationDependent())
5998 return SourceLocation();
5999 DependencyChecker Checker(Depth);
6000 Checker.TraverseStmt(E);
6001 if (Checker.Match && Checker.MatchLoc.isInvalid())
6002 return E->getSourceRange();
6003 return Checker.MatchLoc;
6006 static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
6007 if (!TL.getType()->isDependentType())
6008 return SourceLocation();
6009 DependencyChecker Checker(Depth);
6010 Checker.TraverseTypeLoc(TL);
6011 if (Checker.Match && Checker.MatchLoc.isInvalid())
6012 return TL.getSourceRange();
6013 return Checker.MatchLoc;
6016 /// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
6017 /// that checks non-type template partial specialization arguments.
6018 static bool CheckNonTypeTemplatePartialSpecializationArgs(
6019 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
6020 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
6021 for (unsigned I = 0; I != NumArgs; ++I) {
6022 if (Args[I].getKind() == TemplateArgument::Pack) {
6023 if (CheckNonTypeTemplatePartialSpecializationArgs(
6024 S, TemplateNameLoc, Param, Args[I].pack_begin(),
6025 Args[I].pack_size(), IsDefaultArgument))
6031 if (Args[I].getKind() != TemplateArgument::Expression)
6034 Expr *ArgExpr = Args[I].getAsExpr();
6036 // We can have a pack expansion of any of the bullets below.
6037 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
6038 ArgExpr = Expansion->getPattern();
6040 // Strip off any implicit casts we added as part of type checking.
6041 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
6042 ArgExpr = ICE->getSubExpr();
6044 // C++ [temp.class.spec]p8:
6045 // A non-type argument is non-specialized if it is the name of a
6046 // non-type parameter. All other non-type arguments are
6049 // Below, we check the two conditions that only apply to
6050 // specialized non-type arguments, so skip any non-specialized
6052 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
6053 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
6056 // C++ [temp.class.spec]p9:
6057 // Within the argument list of a class template partial
6058 // specialization, the following restrictions apply:
6059 // -- A partially specialized non-type argument expression
6060 // shall not involve a template parameter of the partial
6061 // specialization except when the argument expression is a
6062 // simple identifier.
6063 SourceRange ParamUseRange =
6064 findTemplateParameter(Param->getDepth(), ArgExpr);
6065 if (ParamUseRange.isValid()) {
6066 if (IsDefaultArgument) {
6067 S.Diag(TemplateNameLoc,
6068 diag::err_dependent_non_type_arg_in_partial_spec);
6069 S.Diag(ParamUseRange.getBegin(),
6070 diag::note_dependent_non_type_default_arg_in_partial_spec)
6073 S.Diag(ParamUseRange.getBegin(),
6074 diag::err_dependent_non_type_arg_in_partial_spec)
6080 // -- The type of a template parameter corresponding to a
6081 // specialized non-type argument shall not be dependent on a
6082 // parameter of the specialization.
6084 // FIXME: We need to delay this check until instantiation in some cases:
6086 // template<template<typename> class X> struct A {
6087 // template<typename T, X<T> N> struct B;
6088 // template<typename T> struct B<T, 0>;
6090 // template<typename> using X = int;
6091 // A<X>::B<int, 0> b;
6092 ParamUseRange = findTemplateParameter(
6093 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
6094 if (ParamUseRange.isValid()) {
6095 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
6096 diag::err_dependent_typed_non_type_arg_in_partial_spec)
6097 << Param->getType() << ParamUseRange;
6098 S.Diag(Param->getLocation(), diag::note_template_param_here)
6099 << (IsDefaultArgument ? ParamUseRange : SourceRange());
6107 /// \brief Check the non-type template arguments of a class template
6108 /// partial specialization according to C++ [temp.class.spec]p9.
6110 /// \param TemplateNameLoc the location of the template name.
6111 /// \param TemplateParams the template parameters of the primary class
6113 /// \param NumExplicit the number of explicitly-specified template arguments.
6114 /// \param TemplateArgs the template arguments of the class template
6115 /// partial specialization.
6117 /// \returns \c true if there was an error, \c false otherwise.
6118 static bool CheckTemplatePartialSpecializationArgs(
6119 Sema &S, SourceLocation TemplateNameLoc,
6120 TemplateParameterList *TemplateParams, unsigned NumExplicit,
6121 SmallVectorImpl<TemplateArgument> &TemplateArgs) {
6122 const TemplateArgument *ArgList = TemplateArgs.data();
6124 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6125 NonTypeTemplateParmDecl *Param
6126 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
6130 if (CheckNonTypeTemplatePartialSpecializationArgs(
6131 S, TemplateNameLoc, Param, &ArgList[I], 1, I >= NumExplicit))
6139 Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
6141 SourceLocation KWLoc,
6142 SourceLocation ModulePrivateLoc,
6143 TemplateIdAnnotation &TemplateId,
6144 AttributeList *Attr,
6145 MultiTemplateParamsArg
6146 TemplateParameterLists,
6147 SkipBodyInfo *SkipBody) {
6148 assert(TUK != TUK_Reference && "References are not specializations");
6150 CXXScopeSpec &SS = TemplateId.SS;
6152 // NOTE: KWLoc is the location of the tag keyword. This will instead
6153 // store the location of the outermost template keyword in the declaration.
6154 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
6155 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
6156 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
6157 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
6158 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
6160 // Find the class template we're specializing
6161 TemplateName Name = TemplateId.Template.get();
6162 ClassTemplateDecl *ClassTemplate
6163 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
6165 if (!ClassTemplate) {
6166 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
6167 << (Name.getAsTemplateDecl() &&
6168 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
6172 bool isExplicitSpecialization = false;
6173 bool isPartialSpecialization = false;
6175 // Check the validity of the template headers that introduce this
6177 // FIXME: We probably shouldn't complain about these headers for
6178 // friend declarations.
6179 bool Invalid = false;
6180 TemplateParameterList *TemplateParams =
6181 MatchTemplateParametersToScopeSpecifier(
6182 KWLoc, TemplateNameLoc, SS, &TemplateId,
6183 TemplateParameterLists, TUK == TUK_Friend, isExplicitSpecialization,
6188 if (TemplateParams && TemplateParams->size() > 0) {
6189 isPartialSpecialization = true;
6191 if (TUK == TUK_Friend) {
6192 Diag(KWLoc, diag::err_partial_specialization_friend)
6193 << SourceRange(LAngleLoc, RAngleLoc);
6197 // C++ [temp.class.spec]p10:
6198 // The template parameter list of a specialization shall not
6199 // contain default template argument values.
6200 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6201 Decl *Param = TemplateParams->getParam(I);
6202 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6203 if (TTP->hasDefaultArgument()) {
6204 Diag(TTP->getDefaultArgumentLoc(),
6205 diag::err_default_arg_in_partial_spec);
6206 TTP->removeDefaultArgument();
6208 } else if (NonTypeTemplateParmDecl *NTTP
6209 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6210 if (Expr *DefArg = NTTP->getDefaultArgument()) {
6211 Diag(NTTP->getDefaultArgumentLoc(),
6212 diag::err_default_arg_in_partial_spec)
6213 << DefArg->getSourceRange();
6214 NTTP->removeDefaultArgument();
6217 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
6218 if (TTP->hasDefaultArgument()) {
6219 Diag(TTP->getDefaultArgument().getLocation(),
6220 diag::err_default_arg_in_partial_spec)
6221 << TTP->getDefaultArgument().getSourceRange();
6222 TTP->removeDefaultArgument();
6226 } else if (TemplateParams) {
6227 if (TUK == TUK_Friend)
6228 Diag(KWLoc, diag::err_template_spec_friend)
6229 << FixItHint::CreateRemoval(
6230 SourceRange(TemplateParams->getTemplateLoc(),
6231 TemplateParams->getRAngleLoc()))
6232 << SourceRange(LAngleLoc, RAngleLoc);
6234 isExplicitSpecialization = true;
6236 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
6239 // Check that the specialization uses the same tag kind as the
6240 // original template.
6241 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6242 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
6243 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
6244 Kind, TUK == TUK_Definition, KWLoc,
6245 ClassTemplate->getIdentifier())) {
6246 Diag(KWLoc, diag::err_use_with_wrong_tag)
6248 << FixItHint::CreateReplacement(KWLoc,
6249 ClassTemplate->getTemplatedDecl()->getKindName());
6250 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
6251 diag::note_previous_use);
6252 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
6255 // Translate the parser's template argument list in our AST format.
6256 TemplateArgumentListInfo TemplateArgs =
6257 makeTemplateArgumentListInfo(*this, TemplateId);
6259 // Check for unexpanded parameter packs in any of the template arguments.
6260 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
6261 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
6262 UPPC_PartialSpecialization))
6265 // Check that the template argument list is well-formed for this
6267 SmallVector<TemplateArgument, 4> Converted;
6268 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
6269 TemplateArgs, false, Converted))
6272 // Find the class template (partial) specialization declaration that
6273 // corresponds to these arguments.
6274 if (isPartialSpecialization) {
6275 if (CheckTemplatePartialSpecializationArgs(
6276 *this, TemplateNameLoc, ClassTemplate->getTemplateParameters(),
6277 TemplateArgs.size(), Converted))
6280 bool InstantiationDependent;
6281 if (!Name.isDependent() &&
6282 !TemplateSpecializationType::anyDependentTemplateArguments(
6283 TemplateArgs.getArgumentArray(),
6284 TemplateArgs.size(),
6285 InstantiationDependent)) {
6286 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
6287 << ClassTemplate->getDeclName();
6288 isPartialSpecialization = false;
6292 void *InsertPos = nullptr;
6293 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
6295 if (isPartialSpecialization)
6296 // FIXME: Template parameter list matters, too
6297 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
6299 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
6301 ClassTemplateSpecializationDecl *Specialization = nullptr;
6303 // Check whether we can declare a class template specialization in
6304 // the current scope.
6305 if (TUK != TUK_Friend &&
6306 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
6308 isPartialSpecialization))
6311 // The canonical type
6313 if (isPartialSpecialization) {
6314 // Build the canonical type that describes the converted template
6315 // arguments of the class template partial specialization.
6316 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6317 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
6321 if (Context.hasSameType(CanonType,
6322 ClassTemplate->getInjectedClassNameSpecialization())) {
6323 // C++ [temp.class.spec]p9b3:
6325 // -- The argument list of the specialization shall not be identical
6326 // to the implicit argument list of the primary template.
6327 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
6328 << /*class template*/0 << (TUK == TUK_Definition)
6329 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
6330 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
6331 ClassTemplate->getIdentifier(),
6335 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
6336 /*FriendLoc*/SourceLocation(),
6337 TemplateParameterLists.size() - 1,
6338 TemplateParameterLists.data());
6341 // Create a new class template partial specialization declaration node.
6342 ClassTemplatePartialSpecializationDecl *PrevPartial
6343 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
6344 ClassTemplatePartialSpecializationDecl *Partial
6345 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
6346 ClassTemplate->getDeclContext(),
6347 KWLoc, TemplateNameLoc,
6355 SetNestedNameSpecifier(Partial, SS);
6356 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
6357 Partial->setTemplateParameterListsInfo(
6358 Context, TemplateParameterLists.drop_back(1));
6362 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
6363 Specialization = Partial;
6365 // If we are providing an explicit specialization of a member class
6366 // template specialization, make a note of that.
6367 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
6368 PrevPartial->setMemberSpecialization();
6370 // Check that all of the template parameters of the class template
6371 // partial specialization are deducible from the template
6372 // arguments. If not, this class template partial specialization
6373 // will never be used.
6374 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
6375 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
6376 TemplateParams->getDepth(),
6379 if (!DeducibleParams.all()) {
6380 unsigned NumNonDeducible = DeducibleParams.size()-DeducibleParams.count();
6381 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
6382 << /*class template*/0 << (NumNonDeducible > 1)
6383 << SourceRange(TemplateNameLoc, RAngleLoc);
6384 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
6385 if (!DeducibleParams[I]) {
6386 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
6387 if (Param->getDeclName())
6388 Diag(Param->getLocation(),
6389 diag::note_partial_spec_unused_parameter)
6390 << Param->getDeclName();
6392 Diag(Param->getLocation(),
6393 diag::note_partial_spec_unused_parameter)
6399 // Create a new class template specialization declaration node for
6400 // this explicit specialization or friend declaration.
6402 = ClassTemplateSpecializationDecl::Create(Context, Kind,
6403 ClassTemplate->getDeclContext(),
6404 KWLoc, TemplateNameLoc,
6409 SetNestedNameSpecifier(Specialization, SS);
6410 if (TemplateParameterLists.size() > 0) {
6411 Specialization->setTemplateParameterListsInfo(Context,
6412 TemplateParameterLists);
6416 ClassTemplate->AddSpecialization(Specialization, InsertPos);
6418 if (CurContext->isDependentContext()) {
6419 // -fms-extensions permits specialization of nested classes without
6420 // fully specializing the outer class(es).
6421 assert(getLangOpts().MicrosoftExt &&
6422 "Only possible with -fms-extensions!");
6423 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6424 CanonType = Context.getTemplateSpecializationType(
6425 CanonTemplate, Converted.data(), Converted.size());
6427 CanonType = Context.getTypeDeclType(Specialization);
6431 // C++ [temp.expl.spec]p6:
6432 // If a template, a member template or the member of a class template is
6433 // explicitly specialized then that specialization shall be declared
6434 // before the first use of that specialization that would cause an implicit
6435 // instantiation to take place, in every translation unit in which such a
6436 // use occurs; no diagnostic is required.
6437 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
6439 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
6440 // Is there any previous explicit specialization declaration?
6441 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6448 SourceRange Range(TemplateNameLoc, RAngleLoc);
6449 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
6450 << Context.getTypeDeclType(Specialization) << Range;
6452 Diag(PrevDecl->getPointOfInstantiation(),
6453 diag::note_instantiation_required_here)
6454 << (PrevDecl->getTemplateSpecializationKind()
6455 != TSK_ImplicitInstantiation);
6460 // If this is not a friend, note that this is an explicit specialization.
6461 if (TUK != TUK_Friend)
6462 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
6464 // Check that this isn't a redefinition of this specialization.
6465 if (TUK == TUK_Definition) {
6466 RecordDecl *Def = Specialization->getDefinition();
6467 NamedDecl *Hidden = nullptr;
6468 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
6469 SkipBody->ShouldSkip = true;
6470 makeMergedDefinitionVisible(Hidden, KWLoc);
6471 // From here on out, treat this as just a redeclaration.
6472 TUK = TUK_Declaration;
6474 SourceRange Range(TemplateNameLoc, RAngleLoc);
6475 Diag(TemplateNameLoc, diag::err_redefinition)
6476 << Context.getTypeDeclType(Specialization) << Range;
6477 Diag(Def->getLocation(), diag::note_previous_definition);
6478 Specialization->setInvalidDecl();
6484 ProcessDeclAttributeList(S, Specialization, Attr);
6486 // Add alignment attributes if necessary; these attributes are checked when
6487 // the ASTContext lays out the structure.
6488 if (TUK == TUK_Definition) {
6489 AddAlignmentAttributesForRecord(Specialization);
6490 AddMsStructLayoutForRecord(Specialization);
6493 if (ModulePrivateLoc.isValid())
6494 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
6495 << (isPartialSpecialization? 1 : 0)
6496 << FixItHint::CreateRemoval(ModulePrivateLoc);
6498 // Build the fully-sugared type for this class template
6499 // specialization as the user wrote in the specialization
6500 // itself. This means that we'll pretty-print the type retrieved
6501 // from the specialization's declaration the way that the user
6502 // actually wrote the specialization, rather than formatting the
6503 // name based on the "canonical" representation used to store the
6504 // template arguments in the specialization.
6505 TypeSourceInfo *WrittenTy
6506 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
6507 TemplateArgs, CanonType);
6508 if (TUK != TUK_Friend) {
6509 Specialization->setTypeAsWritten(WrittenTy);
6510 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
6513 // C++ [temp.expl.spec]p9:
6514 // A template explicit specialization is in the scope of the
6515 // namespace in which the template was defined.
6517 // We actually implement this paragraph where we set the semantic
6518 // context (in the creation of the ClassTemplateSpecializationDecl),
6519 // but we also maintain the lexical context where the actual
6520 // definition occurs.
6521 Specialization->setLexicalDeclContext(CurContext);
6523 // We may be starting the definition of this specialization.
6524 if (TUK == TUK_Definition)
6525 Specialization->startDefinition();
6527 if (TUK == TUK_Friend) {
6528 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
6532 Friend->setAccess(AS_public);
6533 CurContext->addDecl(Friend);
6535 // Add the specialization into its lexical context, so that it can
6536 // be seen when iterating through the list of declarations in that
6537 // context. However, specializations are not found by name lookup.
6538 CurContext->addDecl(Specialization);
6540 return Specialization;
6543 Decl *Sema::ActOnTemplateDeclarator(Scope *S,
6544 MultiTemplateParamsArg TemplateParameterLists,
6546 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
6547 ActOnDocumentableDecl(NewDecl);
6551 /// \brief Strips various properties off an implicit instantiation
6552 /// that has just been explicitly specialized.
6553 static void StripImplicitInstantiation(NamedDecl *D) {
6554 D->dropAttr<DLLImportAttr>();
6555 D->dropAttr<DLLExportAttr>();
6557 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
6558 FD->setInlineSpecified(false);
6561 /// \brief Compute the diagnostic location for an explicit instantiation
6562 // declaration or definition.
6563 static SourceLocation DiagLocForExplicitInstantiation(
6564 NamedDecl* D, SourceLocation PointOfInstantiation) {
6565 // Explicit instantiations following a specialization have no effect and
6566 // hence no PointOfInstantiation. In that case, walk decl backwards
6567 // until a valid name loc is found.
6568 SourceLocation PrevDiagLoc = PointOfInstantiation;
6569 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
6570 Prev = Prev->getPreviousDecl()) {
6571 PrevDiagLoc = Prev->getLocation();
6573 assert(PrevDiagLoc.isValid() &&
6574 "Explicit instantiation without point of instantiation?");
6578 /// \brief Diagnose cases where we have an explicit template specialization
6579 /// before/after an explicit template instantiation, producing diagnostics
6580 /// for those cases where they are required and determining whether the
6581 /// new specialization/instantiation will have any effect.
6583 /// \param NewLoc the location of the new explicit specialization or
6586 /// \param NewTSK the kind of the new explicit specialization or instantiation.
6588 /// \param PrevDecl the previous declaration of the entity.
6590 /// \param PrevTSK the kind of the old explicit specialization or instantiatin.
6592 /// \param PrevPointOfInstantiation if valid, indicates where the previus
6593 /// declaration was instantiated (either implicitly or explicitly).
6595 /// \param HasNoEffect will be set to true to indicate that the new
6596 /// specialization or instantiation has no effect and should be ignored.
6598 /// \returns true if there was an error that should prevent the introduction of
6599 /// the new declaration into the AST, false otherwise.
6601 Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6602 TemplateSpecializationKind NewTSK,
6603 NamedDecl *PrevDecl,
6604 TemplateSpecializationKind PrevTSK,
6605 SourceLocation PrevPointOfInstantiation,
6606 bool &HasNoEffect) {
6607 HasNoEffect = false;
6610 case TSK_Undeclared:
6611 case TSK_ImplicitInstantiation:
6613 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
6614 "previous declaration must be implicit!");
6617 case TSK_ExplicitSpecialization:
6619 case TSK_Undeclared:
6620 case TSK_ExplicitSpecialization:
6621 // Okay, we're just specializing something that is either already
6622 // explicitly specialized or has merely been mentioned without any
6626 case TSK_ImplicitInstantiation:
6627 if (PrevPointOfInstantiation.isInvalid()) {
6628 // The declaration itself has not actually been instantiated, so it is
6629 // still okay to specialize it.
6630 StripImplicitInstantiation(PrevDecl);
6635 case TSK_ExplicitInstantiationDeclaration:
6636 case TSK_ExplicitInstantiationDefinition:
6637 assert((PrevTSK == TSK_ImplicitInstantiation ||
6638 PrevPointOfInstantiation.isValid()) &&
6639 "Explicit instantiation without point of instantiation?");
6641 // C++ [temp.expl.spec]p6:
6642 // If a template, a member template or the member of a class template
6643 // is explicitly specialized then that specialization shall be declared
6644 // before the first use of that specialization that would cause an
6645 // implicit instantiation to take place, in every translation unit in
6646 // which such a use occurs; no diagnostic is required.
6647 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
6648 // Is there any previous explicit specialization declaration?
6649 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
6653 Diag(NewLoc, diag::err_specialization_after_instantiation)
6655 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
6656 << (PrevTSK != TSK_ImplicitInstantiation);
6661 case TSK_ExplicitInstantiationDeclaration:
6663 case TSK_ExplicitInstantiationDeclaration:
6664 // This explicit instantiation declaration is redundant (that's okay).
6668 case TSK_Undeclared:
6669 case TSK_ImplicitInstantiation:
6670 // We're explicitly instantiating something that may have already been
6671 // implicitly instantiated; that's fine.
6674 case TSK_ExplicitSpecialization:
6675 // C++0x [temp.explicit]p4:
6676 // For a given set of template parameters, if an explicit instantiation
6677 // of a template appears after a declaration of an explicit
6678 // specialization for that template, the explicit instantiation has no
6683 case TSK_ExplicitInstantiationDefinition:
6684 // C++0x [temp.explicit]p10:
6685 // If an entity is the subject of both an explicit instantiation
6686 // declaration and an explicit instantiation definition in the same
6687 // translation unit, the definition shall follow the declaration.
6689 diag::err_explicit_instantiation_declaration_after_definition);
6691 // Explicit instantiations following a specialization have no effect and
6692 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
6693 // until a valid name loc is found.
6694 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6695 diag::note_explicit_instantiation_definition_here);
6700 case TSK_ExplicitInstantiationDefinition:
6702 case TSK_Undeclared:
6703 case TSK_ImplicitInstantiation:
6704 // We're explicitly instantiating something that may have already been
6705 // implicitly instantiated; that's fine.
6708 case TSK_ExplicitSpecialization:
6709 // C++ DR 259, C++0x [temp.explicit]p4:
6710 // For a given set of template parameters, if an explicit
6711 // instantiation of a template appears after a declaration of
6712 // an explicit specialization for that template, the explicit
6713 // instantiation has no effect.
6715 // In C++98/03 mode, we only give an extension warning here, because it
6716 // is not harmful to try to explicitly instantiate something that
6717 // has been explicitly specialized.
6718 Diag(NewLoc, getLangOpts().CPlusPlus11 ?
6719 diag::warn_cxx98_compat_explicit_instantiation_after_specialization :
6720 diag::ext_explicit_instantiation_after_specialization)
6722 Diag(PrevDecl->getLocation(),
6723 diag::note_previous_template_specialization);
6727 case TSK_ExplicitInstantiationDeclaration:
6728 // We're explicity instantiating a definition for something for which we
6729 // were previously asked to suppress instantiations. That's fine.
6731 // C++0x [temp.explicit]p4:
6732 // For a given set of template parameters, if an explicit instantiation
6733 // of a template appears after a declaration of an explicit
6734 // specialization for that template, the explicit instantiation has no
6736 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
6737 // Is there any previous explicit specialization declaration?
6738 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6746 case TSK_ExplicitInstantiationDefinition:
6747 // C++0x [temp.spec]p5:
6748 // For a given template and a given set of template-arguments,
6749 // - an explicit instantiation definition shall appear at most once
6752 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
6753 Diag(NewLoc, (getLangOpts().MSVCCompat)
6754 ? diag::ext_explicit_instantiation_duplicate
6755 : diag::err_explicit_instantiation_duplicate)
6757 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6758 diag::note_previous_explicit_instantiation);
6764 llvm_unreachable("Missing specialization/instantiation case?");
6767 /// \brief Perform semantic analysis for the given dependent function
6768 /// template specialization.
6770 /// The only possible way to get a dependent function template specialization
6771 /// is with a friend declaration, like so:
6774 /// template \<class T> void foo(T);
6775 /// template \<class T> class A {
6776 /// friend void foo<>(T);
6780 /// There really isn't any useful analysis we can do here, so we
6781 /// just store the information.
6783 Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6784 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6785 LookupResult &Previous) {
6786 // Remove anything from Previous that isn't a function template in
6787 // the correct context.
6788 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
6789 LookupResult::Filter F = Previous.makeFilter();
6790 while (F.hasNext()) {
6791 NamedDecl *D = F.next()->getUnderlyingDecl();
6792 if (!isa<FunctionTemplateDecl>(D) ||
6793 !FDLookupContext->InEnclosingNamespaceSetOf(
6794 D->getDeclContext()->getRedeclContext()))
6799 // Should this be diagnosed here?
6800 if (Previous.empty()) return true;
6802 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
6803 ExplicitTemplateArgs);
6807 /// \brief Perform semantic analysis for the given function template
6810 /// This routine performs all of the semantic analysis required for an
6811 /// explicit function template specialization. On successful completion,
6812 /// the function declaration \p FD will become a function template
6815 /// \param FD the function declaration, which will be updated to become a
6816 /// function template specialization.
6818 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
6819 /// if any. Note that this may be valid info even when 0 arguments are
6820 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
6821 /// as it anyway contains info on the angle brackets locations.
6823 /// \param Previous the set of declarations that may be specialized by
6824 /// this function specialization.
6825 bool Sema::CheckFunctionTemplateSpecialization(
6826 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
6827 LookupResult &Previous) {
6828 // The set of function template specializations that could match this
6829 // explicit function template specialization.
6830 UnresolvedSet<8> Candidates;
6831 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
6832 /*ForTakingAddress=*/false);
6834 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
6835 ConvertedTemplateArgs;
6837 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
6838 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6840 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
6841 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
6842 // Only consider templates found within the same semantic lookup scope as
6844 if (!FDLookupContext->InEnclosingNamespaceSetOf(
6845 Ovl->getDeclContext()->getRedeclContext()))
6848 // When matching a constexpr member function template specialization
6849 // against the primary template, we don't yet know whether the
6850 // specialization has an implicit 'const' (because we don't know whether
6851 // it will be a static member function until we know which template it
6852 // specializes), so adjust it now assuming it specializes this template.
6853 QualType FT = FD->getType();
6854 if (FD->isConstexpr()) {
6855 CXXMethodDecl *OldMD =
6856 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
6857 if (OldMD && OldMD->isConst()) {
6858 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
6859 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6860 EPI.TypeQuals |= Qualifiers::Const;
6861 FT = Context.getFunctionType(FPT->getReturnType(),
6862 FPT->getParamTypes(), EPI);
6866 TemplateArgumentListInfo Args;
6867 if (ExplicitTemplateArgs)
6868 Args = *ExplicitTemplateArgs;
6870 // C++ [temp.expl.spec]p11:
6871 // A trailing template-argument can be left unspecified in the
6872 // template-id naming an explicit function template specialization
6873 // provided it can be deduced from the function argument type.
6874 // Perform template argument deduction to determine whether we may be
6875 // specializing this template.
6876 // FIXME: It is somewhat wasteful to build
6877 TemplateDeductionInfo Info(FailedCandidates.getLocation());
6878 FunctionDecl *Specialization = nullptr;
6879 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
6880 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
6881 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, Info)) {
6882 // Template argument deduction failed; record why it failed, so
6883 // that we can provide nifty diagnostics.
6884 FailedCandidates.addCandidate()
6885 .set(FunTmpl->getTemplatedDecl(),
6886 MakeDeductionFailureInfo(Context, TDK, Info));
6891 // Record this candidate.
6892 if (ExplicitTemplateArgs)
6893 ConvertedTemplateArgs[Specialization] = std::move(Args);
6894 Candidates.addDecl(Specialization, I.getAccess());
6898 // Find the most specialized function template.
6899 UnresolvedSetIterator Result = getMostSpecialized(
6900 Candidates.begin(), Candidates.end(), FailedCandidates,
6902 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
6903 PDiag(diag::err_function_template_spec_ambiguous)
6904 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
6905 PDiag(diag::note_function_template_spec_matched));
6907 if (Result == Candidates.end())
6910 // Ignore access information; it doesn't figure into redeclaration checking.
6911 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
6913 FunctionTemplateSpecializationInfo *SpecInfo
6914 = Specialization->getTemplateSpecializationInfo();
6915 assert(SpecInfo && "Function template specialization info missing?");
6917 // Note: do not overwrite location info if previous template
6918 // specialization kind was explicit.
6919 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
6920 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
6921 Specialization->setLocation(FD->getLocation());
6922 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
6923 // function can differ from the template declaration with respect to
6924 // the constexpr specifier.
6925 Specialization->setConstexpr(FD->isConstexpr());
6928 // FIXME: Check if the prior specialization has a point of instantiation.
6929 // If so, we have run afoul of .
6931 // If this is a friend declaration, then we're not really declaring
6932 // an explicit specialization.
6933 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
6935 // Check the scope of this explicit specialization.
6937 CheckTemplateSpecializationScope(*this,
6938 Specialization->getPrimaryTemplate(),
6939 Specialization, FD->getLocation(),
6943 // C++ [temp.expl.spec]p6:
6944 // If a template, a member template or the member of a class template is
6945 // explicitly specialized then that specialization shall be declared
6946 // before the first use of that specialization that would cause an implicit
6947 // instantiation to take place, in every translation unit in which such a
6948 // use occurs; no diagnostic is required.
6949 bool HasNoEffect = false;
6951 CheckSpecializationInstantiationRedecl(FD->getLocation(),
6952 TSK_ExplicitSpecialization,
6954 SpecInfo->getTemplateSpecializationKind(),
6955 SpecInfo->getPointOfInstantiation(),
6959 // Mark the prior declaration as an explicit specialization, so that later
6960 // clients know that this is an explicit specialization.
6962 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
6963 MarkUnusedFileScopedDecl(Specialization);
6966 // Turn the given function declaration into a function template
6967 // specialization, with the template arguments from the previous
6969 // Take copies of (semantic and syntactic) template argument lists.
6970 const TemplateArgumentList* TemplArgs = new (Context)
6971 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
6972 FD->setFunctionTemplateSpecialization(
6973 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
6974 SpecInfo->getTemplateSpecializationKind(),
6975 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
6977 // The "previous declaration" for this function template specialization is
6978 // the prior function template specialization.
6980 Previous.addDecl(Specialization);
6984 /// \brief Perform semantic analysis for the given non-template member
6987 /// This routine performs all of the semantic analysis required for an
6988 /// explicit member function specialization. On successful completion,
6989 /// the function declaration \p FD will become a member function
6992 /// \param Member the member declaration, which will be updated to become a
6995 /// \param Previous the set of declarations, one of which may be specialized
6996 /// by this function specialization; the set will be modified to contain the
6997 /// redeclared member.
6999 Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
7000 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
7002 // Try to find the member we are instantiating.
7003 NamedDecl *Instantiation = nullptr;
7004 NamedDecl *InstantiatedFrom = nullptr;
7005 MemberSpecializationInfo *MSInfo = nullptr;
7007 if (Previous.empty()) {
7008 // Nowhere to look anyway.
7009 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
7010 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7012 NamedDecl *D = (*I)->getUnderlyingDecl();
7013 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
7014 QualType Adjusted = Function->getType();
7015 if (!hasExplicitCallingConv(Adjusted))
7016 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
7017 if (Context.hasSameType(Adjusted, Method->getType())) {
7018 Instantiation = Method;
7019 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
7020 MSInfo = Method->getMemberSpecializationInfo();
7025 } else if (isa<VarDecl>(Member)) {
7027 if (Previous.isSingleResult() &&
7028 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
7029 if (PrevVar->isStaticDataMember()) {
7030 Instantiation = PrevVar;
7031 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
7032 MSInfo = PrevVar->getMemberSpecializationInfo();
7034 } else if (isa<RecordDecl>(Member)) {
7035 CXXRecordDecl *PrevRecord;
7036 if (Previous.isSingleResult() &&
7037 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
7038 Instantiation = PrevRecord;
7039 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
7040 MSInfo = PrevRecord->getMemberSpecializationInfo();
7042 } else if (isa<EnumDecl>(Member)) {
7044 if (Previous.isSingleResult() &&
7045 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
7046 Instantiation = PrevEnum;
7047 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
7048 MSInfo = PrevEnum->getMemberSpecializationInfo();
7052 if (!Instantiation) {
7053 // There is no previous declaration that matches. Since member
7054 // specializations are always out-of-line, the caller will complain about
7055 // this mismatch later.
7059 // If this is a friend, just bail out here before we start turning
7060 // things into explicit specializations.
7061 if (Member->getFriendObjectKind() != Decl::FOK_None) {
7062 // Preserve instantiation information.
7063 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
7064 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
7065 cast<CXXMethodDecl>(InstantiatedFrom),
7066 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
7067 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
7068 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
7069 cast<CXXRecordDecl>(InstantiatedFrom),
7070 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
7074 Previous.addDecl(Instantiation);
7078 // Make sure that this is a specialization of a member.
7079 if (!InstantiatedFrom) {
7080 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
7082 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
7086 // C++ [temp.expl.spec]p6:
7087 // If a template, a member template or the member of a class template is
7088 // explicitly specialized then that specialization shall be declared
7089 // before the first use of that specialization that would cause an implicit
7090 // instantiation to take place, in every translation unit in which such a
7091 // use occurs; no diagnostic is required.
7092 assert(MSInfo && "Member specialization info missing?");
7094 bool HasNoEffect = false;
7095 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
7096 TSK_ExplicitSpecialization,
7098 MSInfo->getTemplateSpecializationKind(),
7099 MSInfo->getPointOfInstantiation(),
7103 // Check the scope of this explicit specialization.
7104 if (CheckTemplateSpecializationScope(*this,
7106 Instantiation, Member->getLocation(),
7110 // Note that this is an explicit instantiation of a member.
7111 // the original declaration to note that it is an explicit specialization
7112 // (if it was previously an implicit instantiation). This latter step
7113 // makes bookkeeping easier.
7114 if (isa<FunctionDecl>(Member)) {
7115 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
7116 if (InstantiationFunction->getTemplateSpecializationKind() ==
7117 TSK_ImplicitInstantiation) {
7118 InstantiationFunction->setTemplateSpecializationKind(
7119 TSK_ExplicitSpecialization);
7120 InstantiationFunction->setLocation(Member->getLocation());
7123 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
7124 cast<CXXMethodDecl>(InstantiatedFrom),
7125 TSK_ExplicitSpecialization);
7126 MarkUnusedFileScopedDecl(InstantiationFunction);
7127 } else if (isa<VarDecl>(Member)) {
7128 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
7129 if (InstantiationVar->getTemplateSpecializationKind() ==
7130 TSK_ImplicitInstantiation) {
7131 InstantiationVar->setTemplateSpecializationKind(
7132 TSK_ExplicitSpecialization);
7133 InstantiationVar->setLocation(Member->getLocation());
7136 cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
7137 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
7138 MarkUnusedFileScopedDecl(InstantiationVar);
7139 } else if (isa<CXXRecordDecl>(Member)) {
7140 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
7141 if (InstantiationClass->getTemplateSpecializationKind() ==
7142 TSK_ImplicitInstantiation) {
7143 InstantiationClass->setTemplateSpecializationKind(
7144 TSK_ExplicitSpecialization);
7145 InstantiationClass->setLocation(Member->getLocation());
7148 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
7149 cast<CXXRecordDecl>(InstantiatedFrom),
7150 TSK_ExplicitSpecialization);
7152 assert(isa<EnumDecl>(Member) && "Only member enums remain");
7153 EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
7154 if (InstantiationEnum->getTemplateSpecializationKind() ==
7155 TSK_ImplicitInstantiation) {
7156 InstantiationEnum->setTemplateSpecializationKind(
7157 TSK_ExplicitSpecialization);
7158 InstantiationEnum->setLocation(Member->getLocation());
7161 cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
7162 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
7165 // Save the caller the trouble of having to figure out which declaration
7166 // this specialization matches.
7168 Previous.addDecl(Instantiation);
7172 /// \brief Check the scope of an explicit instantiation.
7174 /// \returns true if a serious error occurs, false otherwise.
7175 static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
7176 SourceLocation InstLoc,
7177 bool WasQualifiedName) {
7178 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
7179 DeclContext *CurContext = S.CurContext->getRedeclContext();
7181 if (CurContext->isRecord()) {
7182 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
7187 // C++11 [temp.explicit]p3:
7188 // An explicit instantiation shall appear in an enclosing namespace of its
7189 // template. If the name declared in the explicit instantiation is an
7190 // unqualified name, the explicit instantiation shall appear in the
7191 // namespace where its template is declared or, if that namespace is inline
7192 // (7.3.1), any namespace from its enclosing namespace set.
7194 // This is DR275, which we do not retroactively apply to C++98/03.
7195 if (WasQualifiedName) {
7196 if (CurContext->Encloses(OrigContext))
7199 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
7203 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
7204 if (WasQualifiedName)
7206 S.getLangOpts().CPlusPlus11?
7207 diag::err_explicit_instantiation_out_of_scope :
7208 diag::warn_explicit_instantiation_out_of_scope_0x)
7212 S.getLangOpts().CPlusPlus11?
7213 diag::err_explicit_instantiation_unqualified_wrong_namespace :
7214 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
7218 S.getLangOpts().CPlusPlus11?
7219 diag::err_explicit_instantiation_must_be_global :
7220 diag::warn_explicit_instantiation_must_be_global_0x)
7222 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
7226 /// \brief Determine whether the given scope specifier has a template-id in it.
7227 static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
7231 // C++11 [temp.explicit]p3:
7232 // If the explicit instantiation is for a member function, a member class
7233 // or a static data member of a class template specialization, the name of
7234 // the class template specialization in the qualified-id for the member
7235 // name shall be a simple-template-id.
7237 // C++98 has the same restriction, just worded differently.
7238 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
7239 NNS = NNS->getPrefix())
7240 if (const Type *T = NNS->getAsType())
7241 if (isa<TemplateSpecializationType>(T))
7247 // Explicit instantiation of a class template specialization
7249 Sema::ActOnExplicitInstantiation(Scope *S,
7250 SourceLocation ExternLoc,
7251 SourceLocation TemplateLoc,
7253 SourceLocation KWLoc,
7254 const CXXScopeSpec &SS,
7255 TemplateTy TemplateD,
7256 SourceLocation TemplateNameLoc,
7257 SourceLocation LAngleLoc,
7258 ASTTemplateArgsPtr TemplateArgsIn,
7259 SourceLocation RAngleLoc,
7260 AttributeList *Attr) {
7261 // Find the class template we're specializing
7262 TemplateName Name = TemplateD.get();
7263 TemplateDecl *TD = Name.getAsTemplateDecl();
7264 // Check that the specialization uses the same tag kind as the
7265 // original template.
7266 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7267 assert(Kind != TTK_Enum &&
7268 "Invalid enum tag in class template explicit instantiation!");
7270 if (isa<TypeAliasTemplateDecl>(TD)) {
7271 Diag(KWLoc, diag::err_tag_reference_non_tag) << Kind;
7272 Diag(TD->getTemplatedDecl()->getLocation(),
7273 diag::note_previous_use);
7277 ClassTemplateDecl *ClassTemplate = cast<ClassTemplateDecl>(TD);
7279 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
7280 Kind, /*isDefinition*/false, KWLoc,
7281 ClassTemplate->getIdentifier())) {
7282 Diag(KWLoc, diag::err_use_with_wrong_tag)
7284 << FixItHint::CreateReplacement(KWLoc,
7285 ClassTemplate->getTemplatedDecl()->getKindName());
7286 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
7287 diag::note_previous_use);
7288 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7291 // C++0x [temp.explicit]p2:
7292 // There are two forms of explicit instantiation: an explicit instantiation
7293 // definition and an explicit instantiation declaration. An explicit
7294 // instantiation declaration begins with the extern keyword. [...]
7295 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
7296 ? TSK_ExplicitInstantiationDefinition
7297 : TSK_ExplicitInstantiationDeclaration;
7299 if (TSK == TSK_ExplicitInstantiationDeclaration) {
7300 // Check for dllexport class template instantiation declarations.
7301 for (AttributeList *A = Attr; A; A = A->getNext()) {
7302 if (A->getKind() == AttributeList::AT_DLLExport) {
7304 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7305 Diag(A->getLoc(), diag::note_attribute);
7310 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
7312 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7313 Diag(A->getLocation(), diag::note_attribute);
7317 // Translate the parser's template argument list in our AST format.
7318 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
7319 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
7321 // Check that the template argument list is well-formed for this
7323 SmallVector<TemplateArgument, 4> Converted;
7324 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7325 TemplateArgs, false, Converted))
7328 // Find the class template specialization declaration that
7329 // corresponds to these arguments.
7330 void *InsertPos = nullptr;
7331 ClassTemplateSpecializationDecl *PrevDecl
7332 = ClassTemplate->findSpecialization(Converted, InsertPos);
7334 TemplateSpecializationKind PrevDecl_TSK
7335 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
7337 // C++0x [temp.explicit]p2:
7338 // [...] An explicit instantiation shall appear in an enclosing
7339 // namespace of its template. [...]
7341 // This is C++ DR 275.
7342 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
7346 ClassTemplateSpecializationDecl *Specialization = nullptr;
7348 bool HasNoEffect = false;
7350 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
7351 PrevDecl, PrevDecl_TSK,
7352 PrevDecl->getPointOfInstantiation(),
7356 // Even though HasNoEffect == true means that this explicit instantiation
7357 // has no effect on semantics, we go on to put its syntax in the AST.
7359 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
7360 PrevDecl_TSK == TSK_Undeclared) {
7361 // Since the only prior class template specialization with these
7362 // arguments was referenced but not declared, reuse that
7363 // declaration node as our own, updating the source location
7364 // for the template name to reflect our new declaration.
7365 // (Other source locations will be updated later.)
7366 Specialization = PrevDecl;
7367 Specialization->setLocation(TemplateNameLoc);
7372 if (!Specialization) {
7373 // Create a new class template specialization declaration node for
7374 // this explicit specialization.
7376 = ClassTemplateSpecializationDecl::Create(Context, Kind,
7377 ClassTemplate->getDeclContext(),
7378 KWLoc, TemplateNameLoc,
7383 SetNestedNameSpecifier(Specialization, SS);
7385 if (!HasNoEffect && !PrevDecl) {
7386 // Insert the new specialization.
7387 ClassTemplate->AddSpecialization(Specialization, InsertPos);
7391 // Build the fully-sugared type for this explicit instantiation as
7392 // the user wrote in the explicit instantiation itself. This means
7393 // that we'll pretty-print the type retrieved from the
7394 // specialization's declaration the way that the user actually wrote
7395 // the explicit instantiation, rather than formatting the name based
7396 // on the "canonical" representation used to store the template
7397 // arguments in the specialization.
7398 TypeSourceInfo *WrittenTy
7399 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7401 Context.getTypeDeclType(Specialization));
7402 Specialization->setTypeAsWritten(WrittenTy);
7404 // Set source locations for keywords.
7405 Specialization->setExternLoc(ExternLoc);
7406 Specialization->setTemplateKeywordLoc(TemplateLoc);
7407 Specialization->setRBraceLoc(SourceLocation());
7410 ProcessDeclAttributeList(S, Specialization, Attr);
7412 // Add the explicit instantiation into its lexical context. However,
7413 // since explicit instantiations are never found by name lookup, we
7414 // just put it into the declaration context directly.
7415 Specialization->setLexicalDeclContext(CurContext);
7416 CurContext->addDecl(Specialization);
7418 // Syntax is now OK, so return if it has no other effect on semantics.
7420 // Set the template specialization kind.
7421 Specialization->setTemplateSpecializationKind(TSK);
7422 return Specialization;
7425 // C++ [temp.explicit]p3:
7426 // A definition of a class template or class member template
7427 // shall be in scope at the point of the explicit instantiation of
7428 // the class template or class member template.
7430 // This check comes when we actually try to perform the
7432 ClassTemplateSpecializationDecl *Def
7433 = cast_or_null<ClassTemplateSpecializationDecl>(
7434 Specialization->getDefinition());
7436 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
7437 else if (TSK == TSK_ExplicitInstantiationDefinition) {
7438 MarkVTableUsed(TemplateNameLoc, Specialization, true);
7439 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
7442 // Instantiate the members of this class template specialization.
7443 Def = cast_or_null<ClassTemplateSpecializationDecl>(
7444 Specialization->getDefinition());
7446 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
7448 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
7449 // TSK_ExplicitInstantiationDefinition
7450 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
7451 TSK == TSK_ExplicitInstantiationDefinition) {
7452 // FIXME: Need to notify the ASTMutationListener that we did this.
7453 Def->setTemplateSpecializationKind(TSK);
7455 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
7456 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7457 // In the MS ABI, an explicit instantiation definition can add a dll
7458 // attribute to a template with a previous instantiation declaration.
7459 // MinGW doesn't allow this.
7460 auto *A = cast<InheritableAttr>(
7461 getDLLAttr(Specialization)->clone(getASTContext()));
7462 A->setInherited(true);
7464 checkClassLevelDLLAttribute(Def);
7466 // Propagate attribute to base class templates.
7467 for (auto &B : Def->bases()) {
7468 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
7469 B.getType()->getAsCXXRecordDecl()))
7470 propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getLocStart());
7475 // Set the template specialization kind. Make sure it is set before
7476 // instantiating the members which will trigger ASTConsumer callbacks.
7477 Specialization->setTemplateSpecializationKind(TSK);
7478 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
7481 // Set the template specialization kind.
7482 Specialization->setTemplateSpecializationKind(TSK);
7485 return Specialization;
7488 // Explicit instantiation of a member class of a class template.
7490 Sema::ActOnExplicitInstantiation(Scope *S,
7491 SourceLocation ExternLoc,
7492 SourceLocation TemplateLoc,
7494 SourceLocation KWLoc,
7496 IdentifierInfo *Name,
7497 SourceLocation NameLoc,
7498 AttributeList *Attr) {
7501 bool IsDependent = false;
7502 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
7503 KWLoc, SS, Name, NameLoc, Attr, AS_none,
7504 /*ModulePrivateLoc=*/SourceLocation(),
7505 MultiTemplateParamsArg(), Owned, IsDependent,
7506 SourceLocation(), false, TypeResult(),
7507 /*IsTypeSpecifier*/false);
7508 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
7513 TagDecl *Tag = cast<TagDecl>(TagD);
7514 assert(!Tag->isEnum() && "shouldn't see enumerations here");
7516 if (Tag->isInvalidDecl())
7519 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
7520 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
7522 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
7523 << Context.getTypeDeclType(Record);
7524 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
7528 // C++0x [temp.explicit]p2:
7529 // If the explicit instantiation is for a class or member class, the
7530 // elaborated-type-specifier in the declaration shall include a
7531 // simple-template-id.
7533 // C++98 has the same restriction, just worded differently.
7534 if (!ScopeSpecifierHasTemplateId(SS))
7535 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
7536 << Record << SS.getRange();
7538 // C++0x [temp.explicit]p2:
7539 // There are two forms of explicit instantiation: an explicit instantiation
7540 // definition and an explicit instantiation declaration. An explicit
7541 // instantiation declaration begins with the extern keyword. [...]
7542 TemplateSpecializationKind TSK
7543 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7544 : TSK_ExplicitInstantiationDeclaration;
7546 // C++0x [temp.explicit]p2:
7547 // [...] An explicit instantiation shall appear in an enclosing
7548 // namespace of its template. [...]
7550 // This is C++ DR 275.
7551 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
7553 // Verify that it is okay to explicitly instantiate here.
7554 CXXRecordDecl *PrevDecl
7555 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
7556 if (!PrevDecl && Record->getDefinition())
7559 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
7560 bool HasNoEffect = false;
7561 assert(MSInfo && "No member specialization information?");
7562 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
7564 MSInfo->getTemplateSpecializationKind(),
7565 MSInfo->getPointOfInstantiation(),
7572 CXXRecordDecl *RecordDef
7573 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
7575 // C++ [temp.explicit]p3:
7576 // A definition of a member class of a class template shall be in scope
7577 // at the point of an explicit instantiation of the member class.
7579 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
7581 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
7582 << 0 << Record->getDeclName() << Record->getDeclContext();
7583 Diag(Pattern->getLocation(), diag::note_forward_declaration)
7587 if (InstantiateClass(NameLoc, Record, Def,
7588 getTemplateInstantiationArgs(Record),
7592 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
7598 // Instantiate all of the members of the class.
7599 InstantiateClassMembers(NameLoc, RecordDef,
7600 getTemplateInstantiationArgs(Record), TSK);
7602 if (TSK == TSK_ExplicitInstantiationDefinition)
7603 MarkVTableUsed(NameLoc, RecordDef, true);
7605 // FIXME: We don't have any representation for explicit instantiations of
7606 // member classes. Such a representation is not needed for compilation, but it
7607 // should be available for clients that want to see all of the declarations in
7612 DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
7613 SourceLocation ExternLoc,
7614 SourceLocation TemplateLoc,
7616 // Explicit instantiations always require a name.
7617 // TODO: check if/when DNInfo should replace Name.
7618 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7619 DeclarationName Name = NameInfo.getName();
7621 if (!D.isInvalidType())
7622 Diag(D.getDeclSpec().getLocStart(),
7623 diag::err_explicit_instantiation_requires_name)
7624 << D.getDeclSpec().getSourceRange()
7625 << D.getSourceRange();
7630 // The scope passed in may not be a decl scope. Zip up the scope tree until
7631 // we find one that is.
7632 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7633 (S->getFlags() & Scope::TemplateParamScope) != 0)
7636 // Determine the type of the declaration.
7637 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
7638 QualType R = T->getType();
7643 // A storage-class-specifier shall not be specified in [...] an explicit
7644 // instantiation (14.7.2) directive.
7645 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
7646 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
7649 } else if (D.getDeclSpec().getStorageClassSpec()
7650 != DeclSpec::SCS_unspecified) {
7651 // Complain about then remove the storage class specifier.
7652 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
7653 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7655 D.getMutableDeclSpec().ClearStorageClassSpecs();
7658 // C++0x [temp.explicit]p1:
7659 // [...] An explicit instantiation of a function template shall not use the
7660 // inline or constexpr specifiers.
7661 // Presumably, this also applies to member functions of class templates as
7663 if (D.getDeclSpec().isInlineSpecified())
7664 Diag(D.getDeclSpec().getInlineSpecLoc(),
7665 getLangOpts().CPlusPlus11 ?
7666 diag::err_explicit_instantiation_inline :
7667 diag::warn_explicit_instantiation_inline_0x)
7668 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7669 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
7670 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
7671 // not already specified.
7672 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7673 diag::err_explicit_instantiation_constexpr);
7675 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7676 // applied only to the definition of a function template or variable template,
7677 // declared in namespace scope.
7678 if (D.getDeclSpec().isConceptSpecified()) {
7679 Diag(D.getDeclSpec().getConceptSpecLoc(),
7680 diag::err_concept_specified_specialization) << 0;
7684 // C++0x [temp.explicit]p2:
7685 // There are two forms of explicit instantiation: an explicit instantiation
7686 // definition and an explicit instantiation declaration. An explicit
7687 // instantiation declaration begins with the extern keyword. [...]
7688 TemplateSpecializationKind TSK
7689 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7690 : TSK_ExplicitInstantiationDeclaration;
7692 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
7693 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
7695 if (!R->isFunctionType()) {
7696 // C++ [temp.explicit]p1:
7697 // A [...] static data member of a class template can be explicitly
7698 // instantiated from the member definition associated with its class
7700 // C++1y [temp.explicit]p1:
7701 // A [...] variable [...] template specialization can be explicitly
7702 // instantiated from its template.
7703 if (Previous.isAmbiguous())
7706 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
7707 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
7709 if (!PrevTemplate) {
7710 if (!Prev || !Prev->isStaticDataMember()) {
7711 // We expect to see a data data member here.
7712 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
7714 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7716 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
7720 if (!Prev->getInstantiatedFromStaticDataMember()) {
7721 // FIXME: Check for explicit specialization?
7722 Diag(D.getIdentifierLoc(),
7723 diag::err_explicit_instantiation_data_member_not_instantiated)
7725 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
7726 // FIXME: Can we provide a note showing where this was declared?
7730 // Explicitly instantiate a variable template.
7732 // C++1y [dcl.spec.auto]p6:
7733 // ... A program that uses auto or decltype(auto) in a context not
7734 // explicitly allowed in this section is ill-formed.
7736 // This includes auto-typed variable template instantiations.
7737 if (R->isUndeducedType()) {
7738 Diag(T->getTypeLoc().getLocStart(),
7739 diag::err_auto_not_allowed_var_inst);
7743 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7744 // C++1y [temp.explicit]p3:
7745 // If the explicit instantiation is for a variable, the unqualified-id
7746 // in the declaration shall be a template-id.
7747 Diag(D.getIdentifierLoc(),
7748 diag::err_explicit_instantiation_without_template_id)
7750 Diag(PrevTemplate->getLocation(),
7751 diag::note_explicit_instantiation_here);
7755 // Translate the parser's template argument list into our AST format.
7756 TemplateArgumentListInfo TemplateArgs =
7757 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
7759 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
7760 D.getIdentifierLoc(), TemplateArgs);
7761 if (Res.isInvalid())
7764 // Ignore access control bits, we don't need them for redeclaration
7766 Prev = cast<VarDecl>(Res.get());
7769 // C++0x [temp.explicit]p2:
7770 // If the explicit instantiation is for a member function, a member class
7771 // or a static data member of a class template specialization, the name of
7772 // the class template specialization in the qualified-id for the member
7773 // name shall be a simple-template-id.
7775 // C++98 has the same restriction, just worded differently.
7777 // This does not apply to variable template specializations, where the
7778 // template-id is in the unqualified-id instead.
7779 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
7780 Diag(D.getIdentifierLoc(),
7781 diag::ext_explicit_instantiation_without_qualified_id)
7782 << Prev << D.getCXXScopeSpec().getRange();
7784 // Check the scope of this explicit instantiation.
7785 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
7787 // Verify that it is okay to explicitly instantiate here.
7788 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
7789 SourceLocation POI = Prev->getPointOfInstantiation();
7790 bool HasNoEffect = false;
7791 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
7792 PrevTSK, POI, HasNoEffect))
7796 // Instantiate static data member or variable template.
7798 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
7800 // Merge attributes.
7801 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
7802 ProcessDeclAttributeList(S, Prev, Attr);
7804 if (TSK == TSK_ExplicitInstantiationDefinition)
7805 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
7808 // Check the new variable specialization against the parsed input.
7809 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
7810 Diag(T->getTypeLoc().getLocStart(),
7811 diag::err_invalid_var_template_spec_type)
7812 << 0 << PrevTemplate << R << Prev->getType();
7813 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
7814 << 2 << PrevTemplate->getDeclName();
7818 // FIXME: Create an ExplicitInstantiation node?
7819 return (Decl*) nullptr;
7822 // If the declarator is a template-id, translate the parser's template
7823 // argument list into our AST format.
7824 bool HasExplicitTemplateArgs = false;
7825 TemplateArgumentListInfo TemplateArgs;
7826 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7827 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
7828 HasExplicitTemplateArgs = true;
7831 // C++ [temp.explicit]p1:
7832 // A [...] function [...] can be explicitly instantiated from its template.
7833 // A member function [...] of a class template can be explicitly
7834 // instantiated from the member definition associated with its class
7836 UnresolvedSet<8> Matches;
7837 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
7838 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7840 NamedDecl *Prev = *P;
7841 if (!HasExplicitTemplateArgs) {
7842 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
7843 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType());
7844 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
7847 Matches.addDecl(Method, P.getAccess());
7848 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
7854 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
7858 TemplateDeductionInfo Info(FailedCandidates.getLocation());
7859 FunctionDecl *Specialization = nullptr;
7860 if (TemplateDeductionResult TDK
7861 = DeduceTemplateArguments(FunTmpl,
7862 (HasExplicitTemplateArgs ? &TemplateArgs
7864 R, Specialization, Info)) {
7865 // Keep track of almost-matches.
7866 FailedCandidates.addCandidate()
7867 .set(FunTmpl->getTemplatedDecl(),
7868 MakeDeductionFailureInfo(Context, TDK, Info));
7873 Matches.addDecl(Specialization, P.getAccess());
7876 // Find the most specialized function template specialization.
7877 UnresolvedSetIterator Result = getMostSpecialized(
7878 Matches.begin(), Matches.end(), FailedCandidates,
7879 D.getIdentifierLoc(),
7880 PDiag(diag::err_explicit_instantiation_not_known) << Name,
7881 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
7882 PDiag(diag::note_explicit_instantiation_candidate));
7884 if (Result == Matches.end())
7887 // Ignore access control bits, we don't need them for redeclaration checking.
7888 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
7890 // C++11 [except.spec]p4
7891 // In an explicit instantiation an exception-specification may be specified,
7892 // but is not required.
7893 // If an exception-specification is specified in an explicit instantiation
7894 // directive, it shall be compatible with the exception-specifications of
7895 // other declarations of that function.
7896 if (auto *FPT = R->getAs<FunctionProtoType>())
7897 if (FPT->hasExceptionSpec()) {
7899 diag::err_mismatched_exception_spec_explicit_instantiation;
7900 if (getLangOpts().MicrosoftExt)
7901 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
7902 bool Result = CheckEquivalentExceptionSpec(
7903 PDiag(DiagID) << Specialization->getType(),
7904 PDiag(diag::note_explicit_instantiation_here),
7905 Specialization->getType()->getAs<FunctionProtoType>(),
7906 Specialization->getLocation(), FPT, D.getLocStart());
7907 // In Microsoft mode, mismatching exception specifications just cause a
7909 if (!getLangOpts().MicrosoftExt && Result)
7913 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
7914 Diag(D.getIdentifierLoc(),
7915 diag::err_explicit_instantiation_member_function_not_instantiated)
7917 << (Specialization->getTemplateSpecializationKind() ==
7918 TSK_ExplicitSpecialization);
7919 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
7923 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
7924 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
7925 PrevDecl = Specialization;
7928 bool HasNoEffect = false;
7929 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
7931 PrevDecl->getTemplateSpecializationKind(),
7932 PrevDecl->getPointOfInstantiation(),
7936 // FIXME: We may still want to build some representation of this
7937 // explicit specialization.
7939 return (Decl*) nullptr;
7942 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
7943 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
7945 ProcessDeclAttributeList(S, Specialization, Attr);
7947 if (Specialization->isDefined()) {
7948 // Let the ASTConsumer know that this function has been explicitly
7949 // instantiated now, and its linkage might have changed.
7950 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
7951 } else if (TSK == TSK_ExplicitInstantiationDefinition)
7952 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
7954 // C++0x [temp.explicit]p2:
7955 // If the explicit instantiation is for a member function, a member class
7956 // or a static data member of a class template specialization, the name of
7957 // the class template specialization in the qualified-id for the member
7958 // name shall be a simple-template-id.
7960 // C++98 has the same restriction, just worded differently.
7961 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
7962 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
7963 D.getCXXScopeSpec().isSet() &&
7964 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
7965 Diag(D.getIdentifierLoc(),
7966 diag::ext_explicit_instantiation_without_qualified_id)
7967 << Specialization << D.getCXXScopeSpec().getRange();
7969 CheckExplicitInstantiationScope(*this,
7970 FunTmpl? (NamedDecl *)FunTmpl
7971 : Specialization->getInstantiatedFromMemberFunction(),
7972 D.getIdentifierLoc(),
7973 D.getCXXScopeSpec().isSet());
7975 // FIXME: Create some kind of ExplicitInstantiationDecl here.
7976 return (Decl*) nullptr;
7980 Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
7981 const CXXScopeSpec &SS, IdentifierInfo *Name,
7982 SourceLocation TagLoc, SourceLocation NameLoc) {
7983 // This has to hold, because SS is expected to be defined.
7984 assert(Name && "Expected a name in a dependent tag");
7986 NestedNameSpecifier *NNS = SS.getScopeRep();
7990 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7992 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
7993 Diag(NameLoc, diag::err_dependent_tag_decl)
7994 << (TUK == TUK_Definition) << Kind << SS.getRange();
7998 // Create the resulting type.
7999 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
8000 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
8002 // Create type-source location information for this type.
8004 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
8005 TL.setElaboratedKeywordLoc(TagLoc);
8006 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8007 TL.setNameLoc(NameLoc);
8008 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
8012 Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
8013 const CXXScopeSpec &SS, const IdentifierInfo &II,
8014 SourceLocation IdLoc) {
8018 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
8020 getLangOpts().CPlusPlus11 ?
8021 diag::warn_cxx98_compat_typename_outside_of_template :
8022 diag::ext_typename_outside_of_template)
8023 << FixItHint::CreateRemoval(TypenameLoc);
8025 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
8026 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
8027 TypenameLoc, QualifierLoc, II, IdLoc);
8031 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
8032 if (isa<DependentNameType>(T)) {
8033 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
8034 TL.setElaboratedKeywordLoc(TypenameLoc);
8035 TL.setQualifierLoc(QualifierLoc);
8036 TL.setNameLoc(IdLoc);
8038 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
8039 TL.setElaboratedKeywordLoc(TypenameLoc);
8040 TL.setQualifierLoc(QualifierLoc);
8041 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
8044 return CreateParsedType(T, TSI);
8048 Sema::ActOnTypenameType(Scope *S,
8049 SourceLocation TypenameLoc,
8050 const CXXScopeSpec &SS,
8051 SourceLocation TemplateKWLoc,
8052 TemplateTy TemplateIn,
8053 SourceLocation TemplateNameLoc,
8054 SourceLocation LAngleLoc,
8055 ASTTemplateArgsPtr TemplateArgsIn,
8056 SourceLocation RAngleLoc) {
8057 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
8059 getLangOpts().CPlusPlus11 ?
8060 diag::warn_cxx98_compat_typename_outside_of_template :
8061 diag::ext_typename_outside_of_template)
8062 << FixItHint::CreateRemoval(TypenameLoc);
8064 // Translate the parser's template argument list in our AST format.
8065 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
8066 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
8068 TemplateName Template = TemplateIn.get();
8069 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
8070 // Construct a dependent template specialization type.
8071 assert(DTN && "dependent template has non-dependent name?");
8072 assert(DTN->getQualifier() == SS.getScopeRep());
8073 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
8074 DTN->getQualifier(),
8075 DTN->getIdentifier(),
8078 // Create source-location information for this type.
8079 TypeLocBuilder Builder;
8080 DependentTemplateSpecializationTypeLoc SpecTL
8081 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
8082 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
8083 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
8084 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
8085 SpecTL.setTemplateNameLoc(TemplateNameLoc);
8086 SpecTL.setLAngleLoc(LAngleLoc);
8087 SpecTL.setRAngleLoc(RAngleLoc);
8088 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8089 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
8090 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
8093 QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
8097 // Provide source-location information for the template specialization type.
8098 TypeLocBuilder Builder;
8099 TemplateSpecializationTypeLoc SpecTL
8100 = Builder.push<TemplateSpecializationTypeLoc>(T);
8101 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
8102 SpecTL.setTemplateNameLoc(TemplateNameLoc);
8103 SpecTL.setLAngleLoc(LAngleLoc);
8104 SpecTL.setRAngleLoc(RAngleLoc);
8105 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8106 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
8108 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
8109 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
8110 TL.setElaboratedKeywordLoc(TypenameLoc);
8111 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8113 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
8114 return CreateParsedType(T, TSI);
8118 /// Determine whether this failed name lookup should be treated as being
8119 /// disabled by a usage of std::enable_if.
8120 static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
8121 SourceRange &CondRange) {
8122 // We must be looking for a ::type...
8123 if (!II.isStr("type"))
8126 // ... within an explicitly-written template specialization...
8127 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
8129 TypeLoc EnableIfTy = NNS.getTypeLoc();
8130 TemplateSpecializationTypeLoc EnableIfTSTLoc =
8131 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
8132 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
8134 const TemplateSpecializationType *EnableIfTST =
8135 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
8137 // ... which names a complete class template declaration...
8138 const TemplateDecl *EnableIfDecl =
8139 EnableIfTST->getTemplateName().getAsTemplateDecl();
8140 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
8143 // ... called "enable_if".
8144 const IdentifierInfo *EnableIfII =
8145 EnableIfDecl->getDeclName().getAsIdentifierInfo();
8146 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
8149 // Assume the first template argument is the condition.
8150 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
8154 /// \brief Build the type that describes a C++ typename specifier,
8155 /// e.g., "typename T::type".
8157 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
8158 SourceLocation KeywordLoc,
8159 NestedNameSpecifierLoc QualifierLoc,
8160 const IdentifierInfo &II,
8161 SourceLocation IILoc) {
8163 SS.Adopt(QualifierLoc);
8165 DeclContext *Ctx = computeDeclContext(SS);
8167 // If the nested-name-specifier is dependent and couldn't be
8168 // resolved to a type, build a typename type.
8169 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
8170 return Context.getDependentNameType(Keyword,
8171 QualifierLoc.getNestedNameSpecifier(),
8175 // If the nested-name-specifier refers to the current instantiation,
8176 // the "typename" keyword itself is superfluous. In C++03, the
8177 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
8178 // allows such extraneous "typename" keywords, and we retroactively
8179 // apply this DR to C++03 code with only a warning. In any case we continue.
8181 if (RequireCompleteDeclContext(SS, Ctx))
8184 DeclarationName Name(&II);
8185 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
8186 LookupQualifiedName(Result, Ctx, SS);
8187 unsigned DiagID = 0;
8188 Decl *Referenced = nullptr;
8189 switch (Result.getResultKind()) {
8190 case LookupResult::NotFound: {
8191 // If we're looking up 'type' within a template named 'enable_if', produce
8192 // a more specific diagnostic.
8193 SourceRange CondRange;
8194 if (isEnableIf(QualifierLoc, II, CondRange)) {
8195 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
8196 << Ctx << CondRange;
8200 DiagID = diag::err_typename_nested_not_found;
8204 case LookupResult::FoundUnresolvedValue: {
8205 // We found a using declaration that is a value. Most likely, the using
8206 // declaration itself is meant to have the 'typename' keyword.
8207 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
8209 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
8210 << Name << Ctx << FullRange;
8211 if (UnresolvedUsingValueDecl *Using
8212 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
8213 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
8214 Diag(Loc, diag::note_using_value_decl_missing_typename)
8215 << FixItHint::CreateInsertion(Loc, "typename ");
8218 // Fall through to create a dependent typename type, from which we can recover
8221 case LookupResult::NotFoundInCurrentInstantiation:
8222 // Okay, it's a member of an unknown instantiation.
8223 return Context.getDependentNameType(Keyword,
8224 QualifierLoc.getNestedNameSpecifier(),
8227 case LookupResult::Found:
8228 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
8229 // We found a type. Build an ElaboratedType, since the
8230 // typename-specifier was just sugar.
8231 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
8232 return Context.getElaboratedType(ETK_Typename,
8233 QualifierLoc.getNestedNameSpecifier(),
8234 Context.getTypeDeclType(Type));
8237 DiagID = diag::err_typename_nested_not_type;
8238 Referenced = Result.getFoundDecl();
8241 case LookupResult::FoundOverloaded:
8242 DiagID = diag::err_typename_nested_not_type;
8243 Referenced = *Result.begin();
8246 case LookupResult::Ambiguous:
8250 // If we get here, it's because name lookup did not find a
8251 // type. Emit an appropriate diagnostic and return an error.
8252 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
8254 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
8256 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
8262 // See Sema::RebuildTypeInCurrentInstantiation
8263 class CurrentInstantiationRebuilder
8264 : public TreeTransform<CurrentInstantiationRebuilder> {
8266 DeclarationName Entity;
8269 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
8271 CurrentInstantiationRebuilder(Sema &SemaRef,
8273 DeclarationName Entity)
8274 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
8275 Loc(Loc), Entity(Entity) { }
8277 /// \brief Determine whether the given type \p T has already been
8280 /// For the purposes of type reconstruction, a type has already been
8281 /// transformed if it is NULL or if it is not dependent.
8282 bool AlreadyTransformed(QualType T) {
8283 return T.isNull() || !T->isDependentType();
8286 /// \brief Returns the location of the entity whose type is being
8288 SourceLocation getBaseLocation() { return Loc; }
8290 /// \brief Returns the name of the entity whose type is being rebuilt.
8291 DeclarationName getBaseEntity() { return Entity; }
8293 /// \brief Sets the "base" location and entity when that
8294 /// information is known based on another transformation.
8295 void setBase(SourceLocation Loc, DeclarationName Entity) {
8297 this->Entity = Entity;
8300 ExprResult TransformLambdaExpr(LambdaExpr *E) {
8301 // Lambdas never need to be transformed.
8305 } // end anonymous namespace
8307 /// \brief Rebuilds a type within the context of the current instantiation.
8309 /// The type \p T is part of the type of an out-of-line member definition of
8310 /// a class template (or class template partial specialization) that was parsed
8311 /// and constructed before we entered the scope of the class template (or
8312 /// partial specialization thereof). This routine will rebuild that type now
8313 /// that we have entered the declarator's scope, which may produce different
8314 /// canonical types, e.g.,
8317 /// template<typename T>
8319 /// typedef T* pointer;
8323 /// template<typename T>
8324 /// typename X<T>::pointer X<T>::data() { ... }
8327 /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
8328 /// since we do not know that we can look into X<T> when we parsed the type.
8329 /// This function will rebuild the type, performing the lookup of "pointer"
8330 /// in X<T> and returning an ElaboratedType whose canonical type is the same
8331 /// as the canonical type of T*, allowing the return types of the out-of-line
8332 /// definition and the declaration to match.
8333 TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
8335 DeclarationName Name) {
8336 if (!T || !T->getType()->isDependentType())
8339 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
8340 return Rebuilder.TransformType(T);
8343 ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
8344 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
8346 return Rebuilder.TransformExpr(E);
8349 bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
8353 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
8354 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
8356 NestedNameSpecifierLoc Rebuilt
8357 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
8365 /// \brief Rebuild the template parameters now that we know we're in a current
8367 bool Sema::RebuildTemplateParamsInCurrentInstantiation(
8368 TemplateParameterList *Params) {
8369 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8370 Decl *Param = Params->getParam(I);
8372 // There is nothing to rebuild in a type parameter.
8373 if (isa<TemplateTypeParmDecl>(Param))
8376 // Rebuild the template parameter list of a template template parameter.
8377 if (TemplateTemplateParmDecl *TTP
8378 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
8379 if (RebuildTemplateParamsInCurrentInstantiation(
8380 TTP->getTemplateParameters()))
8386 // Rebuild the type of a non-type template parameter.
8387 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
8388 TypeSourceInfo *NewTSI
8389 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
8390 NTTP->getLocation(),
8391 NTTP->getDeclName());
8395 if (NewTSI != NTTP->getTypeSourceInfo()) {
8396 NTTP->setTypeSourceInfo(NewTSI);
8397 NTTP->setType(NewTSI->getType());
8404 /// \brief Produces a formatted string that describes the binding of
8405 /// template parameters to template arguments.
8407 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8408 const TemplateArgumentList &Args) {
8409 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
8413 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8414 const TemplateArgument *Args,
8416 SmallString<128> Str;
8417 llvm::raw_svector_ostream Out(Str);
8419 if (!Params || Params->size() == 0 || NumArgs == 0)
8420 return std::string();
8422 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8431 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
8432 Out << Id->getName();
8438 Args[I].print(getPrintingPolicy(), Out);
8445 void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
8446 CachedTokens &Toks) {
8450 LateParsedTemplate *LPT = new LateParsedTemplate;
8452 // Take tokens to avoid allocations
8453 LPT->Toks.swap(Toks);
8455 LateParsedTemplateMap.insert(std::make_pair(FD, LPT));
8457 FD->setLateTemplateParsed(true);
8460 void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
8463 FD->setLateTemplateParsed(false);
8466 bool Sema::IsInsideALocalClassWithinATemplateFunction() {
8467 DeclContext *DC = CurContext;
8470 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
8471 const FunctionDecl *FD = RD->isLocalClass();
8472 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
8473 } else if (DC->isTranslationUnit() || DC->isNamespace())
8476 DC = DC->getParent();