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/LangOptions.h"
22 #include "clang/Basic/PartialDiagnostic.h"
23 #include "clang/Basic/TargetInfo.h"
24 #include "clang/Sema/DeclSpec.h"
25 #include "clang/Sema/Lookup.h"
26 #include "clang/Sema/ParsedTemplate.h"
27 #include "clang/Sema/Scope.h"
28 #include "clang/Sema/SemaInternal.h"
29 #include "clang/Sema/Template.h"
30 #include "clang/Sema/TemplateDeduction.h"
31 #include "llvm/ADT/SmallBitVector.h"
32 #include "llvm/ADT/SmallString.h"
33 #include "llvm/ADT/StringExtras.h"
34 using namespace clang;
37 // Exported for use by Parser.
39 clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
41 if (!N) return SourceRange();
42 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
45 /// \brief Determine whether the declaration found is acceptable as the name
46 /// of a template and, if so, return that template declaration. Otherwise,
48 static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
50 bool AllowFunctionTemplates) {
51 NamedDecl *D = Orig->getUnderlyingDecl();
53 if (isa<TemplateDecl>(D)) {
54 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
60 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
61 // C++ [temp.local]p1:
62 // Like normal (non-template) classes, class templates have an
63 // injected-class-name (Clause 9). The injected-class-name
64 // can be used with or without a template-argument-list. When
65 // it is used without a template-argument-list, it is
66 // equivalent to the injected-class-name followed by the
67 // template-parameters of the class template enclosed in
68 // <>. When it is used with a template-argument-list, it
69 // refers to the specified class template specialization,
70 // which could be the current specialization or another
72 if (Record->isInjectedClassName()) {
73 Record = cast<CXXRecordDecl>(Record->getDeclContext());
74 if (Record->getDescribedClassTemplate())
75 return Record->getDescribedClassTemplate();
77 if (ClassTemplateSpecializationDecl *Spec
78 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
79 return Spec->getSpecializedTemplate();
88 void Sema::FilterAcceptableTemplateNames(LookupResult &R,
89 bool AllowFunctionTemplates) {
90 // The set of class templates we've already seen.
91 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
92 LookupResult::Filter filter = R.makeFilter();
93 while (filter.hasNext()) {
94 NamedDecl *Orig = filter.next();
95 NamedDecl *Repl = isAcceptableTemplateName(Context, Orig,
96 AllowFunctionTemplates);
99 else if (Repl != Orig) {
101 // C++ [temp.local]p3:
102 // A lookup that finds an injected-class-name (10.2) can result in an
103 // ambiguity in certain cases (for example, if it is found in more than
104 // one base class). If all of the injected-class-names that are found
105 // refer to specializations of the same class template, and if the name
106 // is used as a template-name, the reference refers to the class
107 // template itself and not a specialization thereof, and is not
109 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
110 if (!ClassTemplates.insert(ClassTmpl).second) {
115 // FIXME: we promote access to public here as a workaround to
116 // the fact that LookupResult doesn't let us remember that we
117 // found this template through a particular injected class name,
118 // which means we end up doing nasty things to the invariants.
119 // Pretending that access is public is *much* safer.
120 filter.replace(Repl, AS_public);
126 bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
127 bool AllowFunctionTemplates) {
128 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
129 if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
135 TemplateNameKind Sema::isTemplateName(Scope *S,
137 bool hasTemplateKeyword,
139 ParsedType ObjectTypePtr,
140 bool EnteringContext,
141 TemplateTy &TemplateResult,
142 bool &MemberOfUnknownSpecialization) {
143 assert(getLangOpts().CPlusPlus && "No template names in C!");
145 DeclarationName TName;
146 MemberOfUnknownSpecialization = false;
148 switch (Name.getKind()) {
149 case UnqualifiedId::IK_Identifier:
150 TName = DeclarationName(Name.Identifier);
153 case UnqualifiedId::IK_OperatorFunctionId:
154 TName = Context.DeclarationNames.getCXXOperatorName(
155 Name.OperatorFunctionId.Operator);
158 case UnqualifiedId::IK_LiteralOperatorId:
159 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
163 return TNK_Non_template;
166 QualType ObjectType = ObjectTypePtr.get();
168 LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
169 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
170 MemberOfUnknownSpecialization);
171 if (R.empty()) return TNK_Non_template;
172 if (R.isAmbiguous()) {
173 // Suppress diagnostics; we'll redo this lookup later.
174 R.suppressDiagnostics();
176 // FIXME: we might have ambiguous templates, in which case we
177 // should at least parse them properly!
178 return TNK_Non_template;
181 TemplateName Template;
182 TemplateNameKind TemplateKind;
184 unsigned ResultCount = R.end() - R.begin();
185 if (ResultCount > 1) {
186 // We assume that we'll preserve the qualifier from a function
187 // template name in other ways.
188 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
189 TemplateKind = TNK_Function_template;
191 // We'll do this lookup again later.
192 R.suppressDiagnostics();
194 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
196 if (SS.isSet() && !SS.isInvalid()) {
197 NestedNameSpecifier *Qualifier = SS.getScopeRep();
198 Template = Context.getQualifiedTemplateName(Qualifier,
199 hasTemplateKeyword, TD);
201 Template = TemplateName(TD);
204 if (isa<FunctionTemplateDecl>(TD)) {
205 TemplateKind = TNK_Function_template;
207 // We'll do this lookup again later.
208 R.suppressDiagnostics();
210 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
211 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD));
213 isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template;
217 TemplateResult = TemplateTy::make(Template);
221 bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
222 SourceLocation IILoc,
224 const CXXScopeSpec *SS,
225 TemplateTy &SuggestedTemplate,
226 TemplateNameKind &SuggestedKind) {
227 // We can't recover unless there's a dependent scope specifier preceding the
229 // FIXME: Typo correction?
230 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
231 computeDeclContext(*SS))
234 // The code is missing a 'template' keyword prior to the dependent template
236 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
237 Diag(IILoc, diag::err_template_kw_missing)
238 << Qualifier << II.getName()
239 << FixItHint::CreateInsertion(IILoc, "template ");
241 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
242 SuggestedKind = TNK_Dependent_template_name;
246 void Sema::LookupTemplateName(LookupResult &Found,
247 Scope *S, CXXScopeSpec &SS,
249 bool EnteringContext,
250 bool &MemberOfUnknownSpecialization) {
251 // Determine where to perform name lookup
252 MemberOfUnknownSpecialization = false;
253 DeclContext *LookupCtx = nullptr;
254 bool isDependent = false;
255 if (!ObjectType.isNull()) {
256 // This nested-name-specifier occurs in a member access expression, e.g.,
257 // x->B::f, and we are looking into the type of the object.
258 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
259 LookupCtx = computeDeclContext(ObjectType);
260 isDependent = ObjectType->isDependentType();
261 assert((isDependent || !ObjectType->isIncompleteType() ||
262 ObjectType->castAs<TagType>()->isBeingDefined()) &&
263 "Caller should have completed object type");
265 // Template names cannot appear inside an Objective-C class or object type.
266 if (ObjectType->isObjCObjectOrInterfaceType()) {
270 } else if (SS.isSet()) {
271 // This nested-name-specifier occurs after another nested-name-specifier,
272 // so long into the context associated with the prior nested-name-specifier.
273 LookupCtx = computeDeclContext(SS, EnteringContext);
274 isDependent = isDependentScopeSpecifier(SS);
276 // The declaration context must be complete.
277 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
281 bool ObjectTypeSearchedInScope = false;
282 bool AllowFunctionTemplatesInLookup = true;
284 // Perform "qualified" name lookup into the declaration context we
285 // computed, which is either the type of the base of a member access
286 // expression or the declaration context associated with a prior
287 // nested-name-specifier.
288 LookupQualifiedName(Found, LookupCtx);
289 if (!ObjectType.isNull() && Found.empty()) {
290 // C++ [basic.lookup.classref]p1:
291 // In a class member access expression (5.2.5), if the . or -> token is
292 // immediately followed by an identifier followed by a <, the
293 // identifier must be looked up to determine whether the < is the
294 // beginning of a template argument list (14.2) or a less-than operator.
295 // The identifier is first looked up in the class of the object
296 // expression. If the identifier is not found, it is then looked up in
297 // the context of the entire postfix-expression and shall name a class
298 // or function template.
299 if (S) LookupName(Found, S);
300 ObjectTypeSearchedInScope = true;
301 AllowFunctionTemplatesInLookup = false;
303 } else if (isDependent && (!S || ObjectType.isNull())) {
304 // We cannot look into a dependent object type or nested nme
306 MemberOfUnknownSpecialization = true;
309 // Perform unqualified name lookup in the current scope.
310 LookupName(Found, S);
312 if (!ObjectType.isNull())
313 AllowFunctionTemplatesInLookup = false;
316 if (Found.empty() && !isDependent) {
317 // If we did not find any names, attempt to correct any typos.
318 DeclarationName Name = Found.getLookupName();
320 // Simple filter callback that, for keywords, only accepts the C++ *_cast
321 auto FilterCCC = llvm::make_unique<CorrectionCandidateCallback>();
322 FilterCCC->WantTypeSpecifiers = false;
323 FilterCCC->WantExpressionKeywords = false;
324 FilterCCC->WantRemainingKeywords = false;
325 FilterCCC->WantCXXNamedCasts = true;
326 if (TypoCorrection Corrected = CorrectTypo(
327 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS,
328 std::move(FilterCCC), CTK_ErrorRecovery, LookupCtx)) {
329 Found.setLookupName(Corrected.getCorrection());
330 if (Corrected.getCorrectionDecl())
331 Found.addDecl(Corrected.getCorrectionDecl());
332 FilterAcceptableTemplateNames(Found);
333 if (!Found.empty()) {
335 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
336 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
337 Name.getAsString() == CorrectedStr;
338 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
339 << Name << LookupCtx << DroppedSpecifier
342 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
346 Found.setLookupName(Name);
350 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
353 MemberOfUnknownSpecialization = true;
357 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
358 !getLangOpts().CPlusPlus11) {
359 // C++03 [basic.lookup.classref]p1:
360 // [...] If the lookup in the class of the object expression finds a
361 // template, the name is also looked up in the context of the entire
362 // postfix-expression and [...]
364 // Note: C++11 does not perform this second lookup.
365 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
367 LookupName(FoundOuter, S);
368 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
370 if (FoundOuter.empty()) {
371 // - if the name is not found, the name found in the class of the
372 // object expression is used, otherwise
373 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
374 FoundOuter.isAmbiguous()) {
375 // - if the name is found in the context of the entire
376 // postfix-expression and does not name a class template, the name
377 // found in the class of the object expression is used, otherwise
379 } else if (!Found.isSuppressingDiagnostics()) {
380 // - if the name found is a class template, it must refer to the same
381 // entity as the one found in the class of the object expression,
382 // otherwise the program is ill-formed.
383 if (!Found.isSingleResult() ||
384 Found.getFoundDecl()->getCanonicalDecl()
385 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
386 Diag(Found.getNameLoc(),
387 diag::ext_nested_name_member_ref_lookup_ambiguous)
388 << Found.getLookupName()
390 Diag(Found.getRepresentativeDecl()->getLocation(),
391 diag::note_ambig_member_ref_object_type)
393 Diag(FoundOuter.getFoundDecl()->getLocation(),
394 diag::note_ambig_member_ref_scope);
396 // Recover by taking the template that we found in the object
397 // expression's type.
403 /// ActOnDependentIdExpression - Handle a dependent id-expression that
404 /// was just parsed. This is only possible with an explicit scope
405 /// specifier naming a dependent type.
407 Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
408 SourceLocation TemplateKWLoc,
409 const DeclarationNameInfo &NameInfo,
410 bool isAddressOfOperand,
411 const TemplateArgumentListInfo *TemplateArgs) {
412 DeclContext *DC = getFunctionLevelDeclContext();
414 if (!isAddressOfOperand &&
415 isa<CXXMethodDecl>(DC) &&
416 cast<CXXMethodDecl>(DC)->isInstance()) {
417 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
419 // Since the 'this' expression is synthesized, we don't need to
420 // perform the double-lookup check.
421 NamedDecl *FirstQualifierInScope = nullptr;
423 return CXXDependentScopeMemberExpr::Create(
424 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
425 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
426 FirstQualifierInScope, NameInfo, TemplateArgs);
429 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
433 Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
434 SourceLocation TemplateKWLoc,
435 const DeclarationNameInfo &NameInfo,
436 const TemplateArgumentListInfo *TemplateArgs) {
437 return DependentScopeDeclRefExpr::Create(
438 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
442 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
443 /// that the template parameter 'PrevDecl' is being shadowed by a new
444 /// declaration at location Loc. Returns true to indicate that this is
445 /// an error, and false otherwise.
446 void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
447 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
449 // Microsoft Visual C++ permits template parameters to be shadowed.
450 if (getLangOpts().MicrosoftExt)
453 // C++ [temp.local]p4:
454 // A template-parameter shall not be redeclared within its
455 // scope (including nested scopes).
456 Diag(Loc, diag::err_template_param_shadow)
457 << cast<NamedDecl>(PrevDecl)->getDeclName();
458 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
462 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
463 /// the parameter D to reference the templated declaration and return a pointer
464 /// to the template declaration. Otherwise, do nothing to D and return null.
465 TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
466 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
467 D = Temp->getTemplatedDecl();
473 ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
474 SourceLocation EllipsisLoc) const {
475 assert(Kind == Template &&
476 "Only template template arguments can be pack expansions here");
477 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
478 "Template template argument pack expansion without packs");
479 ParsedTemplateArgument Result(*this);
480 Result.EllipsisLoc = EllipsisLoc;
484 static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
485 const ParsedTemplateArgument &Arg) {
487 switch (Arg.getKind()) {
488 case ParsedTemplateArgument::Type: {
490 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
492 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
493 return TemplateArgumentLoc(TemplateArgument(T), DI);
496 case ParsedTemplateArgument::NonType: {
497 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
498 return TemplateArgumentLoc(TemplateArgument(E), E);
501 case ParsedTemplateArgument::Template: {
502 TemplateName Template = Arg.getAsTemplate().get();
503 TemplateArgument TArg;
504 if (Arg.getEllipsisLoc().isValid())
505 TArg = TemplateArgument(Template, Optional<unsigned int>());
508 return TemplateArgumentLoc(TArg,
509 Arg.getScopeSpec().getWithLocInContext(
512 Arg.getEllipsisLoc());
516 llvm_unreachable("Unhandled parsed template argument");
519 /// \brief Translates template arguments as provided by the parser
520 /// into template arguments used by semantic analysis.
521 void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
522 TemplateArgumentListInfo &TemplateArgs) {
523 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
524 TemplateArgs.addArgument(translateTemplateArgument(*this,
528 static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
530 IdentifierInfo *Name) {
531 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
532 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration);
533 if (PrevDecl && PrevDecl->isTemplateParameter())
534 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
537 /// ActOnTypeParameter - Called when a C++ template type parameter
538 /// (e.g., "typename T") has been parsed. Typename specifies whether
539 /// the keyword "typename" was used to declare the type parameter
540 /// (otherwise, "class" was used), and KeyLoc is the location of the
541 /// "class" or "typename" keyword. ParamName is the name of the
542 /// parameter (NULL indicates an unnamed template parameter) and
543 /// ParamNameLoc is the location of the parameter name (if any).
544 /// If the type parameter has a default argument, it will be added
545 /// later via ActOnTypeParameterDefault.
546 Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
547 SourceLocation EllipsisLoc,
548 SourceLocation KeyLoc,
549 IdentifierInfo *ParamName,
550 SourceLocation ParamNameLoc,
551 unsigned Depth, unsigned Position,
552 SourceLocation EqualLoc,
553 ParsedType DefaultArg) {
554 assert(S->isTemplateParamScope() &&
555 "Template type parameter not in template parameter scope!");
556 bool Invalid = false;
558 SourceLocation Loc = ParamNameLoc;
562 bool IsParameterPack = EllipsisLoc.isValid();
563 TemplateTypeParmDecl *Param
564 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
565 KeyLoc, Loc, Depth, Position, ParamName,
566 Typename, IsParameterPack);
567 Param->setAccess(AS_public);
569 Param->setInvalidDecl();
572 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
574 // Add the template parameter into the current scope.
576 IdResolver.AddDecl(Param);
579 // C++0x [temp.param]p9:
580 // A default template-argument may be specified for any kind of
581 // template-parameter that is not a template parameter pack.
582 if (DefaultArg && IsParameterPack) {
583 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
584 DefaultArg = ParsedType();
587 // Handle the default argument, if provided.
589 TypeSourceInfo *DefaultTInfo;
590 GetTypeFromParser(DefaultArg, &DefaultTInfo);
592 assert(DefaultTInfo && "expected source information for type");
594 // Check for unexpanded parameter packs.
595 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
596 UPPC_DefaultArgument))
599 // Check the template argument itself.
600 if (CheckTemplateArgument(Param, DefaultTInfo)) {
601 Param->setInvalidDecl();
605 Param->setDefaultArgument(DefaultTInfo);
611 /// \brief Check that the type of a non-type template parameter is
614 /// \returns the (possibly-promoted) parameter type if valid;
615 /// otherwise, produces a diagnostic and returns a NULL type.
617 Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
618 // We don't allow variably-modified types as the type of non-type template
620 if (T->isVariablyModifiedType()) {
621 Diag(Loc, diag::err_variably_modified_nontype_template_param)
626 // C++ [temp.param]p4:
628 // A non-type template-parameter shall have one of the following
629 // (optionally cv-qualified) types:
631 // -- integral or enumeration type,
632 if (T->isIntegralOrEnumerationType() ||
633 // -- pointer to object or pointer to function,
634 T->isPointerType() ||
635 // -- reference to object or reference to function,
636 T->isReferenceType() ||
637 // -- pointer to member,
638 T->isMemberPointerType() ||
639 // -- std::nullptr_t.
640 T->isNullPtrType() ||
641 // If T is a dependent type, we can't do the check now, so we
642 // assume that it is well-formed.
643 T->isDependentType()) {
644 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
645 // are ignored when determining its type.
646 return T.getUnqualifiedType();
649 // C++ [temp.param]p8:
651 // A non-type template-parameter of type "array of T" or
652 // "function returning T" is adjusted to be of type "pointer to
653 // T" or "pointer to function returning T", respectively.
654 else if (T->isArrayType() || T->isFunctionType())
655 return Context.getDecayedType(T);
657 Diag(Loc, diag::err_template_nontype_parm_bad_type)
663 Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
666 SourceLocation EqualLoc,
668 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
669 QualType T = TInfo->getType();
671 assert(S->isTemplateParamScope() &&
672 "Non-type template parameter not in template parameter scope!");
673 bool Invalid = false;
675 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
677 T = Context.IntTy; // Recover with an 'int' type.
681 IdentifierInfo *ParamName = D.getIdentifier();
682 bool IsParameterPack = D.hasEllipsis();
683 NonTypeTemplateParmDecl *Param
684 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
686 D.getIdentifierLoc(),
687 Depth, Position, ParamName, T,
688 IsParameterPack, TInfo);
689 Param->setAccess(AS_public);
692 Param->setInvalidDecl();
695 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
698 // Add the template parameter into the current scope.
700 IdResolver.AddDecl(Param);
703 // C++0x [temp.param]p9:
704 // A default template-argument may be specified for any kind of
705 // template-parameter that is not a template parameter pack.
706 if (Default && IsParameterPack) {
707 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
711 // Check the well-formedness of the default template argument, if provided.
713 // Check for unexpanded parameter packs.
714 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
717 TemplateArgument Converted;
718 ExprResult DefaultRes =
719 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
720 if (DefaultRes.isInvalid()) {
721 Param->setInvalidDecl();
724 Default = DefaultRes.get();
726 Param->setDefaultArgument(Default);
732 /// ActOnTemplateTemplateParameter - Called when a C++ template template
733 /// parameter (e.g. T in template <template \<typename> class T> class array)
734 /// has been parsed. S is the current scope.
735 Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
736 SourceLocation TmpLoc,
737 TemplateParameterList *Params,
738 SourceLocation EllipsisLoc,
739 IdentifierInfo *Name,
740 SourceLocation NameLoc,
743 SourceLocation EqualLoc,
744 ParsedTemplateArgument Default) {
745 assert(S->isTemplateParamScope() &&
746 "Template template parameter not in template parameter scope!");
748 // Construct the parameter object.
749 bool IsParameterPack = EllipsisLoc.isValid();
750 TemplateTemplateParmDecl *Param =
751 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
752 NameLoc.isInvalid()? TmpLoc : NameLoc,
753 Depth, Position, IsParameterPack,
755 Param->setAccess(AS_public);
757 // If the template template parameter has a name, then link the identifier
758 // into the scope and lookup mechanisms.
760 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
763 IdResolver.AddDecl(Param);
766 if (Params->size() == 0) {
767 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
768 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
769 Param->setInvalidDecl();
772 // C++0x [temp.param]p9:
773 // A default template-argument may be specified for any kind of
774 // template-parameter that is not a template parameter pack.
775 if (IsParameterPack && !Default.isInvalid()) {
776 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
777 Default = ParsedTemplateArgument();
780 if (!Default.isInvalid()) {
781 // Check only that we have a template template argument. We don't want to
782 // try to check well-formedness now, because our template template parameter
783 // might have dependent types in its template parameters, which we wouldn't
784 // be able to match now.
786 // If none of the template template parameter's template arguments mention
787 // other template parameters, we could actually perform more checking here.
788 // However, it isn't worth doing.
789 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
790 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
791 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
792 << DefaultArg.getSourceRange();
796 // Check for unexpanded parameter packs.
797 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
798 DefaultArg.getArgument().getAsTemplate(),
799 UPPC_DefaultArgument))
802 Param->setDefaultArgument(Context, DefaultArg);
808 /// ActOnTemplateParameterList - Builds a TemplateParameterList that
809 /// contains the template parameters in Params/NumParams.
810 TemplateParameterList *
811 Sema::ActOnTemplateParameterList(unsigned Depth,
812 SourceLocation ExportLoc,
813 SourceLocation TemplateLoc,
814 SourceLocation LAngleLoc,
815 Decl **Params, unsigned NumParams,
816 SourceLocation RAngleLoc) {
817 if (ExportLoc.isValid())
818 Diag(ExportLoc, diag::warn_template_export_unsupported);
820 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
821 (NamedDecl**)Params, NumParams,
825 static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
827 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
831 Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
832 SourceLocation KWLoc, CXXScopeSpec &SS,
833 IdentifierInfo *Name, SourceLocation NameLoc,
835 TemplateParameterList *TemplateParams,
836 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
837 SourceLocation FriendLoc,
838 unsigned NumOuterTemplateParamLists,
839 TemplateParameterList** OuterTemplateParamLists,
840 SkipBodyInfo *SkipBody) {
841 assert(TemplateParams && TemplateParams->size() > 0 &&
842 "No template parameters");
843 assert(TUK != TUK_Reference && "Can only declare or define class templates");
844 bool Invalid = false;
846 // Check that we can declare a template here.
847 if (CheckTemplateDeclScope(S, TemplateParams))
850 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
851 assert(Kind != TTK_Enum && "can't build template of enumerated type");
853 // There is no such thing as an unnamed class template.
855 Diag(KWLoc, diag::err_template_unnamed_class);
859 // Find any previous declaration with this name. For a friend with no
860 // scope explicitly specified, we only look for tag declarations (per
861 // C++11 [basic.lookup.elab]p2).
862 DeclContext *SemanticContext;
863 LookupResult Previous(*this, Name, NameLoc,
864 (SS.isEmpty() && TUK == TUK_Friend)
865 ? LookupTagName : LookupOrdinaryName,
867 if (SS.isNotEmpty() && !SS.isInvalid()) {
868 SemanticContext = computeDeclContext(SS, true);
869 if (!SemanticContext) {
870 // FIXME: Horrible, horrible hack! We can't currently represent this
871 // in the AST, and historically we have just ignored such friend
872 // class templates, so don't complain here.
873 Diag(NameLoc, TUK == TUK_Friend
874 ? diag::warn_template_qualified_friend_ignored
875 : diag::err_template_qualified_declarator_no_match)
876 << SS.getScopeRep() << SS.getRange();
877 return TUK != TUK_Friend;
880 if (RequireCompleteDeclContext(SS, SemanticContext))
883 // If we're adding a template to a dependent context, we may need to
884 // rebuilding some of the types used within the template parameter list,
885 // now that we know what the current instantiation is.
886 if (SemanticContext->isDependentContext()) {
887 ContextRAII SavedContext(*this, SemanticContext);
888 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
890 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
891 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
893 LookupQualifiedName(Previous, SemanticContext);
895 SemanticContext = CurContext;
897 // C++14 [class.mem]p14:
898 // If T is the name of a class, then each of the following shall have a
899 // name different from T:
900 // -- every member template of class T
901 if (TUK != TUK_Friend &&
902 DiagnoseClassNameShadow(SemanticContext,
903 DeclarationNameInfo(Name, NameLoc)))
906 LookupName(Previous, S);
909 if (Previous.isAmbiguous())
912 NamedDecl *PrevDecl = nullptr;
913 if (Previous.begin() != Previous.end())
914 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
916 // If there is a previous declaration with the same name, check
917 // whether this is a valid redeclaration.
918 ClassTemplateDecl *PrevClassTemplate
919 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
921 // We may have found the injected-class-name of a class template,
922 // class template partial specialization, or class template specialization.
923 // In these cases, grab the template that is being defined or specialized.
924 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
925 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
926 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
928 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
929 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
931 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
932 ->getSpecializedTemplate();
936 if (TUK == TUK_Friend) {
937 // C++ [namespace.memdef]p3:
938 // [...] When looking for a prior declaration of a class or a function
939 // declared as a friend, and when the name of the friend class or
940 // function is neither a qualified name nor a template-id, scopes outside
941 // the innermost enclosing namespace scope are not considered.
943 DeclContext *OutermostContext = CurContext;
944 while (!OutermostContext->isFileContext())
945 OutermostContext = OutermostContext->getLookupParent();
948 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
949 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
950 SemanticContext = PrevDecl->getDeclContext();
952 // Declarations in outer scopes don't matter. However, the outermost
953 // context we computed is the semantic context for our new
955 PrevDecl = PrevClassTemplate = nullptr;
956 SemanticContext = OutermostContext;
958 // Check that the chosen semantic context doesn't already contain a
959 // declaration of this name as a non-tag type.
960 Previous.clear(LookupOrdinaryName);
961 DeclContext *LookupContext = SemanticContext;
962 while (LookupContext->isTransparentContext())
963 LookupContext = LookupContext->getLookupParent();
964 LookupQualifiedName(Previous, LookupContext);
966 if (Previous.isAmbiguous())
969 if (Previous.begin() != Previous.end())
970 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
973 } else if (PrevDecl &&
974 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
976 PrevDecl = PrevClassTemplate = nullptr;
978 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
979 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
981 !(PrevClassTemplate &&
982 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
983 SemanticContext->getRedeclContext()))) {
984 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
985 Diag(Shadow->getTargetDecl()->getLocation(),
986 diag::note_using_decl_target);
987 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
988 // Recover by ignoring the old declaration.
989 PrevDecl = PrevClassTemplate = nullptr;
993 if (PrevClassTemplate) {
994 // Ensure that the template parameter lists are compatible. Skip this check
995 // for a friend in a dependent context: the template parameter list itself
996 // could be dependent.
997 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
998 !TemplateParameterListsAreEqual(TemplateParams,
999 PrevClassTemplate->getTemplateParameters(),
1004 // C++ [temp.class]p4:
1005 // In a redeclaration, partial specialization, explicit
1006 // specialization or explicit instantiation of a class template,
1007 // the class-key shall agree in kind with the original class
1008 // template declaration (7.1.5.3).
1009 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
1010 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
1011 TUK == TUK_Definition, KWLoc, Name)) {
1012 Diag(KWLoc, diag::err_use_with_wrong_tag)
1014 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
1015 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
1016 Kind = PrevRecordDecl->getTagKind();
1019 // Check for redefinition of this class template.
1020 if (TUK == TUK_Definition) {
1021 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
1022 // If we have a prior definition that is not visible, treat this as
1023 // simply making that previous definition visible.
1024 NamedDecl *Hidden = nullptr;
1025 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
1026 SkipBody->ShouldSkip = true;
1027 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1028 assert(Tmpl && "original definition of a class template is not a "
1030 makeMergedDefinitionVisible(Hidden, KWLoc);
1031 makeMergedDefinitionVisible(Tmpl, KWLoc);
1035 Diag(NameLoc, diag::err_redefinition) << Name;
1036 Diag(Def->getLocation(), diag::note_previous_definition);
1037 // FIXME: Would it make sense to try to "forget" the previous
1038 // definition, as part of error recovery?
1042 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
1043 // Maybe we will complain about the shadowed template parameter.
1044 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1045 // Just pretend that we didn't see the previous declaration.
1047 } else if (PrevDecl) {
1049 // A class template shall not have the same name as any other
1050 // template, class, function, object, enumeration, enumerator,
1051 // namespace, or type in the same scope (3.3), except as specified
1053 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1054 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1058 // Check the template parameter list of this declaration, possibly
1059 // merging in the template parameter list from the previous class
1060 // template declaration. Skip this check for a friend in a dependent
1061 // context, because the template parameter list might be dependent.
1062 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1063 CheckTemplateParameterList(
1065 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1067 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1068 SemanticContext->isDependentContext())
1069 ? TPC_ClassTemplateMember
1070 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1071 : TPC_ClassTemplate))
1075 // If the name of the template was qualified, we must be defining the
1076 // template out-of-line.
1077 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1078 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
1079 : diag::err_member_decl_does_not_match)
1080 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
1085 CXXRecordDecl *NewClass =
1086 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
1088 PrevClassTemplate->getTemplatedDecl() : nullptr,
1089 /*DelayTypeCreation=*/true);
1090 SetNestedNameSpecifier(NewClass, SS);
1091 if (NumOuterTemplateParamLists > 0)
1092 NewClass->setTemplateParameterListsInfo(
1093 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1094 NumOuterTemplateParamLists));
1096 // Add alignment attributes if necessary; these attributes are checked when
1097 // the ASTContext lays out the structure.
1098 if (TUK == TUK_Definition) {
1099 AddAlignmentAttributesForRecord(NewClass);
1100 AddMsStructLayoutForRecord(NewClass);
1103 ClassTemplateDecl *NewTemplate
1104 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1105 DeclarationName(Name), TemplateParams,
1106 NewClass, PrevClassTemplate);
1107 NewClass->setDescribedClassTemplate(NewTemplate);
1109 if (ModulePrivateLoc.isValid())
1110 NewTemplate->setModulePrivate();
1112 // Build the type for the class template declaration now.
1113 QualType T = NewTemplate->getInjectedClassNameSpecialization();
1114 T = Context.getInjectedClassNameType(NewClass, T);
1115 assert(T->isDependentType() && "Class template type is not dependent?");
1118 // If we are providing an explicit specialization of a member that is a
1119 // class template, make a note of that.
1120 if (PrevClassTemplate &&
1121 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1122 PrevClassTemplate->setMemberSpecialization();
1124 // Set the access specifier.
1125 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
1126 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
1128 // Set the lexical context of these templates
1129 NewClass->setLexicalDeclContext(CurContext);
1130 NewTemplate->setLexicalDeclContext(CurContext);
1132 if (TUK == TUK_Definition)
1133 NewClass->startDefinition();
1136 ProcessDeclAttributeList(S, NewClass, Attr);
1138 if (PrevClassTemplate)
1139 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1141 AddPushedVisibilityAttribute(NewClass);
1143 if (TUK != TUK_Friend) {
1144 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1146 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1147 Outer = Outer->getParent();
1148 PushOnScopeChains(NewTemplate, Outer);
1150 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
1151 NewTemplate->setAccess(PrevClassTemplate->getAccess());
1152 NewClass->setAccess(PrevClassTemplate->getAccess());
1155 NewTemplate->setObjectOfFriendDecl();
1157 // Friend templates are visible in fairly strange ways.
1158 if (!CurContext->isDependentContext()) {
1159 DeclContext *DC = SemanticContext->getRedeclContext();
1160 DC->makeDeclVisibleInContext(NewTemplate);
1161 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1162 PushOnScopeChains(NewTemplate, EnclosingScope,
1163 /* AddToContext = */ false);
1166 FriendDecl *Friend = FriendDecl::Create(
1167 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
1168 Friend->setAccess(AS_public);
1169 CurContext->addDecl(Friend);
1173 NewTemplate->setInvalidDecl();
1174 NewClass->setInvalidDecl();
1177 ActOnDocumentableDecl(NewTemplate);
1182 /// \brief Diagnose the presence of a default template argument on a
1183 /// template parameter, which is ill-formed in certain contexts.
1185 /// \returns true if the default template argument should be dropped.
1186 static bool DiagnoseDefaultTemplateArgument(Sema &S,
1187 Sema::TemplateParamListContext TPC,
1188 SourceLocation ParamLoc,
1189 SourceRange DefArgRange) {
1191 case Sema::TPC_ClassTemplate:
1192 case Sema::TPC_VarTemplate:
1193 case Sema::TPC_TypeAliasTemplate:
1196 case Sema::TPC_FunctionTemplate:
1197 case Sema::TPC_FriendFunctionTemplateDefinition:
1198 // C++ [temp.param]p9:
1199 // A default template-argument shall not be specified in a
1200 // function template declaration or a function template
1202 // If a friend function template declaration specifies a default
1203 // template-argument, that declaration shall be a definition and shall be
1204 // the only declaration of the function template in the translation unit.
1205 // (C++98/03 doesn't have this wording; see DR226).
1206 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
1207 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1208 : diag::ext_template_parameter_default_in_function_template)
1212 case Sema::TPC_ClassTemplateMember:
1213 // C++0x [temp.param]p9:
1214 // A default template-argument shall not be specified in the
1215 // template-parameter-lists of the definition of a member of a
1216 // class template that appears outside of the member's class.
1217 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1221 case Sema::TPC_FriendClassTemplate:
1222 case Sema::TPC_FriendFunctionTemplate:
1223 // C++ [temp.param]p9:
1224 // A default template-argument shall not be specified in a
1225 // friend template declaration.
1226 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1230 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1231 // for friend function templates if there is only a single
1232 // declaration (and it is a definition). Strange!
1235 llvm_unreachable("Invalid TemplateParamListContext!");
1238 /// \brief Check for unexpanded parameter packs within the template parameters
1239 /// of a template template parameter, recursively.
1240 static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1241 TemplateTemplateParmDecl *TTP) {
1242 // A template template parameter which is a parameter pack is also a pack
1244 if (TTP->isParameterPack())
1247 TemplateParameterList *Params = TTP->getTemplateParameters();
1248 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1249 NamedDecl *P = Params->getParam(I);
1250 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
1251 if (!NTTP->isParameterPack() &&
1252 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
1253 NTTP->getTypeSourceInfo(),
1254 Sema::UPPC_NonTypeTemplateParameterType))
1260 if (TemplateTemplateParmDecl *InnerTTP
1261 = dyn_cast<TemplateTemplateParmDecl>(P))
1262 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1269 /// \brief Checks the validity of a template parameter list, possibly
1270 /// considering the template parameter list from a previous
1273 /// If an "old" template parameter list is provided, it must be
1274 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
1275 /// template parameter list.
1277 /// \param NewParams Template parameter list for a new template
1278 /// declaration. This template parameter list will be updated with any
1279 /// default arguments that are carried through from the previous
1280 /// template parameter list.
1282 /// \param OldParams If provided, template parameter list from a
1283 /// previous declaration of the same template. Default template
1284 /// arguments will be merged from the old template parameter list to
1285 /// the new template parameter list.
1287 /// \param TPC Describes the context in which we are checking the given
1288 /// template parameter list.
1290 /// \returns true if an error occurred, false otherwise.
1291 bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
1292 TemplateParameterList *OldParams,
1293 TemplateParamListContext TPC) {
1294 bool Invalid = false;
1296 // C++ [temp.param]p10:
1297 // The set of default template-arguments available for use with a
1298 // template declaration or definition is obtained by merging the
1299 // default arguments from the definition (if in scope) and all
1300 // declarations in scope in the same way default function
1301 // arguments are (8.3.6).
1302 bool SawDefaultArgument = false;
1303 SourceLocation PreviousDefaultArgLoc;
1305 // Dummy initialization to avoid warnings.
1306 TemplateParameterList::iterator OldParam = NewParams->end();
1308 OldParam = OldParams->begin();
1310 bool RemoveDefaultArguments = false;
1311 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1312 NewParamEnd = NewParams->end();
1313 NewParam != NewParamEnd; ++NewParam) {
1314 // Variables used to diagnose redundant default arguments
1315 bool RedundantDefaultArg = false;
1316 SourceLocation OldDefaultLoc;
1317 SourceLocation NewDefaultLoc;
1319 // Variable used to diagnose missing default arguments
1320 bool MissingDefaultArg = false;
1322 // Variable used to diagnose non-final parameter packs
1323 bool SawParameterPack = false;
1325 if (TemplateTypeParmDecl *NewTypeParm
1326 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
1327 // Check the presence of a default argument here.
1328 if (NewTypeParm->hasDefaultArgument() &&
1329 DiagnoseDefaultTemplateArgument(*this, TPC,
1330 NewTypeParm->getLocation(),
1331 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1333 NewTypeParm->removeDefaultArgument();
1335 // Merge default arguments for template type parameters.
1336 TemplateTypeParmDecl *OldTypeParm
1337 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
1338 if (NewTypeParm->isParameterPack()) {
1339 assert(!NewTypeParm->hasDefaultArgument() &&
1340 "Parameter packs can't have a default argument!");
1341 SawParameterPack = true;
1342 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
1343 NewTypeParm->hasDefaultArgument()) {
1344 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1345 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1346 SawDefaultArgument = true;
1347 RedundantDefaultArg = true;
1348 PreviousDefaultArgLoc = NewDefaultLoc;
1349 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1350 // Merge the default argument from the old declaration to the
1352 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
1353 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1354 } else if (NewTypeParm->hasDefaultArgument()) {
1355 SawDefaultArgument = true;
1356 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1357 } else if (SawDefaultArgument)
1358 MissingDefaultArg = true;
1359 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
1360 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
1361 // Check for unexpanded parameter packs.
1362 if (!NewNonTypeParm->isParameterPack() &&
1363 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
1364 NewNonTypeParm->getTypeSourceInfo(),
1365 UPPC_NonTypeTemplateParameterType)) {
1370 // Check the presence of a default argument here.
1371 if (NewNonTypeParm->hasDefaultArgument() &&
1372 DiagnoseDefaultTemplateArgument(*this, TPC,
1373 NewNonTypeParm->getLocation(),
1374 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1375 NewNonTypeParm->removeDefaultArgument();
1378 // Merge default arguments for non-type template parameters
1379 NonTypeTemplateParmDecl *OldNonTypeParm
1380 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
1381 if (NewNonTypeParm->isParameterPack()) {
1382 assert(!NewNonTypeParm->hasDefaultArgument() &&
1383 "Parameter packs can't have a default argument!");
1384 if (!NewNonTypeParm->isPackExpansion())
1385 SawParameterPack = true;
1386 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
1387 NewNonTypeParm->hasDefaultArgument()) {
1388 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1389 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1390 SawDefaultArgument = true;
1391 RedundantDefaultArg = true;
1392 PreviousDefaultArgLoc = NewDefaultLoc;
1393 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1394 // Merge the default argument from the old declaration to the
1396 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
1397 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1398 } else if (NewNonTypeParm->hasDefaultArgument()) {
1399 SawDefaultArgument = true;
1400 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1401 } else if (SawDefaultArgument)
1402 MissingDefaultArg = true;
1404 TemplateTemplateParmDecl *NewTemplateParm
1405 = cast<TemplateTemplateParmDecl>(*NewParam);
1407 // Check for unexpanded parameter packs, recursively.
1408 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
1413 // Check the presence of a default argument here.
1414 if (NewTemplateParm->hasDefaultArgument() &&
1415 DiagnoseDefaultTemplateArgument(*this, TPC,
1416 NewTemplateParm->getLocation(),
1417 NewTemplateParm->getDefaultArgument().getSourceRange()))
1418 NewTemplateParm->removeDefaultArgument();
1420 // Merge default arguments for template template parameters
1421 TemplateTemplateParmDecl *OldTemplateParm
1422 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
1423 if (NewTemplateParm->isParameterPack()) {
1424 assert(!NewTemplateParm->hasDefaultArgument() &&
1425 "Parameter packs can't have a default argument!");
1426 if (!NewTemplateParm->isPackExpansion())
1427 SawParameterPack = true;
1428 } else if (OldTemplateParm &&
1429 hasVisibleDefaultArgument(OldTemplateParm) &&
1430 NewTemplateParm->hasDefaultArgument()) {
1431 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1432 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
1433 SawDefaultArgument = true;
1434 RedundantDefaultArg = true;
1435 PreviousDefaultArgLoc = NewDefaultLoc;
1436 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1437 // Merge the default argument from the old declaration to the
1439 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
1440 PreviousDefaultArgLoc
1441 = OldTemplateParm->getDefaultArgument().getLocation();
1442 } else if (NewTemplateParm->hasDefaultArgument()) {
1443 SawDefaultArgument = true;
1444 PreviousDefaultArgLoc
1445 = NewTemplateParm->getDefaultArgument().getLocation();
1446 } else if (SawDefaultArgument)
1447 MissingDefaultArg = true;
1450 // C++11 [temp.param]p11:
1451 // If a template parameter of a primary class template or alias template
1452 // is a template parameter pack, it shall be the last template parameter.
1453 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
1454 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
1455 TPC == TPC_TypeAliasTemplate)) {
1456 Diag((*NewParam)->getLocation(),
1457 diag::err_template_param_pack_must_be_last_template_parameter);
1461 if (RedundantDefaultArg) {
1462 // C++ [temp.param]p12:
1463 // A template-parameter shall not be given default arguments
1464 // by two different declarations in the same scope.
1465 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1466 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1468 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
1469 // C++ [temp.param]p11:
1470 // If a template-parameter of a class template has a default
1471 // template-argument, each subsequent template-parameter shall either
1472 // have a default template-argument supplied or be a template parameter
1474 Diag((*NewParam)->getLocation(),
1475 diag::err_template_param_default_arg_missing);
1476 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1478 RemoveDefaultArguments = true;
1481 // If we have an old template parameter list that we're merging
1482 // in, move on to the next parameter.
1487 // We were missing some default arguments at the end of the list, so remove
1488 // all of the default arguments.
1489 if (RemoveDefaultArguments) {
1490 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1491 NewParamEnd = NewParams->end();
1492 NewParam != NewParamEnd; ++NewParam) {
1493 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1494 TTP->removeDefaultArgument();
1495 else if (NonTypeTemplateParmDecl *NTTP
1496 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1497 NTTP->removeDefaultArgument();
1499 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1508 /// A class which looks for a use of a certain level of template
1510 struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1511 typedef RecursiveASTVisitor<DependencyChecker> super;
1515 SourceLocation MatchLoc;
1517 DependencyChecker(unsigned Depth) : Depth(Depth), Match(false) {}
1519 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1520 NamedDecl *ND = Params->getParam(0);
1521 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1522 Depth = PD->getDepth();
1523 } else if (NonTypeTemplateParmDecl *PD =
1524 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1525 Depth = PD->getDepth();
1527 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1531 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
1532 if (ParmDepth >= Depth) {
1540 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1541 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
1544 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1545 return !Matches(T->getDepth());
1548 bool TraverseTemplateName(TemplateName N) {
1549 if (TemplateTemplateParmDecl *PD =
1550 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
1551 if (Matches(PD->getDepth()))
1553 return super::TraverseTemplateName(N);
1556 bool VisitDeclRefExpr(DeclRefExpr *E) {
1557 if (NonTypeTemplateParmDecl *PD =
1558 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
1559 if (Matches(PD->getDepth(), E->getExprLoc()))
1561 return super::VisitDeclRefExpr(E);
1564 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1565 return TraverseType(T->getReplacementType());
1569 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
1570 return TraverseTemplateArgument(T->getArgumentPack());
1573 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1574 return TraverseType(T->getInjectedSpecializationType());
1579 /// Determines whether a given type depends on the given parameter
1582 DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
1583 DependencyChecker Checker(Params);
1584 Checker.TraverseType(T);
1585 return Checker.Match;
1588 // Find the source range corresponding to the named type in the given
1589 // nested-name-specifier, if any.
1590 static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
1592 const CXXScopeSpec &SS) {
1593 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
1594 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1595 if (const Type *CurType = NNS->getAsType()) {
1596 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1597 return NNSLoc.getTypeLoc().getSourceRange();
1601 NNSLoc = NNSLoc.getPrefix();
1604 return SourceRange();
1607 /// \brief Match the given template parameter lists to the given scope
1608 /// specifier, returning the template parameter list that applies to the
1611 /// \param DeclStartLoc the start of the declaration that has a scope
1612 /// specifier or a template parameter list.
1614 /// \param DeclLoc The location of the declaration itself.
1616 /// \param SS the scope specifier that will be matched to the given template
1617 /// parameter lists. This scope specifier precedes a qualified name that is
1620 /// \param TemplateId The template-id following the scope specifier, if there
1621 /// is one. Used to check for a missing 'template<>'.
1623 /// \param ParamLists the template parameter lists, from the outermost to the
1624 /// innermost template parameter lists.
1626 /// \param IsFriend Whether to apply the slightly different rules for
1627 /// matching template parameters to scope specifiers in friend
1630 /// \param IsExplicitSpecialization will be set true if the entity being
1631 /// declared is an explicit specialization, false otherwise.
1633 /// \returns the template parameter list, if any, that corresponds to the
1634 /// name that is preceded by the scope specifier @p SS. This template
1635 /// parameter list may have template parameters (if we're declaring a
1636 /// template) or may have no template parameters (if we're declaring a
1637 /// template specialization), or may be NULL (if what we're declaring isn't
1638 /// itself a template).
1639 TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
1640 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
1641 TemplateIdAnnotation *TemplateId,
1642 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
1643 bool &IsExplicitSpecialization, bool &Invalid) {
1644 IsExplicitSpecialization = false;
1647 // The sequence of nested types to which we will match up the template
1648 // parameter lists. We first build this list by starting with the type named
1649 // by the nested-name-specifier and walking out until we run out of types.
1650 SmallVector<QualType, 4> NestedTypes;
1652 if (SS.getScopeRep()) {
1653 if (CXXRecordDecl *Record
1654 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1655 T = Context.getTypeDeclType(Record);
1657 T = QualType(SS.getScopeRep()->getAsType(), 0);
1660 // If we found an explicit specialization that prevents us from needing
1661 // 'template<>' headers, this will be set to the location of that
1662 // explicit specialization.
1663 SourceLocation ExplicitSpecLoc;
1665 while (!T.isNull()) {
1666 NestedTypes.push_back(T);
1668 // Retrieve the parent of a record type.
1669 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1670 // If this type is an explicit specialization, we're done.
1671 if (ClassTemplateSpecializationDecl *Spec
1672 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1673 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
1674 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1675 ExplicitSpecLoc = Spec->getLocation();
1678 } else if (Record->getTemplateSpecializationKind()
1679 == TSK_ExplicitSpecialization) {
1680 ExplicitSpecLoc = Record->getLocation();
1684 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1685 T = Context.getTypeDeclType(Parent);
1691 if (const TemplateSpecializationType *TST
1692 = T->getAs<TemplateSpecializationType>()) {
1693 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1694 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1695 T = Context.getTypeDeclType(Parent);
1702 // Look one step prior in a dependent template specialization type.
1703 if (const DependentTemplateSpecializationType *DependentTST
1704 = T->getAs<DependentTemplateSpecializationType>()) {
1705 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1706 T = QualType(NNS->getAsType(), 0);
1712 // Look one step prior in a dependent name type.
1713 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1714 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1715 T = QualType(NNS->getAsType(), 0);
1721 // Retrieve the parent of an enumeration type.
1722 if (const EnumType *EnumT = T->getAs<EnumType>()) {
1723 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1725 EnumDecl *Enum = EnumT->getDecl();
1727 // Get to the parent type.
1728 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1729 T = Context.getTypeDeclType(Parent);
1737 // Reverse the nested types list, since we want to traverse from the outermost
1738 // to the innermost while checking template-parameter-lists.
1739 std::reverse(NestedTypes.begin(), NestedTypes.end());
1741 // C++0x [temp.expl.spec]p17:
1742 // A member or a member template may be nested within many
1743 // enclosing class templates. In an explicit specialization for
1744 // such a member, the member declaration shall be preceded by a
1745 // template<> for each enclosing class template that is
1746 // explicitly specialized.
1747 bool SawNonEmptyTemplateParameterList = false;
1749 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
1750 if (SawNonEmptyTemplateParameterList) {
1751 Diag(DeclLoc, diag::err_specialize_member_of_template)
1752 << !Recovery << Range;
1754 IsExplicitSpecialization = false;
1761 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
1762 // Check that we can have an explicit specialization here.
1763 if (CheckExplicitSpecialization(Range, true))
1766 // We don't have a template header, but we should.
1767 SourceLocation ExpectedTemplateLoc;
1768 if (!ParamLists.empty())
1769 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
1771 ExpectedTemplateLoc = DeclStartLoc;
1773 Diag(DeclLoc, diag::err_template_spec_needs_header)
1775 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
1779 unsigned ParamIdx = 0;
1780 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
1782 T = NestedTypes[TypeIdx];
1784 // Whether we expect a 'template<>' header.
1785 bool NeedEmptyTemplateHeader = false;
1787 // Whether we expect a template header with parameters.
1788 bool NeedNonemptyTemplateHeader = false;
1790 // For a dependent type, the set of template parameters that we
1792 TemplateParameterList *ExpectedTemplateParams = nullptr;
1794 // C++0x [temp.expl.spec]p15:
1795 // A member or a member template may be nested within many enclosing
1796 // class templates. In an explicit specialization for such a member, the
1797 // member declaration shall be preceded by a template<> for each
1798 // enclosing class template that is explicitly specialized.
1799 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1800 if (ClassTemplatePartialSpecializationDecl *Partial
1801 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1802 ExpectedTemplateParams = Partial->getTemplateParameters();
1803 NeedNonemptyTemplateHeader = true;
1804 } else if (Record->isDependentType()) {
1805 if (Record->getDescribedClassTemplate()) {
1806 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1807 ->getTemplateParameters();
1808 NeedNonemptyTemplateHeader = true;
1810 } else if (ClassTemplateSpecializationDecl *Spec
1811 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1812 // C++0x [temp.expl.spec]p4:
1813 // Members of an explicitly specialized class template are defined
1814 // in the same manner as members of normal classes, and not using
1815 // the template<> syntax.
1816 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
1817 NeedEmptyTemplateHeader = true;
1820 } else if (Record->getTemplateSpecializationKind()) {
1821 if (Record->getTemplateSpecializationKind()
1822 != TSK_ExplicitSpecialization &&
1823 TypeIdx == NumTypes - 1)
1824 IsExplicitSpecialization = true;
1828 } else if (const TemplateSpecializationType *TST
1829 = T->getAs<TemplateSpecializationType>()) {
1830 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1831 ExpectedTemplateParams = Template->getTemplateParameters();
1832 NeedNonemptyTemplateHeader = true;
1834 } else if (T->getAs<DependentTemplateSpecializationType>()) {
1835 // FIXME: We actually could/should check the template arguments here
1836 // against the corresponding template parameter list.
1837 NeedNonemptyTemplateHeader = false;
1840 // C++ [temp.expl.spec]p16:
1841 // In an explicit specialization declaration for a member of a class
1842 // template or a member template that ap- pears in namespace scope, the
1843 // member template and some of its enclosing class templates may remain
1844 // unspecialized, except that the declaration shall not explicitly
1845 // specialize a class member template if its en- closing class templates
1846 // are not explicitly specialized as well.
1847 if (ParamIdx < ParamLists.size()) {
1848 if (ParamLists[ParamIdx]->size() == 0) {
1849 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1853 SawNonEmptyTemplateParameterList = true;
1856 if (NeedEmptyTemplateHeader) {
1857 // If we're on the last of the types, and we need a 'template<>' header
1858 // here, then it's an explicit specialization.
1859 if (TypeIdx == NumTypes - 1)
1860 IsExplicitSpecialization = true;
1862 if (ParamIdx < ParamLists.size()) {
1863 if (ParamLists[ParamIdx]->size() > 0) {
1864 // The header has template parameters when it shouldn't. Complain.
1865 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1866 diag::err_template_param_list_matches_nontemplate)
1868 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
1869 ParamLists[ParamIdx]->getRAngleLoc())
1870 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1875 // Consume this template header.
1881 if (DiagnoseMissingExplicitSpecialization(
1882 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
1888 if (NeedNonemptyTemplateHeader) {
1889 // In friend declarations we can have template-ids which don't
1890 // depend on the corresponding template parameter lists. But
1891 // assume that empty parameter lists are supposed to match this
1893 if (IsFriend && T->isDependentType()) {
1894 if (ParamIdx < ParamLists.size() &&
1895 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
1896 ExpectedTemplateParams = nullptr;
1901 if (ParamIdx < ParamLists.size()) {
1902 // Check the template parameter list, if we can.
1903 if (ExpectedTemplateParams &&
1904 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
1905 ExpectedTemplateParams,
1906 true, TPL_TemplateMatch))
1910 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
1911 TPC_ClassTemplateMember))
1918 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
1920 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1926 // If there were at least as many template-ids as there were template
1927 // parameter lists, then there are no template parameter lists remaining for
1928 // the declaration itself.
1929 if (ParamIdx >= ParamLists.size()) {
1930 if (TemplateId && !IsFriend) {
1931 // We don't have a template header for the declaration itself, but we
1933 IsExplicitSpecialization = true;
1934 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
1935 TemplateId->RAngleLoc));
1937 // Fabricate an empty template parameter list for the invented header.
1938 return TemplateParameterList::Create(Context, SourceLocation(),
1939 SourceLocation(), nullptr, 0,
1946 // If there were too many template parameter lists, complain about that now.
1947 if (ParamIdx < ParamLists.size() - 1) {
1948 bool HasAnyExplicitSpecHeader = false;
1949 bool AllExplicitSpecHeaders = true;
1950 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
1951 if (ParamLists[I]->size() == 0)
1952 HasAnyExplicitSpecHeader = true;
1954 AllExplicitSpecHeaders = false;
1957 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1958 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
1959 : diag::err_template_spec_extra_headers)
1960 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1961 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
1963 // If there was a specialization somewhere, such that 'template<>' is
1964 // not required, and there were any 'template<>' headers, note where the
1965 // specialization occurred.
1966 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
1967 Diag(ExplicitSpecLoc,
1968 diag::note_explicit_template_spec_does_not_need_header)
1969 << NestedTypes.back();
1971 // We have a template parameter list with no corresponding scope, which
1972 // means that the resulting template declaration can't be instantiated
1973 // properly (we'll end up with dependent nodes when we shouldn't).
1974 if (!AllExplicitSpecHeaders)
1978 // C++ [temp.expl.spec]p16:
1979 // In an explicit specialization declaration for a member of a class
1980 // template or a member template that ap- pears in namespace scope, the
1981 // member template and some of its enclosing class templates may remain
1982 // unspecialized, except that the declaration shall not explicitly
1983 // specialize a class member template if its en- closing class templates
1984 // are not explicitly specialized as well.
1985 if (ParamLists.back()->size() == 0 &&
1986 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1990 // Return the last template parameter list, which corresponds to the
1991 // entity being declared.
1992 return ParamLists.back();
1995 void Sema::NoteAllFoundTemplates(TemplateName Name) {
1996 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
1997 Diag(Template->getLocation(), diag::note_template_declared_here)
1998 << (isa<FunctionTemplateDecl>(Template)
2000 : isa<ClassTemplateDecl>(Template)
2002 : isa<VarTemplateDecl>(Template)
2004 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2005 << Template->getDeclName();
2009 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
2010 for (OverloadedTemplateStorage::iterator I = OST->begin(),
2013 Diag((*I)->getLocation(), diag::note_template_declared_here)
2014 << 0 << (*I)->getDeclName();
2020 QualType Sema::CheckTemplateIdType(TemplateName Name,
2021 SourceLocation TemplateLoc,
2022 TemplateArgumentListInfo &TemplateArgs) {
2023 DependentTemplateName *DTN
2024 = Name.getUnderlying().getAsDependentTemplateName();
2025 if (DTN && DTN->isIdentifier())
2026 // When building a template-id where the template-name is dependent,
2027 // assume the template is a type template. Either our assumption is
2028 // correct, or the code is ill-formed and will be diagnosed when the
2029 // dependent name is substituted.
2030 return Context.getDependentTemplateSpecializationType(ETK_None,
2031 DTN->getQualifier(),
2032 DTN->getIdentifier(),
2035 TemplateDecl *Template = Name.getAsTemplateDecl();
2036 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2037 isa<VarTemplateDecl>(Template)) {
2038 // We might have a substituted template template parameter pack. If so,
2039 // build a template specialization type for it.
2040 if (Name.getAsSubstTemplateTemplateParmPack())
2041 return Context.getTemplateSpecializationType(Name, TemplateArgs);
2043 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2045 NoteAllFoundTemplates(Name);
2049 // Check that the template argument list is well-formed for this
2051 SmallVector<TemplateArgument, 4> Converted;
2052 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
2058 bool InstantiationDependent = false;
2059 if (TypeAliasTemplateDecl *AliasTemplate =
2060 dyn_cast<TypeAliasTemplateDecl>(Template)) {
2061 // Find the canonical type for this type alias template specialization.
2062 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2063 if (Pattern->isInvalidDecl())
2066 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2067 Converted.data(), Converted.size());
2069 // Only substitute for the innermost template argument list.
2070 MultiLevelTemplateArgumentList TemplateArgLists;
2071 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
2072 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2073 for (unsigned I = 0; I < Depth; ++I)
2074 TemplateArgLists.addOuterTemplateArguments(None);
2076 LocalInstantiationScope Scope(*this);
2077 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
2078 if (Inst.isInvalid())
2081 CanonType = SubstType(Pattern->getUnderlyingType(),
2082 TemplateArgLists, AliasTemplate->getLocation(),
2083 AliasTemplate->getDeclName());
2084 if (CanonType.isNull())
2086 } else if (Name.isDependent() ||
2087 TemplateSpecializationType::anyDependentTemplateArguments(
2088 TemplateArgs, InstantiationDependent)) {
2089 // This class template specialization is a dependent
2090 // type. Therefore, its canonical type is another class template
2091 // specialization type that contains all of the converted
2092 // arguments in canonical form. This ensures that, e.g., A<T> and
2093 // A<T, T> have identical types when A is declared as:
2095 // template<typename T, typename U = T> struct A;
2096 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
2097 CanonType = Context.getTemplateSpecializationType(CanonName,
2101 // FIXME: CanonType is not actually the canonical type, and unfortunately
2102 // it is a TemplateSpecializationType that we will never use again.
2103 // In the future, we need to teach getTemplateSpecializationType to only
2104 // build the canonical type and return that to us.
2105 CanonType = Context.getCanonicalType(CanonType);
2107 // This might work out to be a current instantiation, in which
2108 // case the canonical type needs to be the InjectedClassNameType.
2110 // TODO: in theory this could be a simple hashtable lookup; most
2111 // changes to CurContext don't change the set of current
2113 if (isa<ClassTemplateDecl>(Template)) {
2114 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2115 // If we get out to a namespace, we're done.
2116 if (Ctx->isFileContext()) break;
2118 // If this isn't a record, keep looking.
2119 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2120 if (!Record) continue;
2122 // Look for one of the two cases with InjectedClassNameTypes
2123 // and check whether it's the same template.
2124 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2125 !Record->getDescribedClassTemplate())
2128 // Fetch the injected class name type and check whether its
2129 // injected type is equal to the type we just built.
2130 QualType ICNT = Context.getTypeDeclType(Record);
2131 QualType Injected = cast<InjectedClassNameType>(ICNT)
2132 ->getInjectedSpecializationType();
2134 if (CanonType != Injected->getCanonicalTypeInternal())
2137 // If so, the canonical type of this TST is the injected
2138 // class name type of the record we just found.
2139 assert(ICNT.isCanonical());
2144 } else if (ClassTemplateDecl *ClassTemplate
2145 = dyn_cast<ClassTemplateDecl>(Template)) {
2146 // Find the class template specialization declaration that
2147 // corresponds to these arguments.
2148 void *InsertPos = nullptr;
2149 ClassTemplateSpecializationDecl *Decl
2150 = ClassTemplate->findSpecialization(Converted, InsertPos);
2152 // This is the first time we have referenced this class template
2153 // specialization. Create the canonical declaration and add it to
2154 // the set of specializations.
2155 Decl = ClassTemplateSpecializationDecl::Create(Context,
2156 ClassTemplate->getTemplatedDecl()->getTagKind(),
2157 ClassTemplate->getDeclContext(),
2158 ClassTemplate->getTemplatedDecl()->getLocStart(),
2159 ClassTemplate->getLocation(),
2162 Converted.size(), nullptr);
2163 ClassTemplate->AddSpecialization(Decl, InsertPos);
2164 if (ClassTemplate->isOutOfLine())
2165 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
2168 // Diagnose uses of this specialization.
2169 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2171 CanonType = Context.getTypeDeclType(Decl);
2172 assert(isa<RecordType>(CanonType) &&
2173 "type of non-dependent specialization is not a RecordType");
2176 // Build the fully-sugared type for this class template
2177 // specialization, which refers back to the class template
2178 // specialization we created or found.
2179 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
2183 Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
2184 TemplateTy TemplateD, SourceLocation TemplateLoc,
2185 SourceLocation LAngleLoc,
2186 ASTTemplateArgsPtr TemplateArgsIn,
2187 SourceLocation RAngleLoc,
2188 bool IsCtorOrDtorName) {
2192 TemplateName Template = TemplateD.get();
2194 // Translate the parser's template argument list in our AST format.
2195 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2196 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2198 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2200 = Context.getDependentTemplateSpecializationType(ETK_None,
2201 DTN->getQualifier(),
2202 DTN->getIdentifier(),
2204 // Build type-source information.
2206 DependentTemplateSpecializationTypeLoc SpecTL
2207 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2208 SpecTL.setElaboratedKeywordLoc(SourceLocation());
2209 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
2210 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2211 SpecTL.setTemplateNameLoc(TemplateLoc);
2212 SpecTL.setLAngleLoc(LAngleLoc);
2213 SpecTL.setRAngleLoc(RAngleLoc);
2214 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2215 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2216 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2219 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2221 if (Result.isNull())
2224 // Build type-source information.
2226 TemplateSpecializationTypeLoc SpecTL
2227 = TLB.push<TemplateSpecializationTypeLoc>(Result);
2228 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2229 SpecTL.setTemplateNameLoc(TemplateLoc);
2230 SpecTL.setLAngleLoc(LAngleLoc);
2231 SpecTL.setRAngleLoc(RAngleLoc);
2232 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2233 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
2235 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2236 // constructor or destructor name (in such a case, the scope specifier
2237 // will be attached to the enclosing Decl or Expr node).
2238 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
2239 // Create an elaborated-type-specifier containing the nested-name-specifier.
2240 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2241 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
2242 ElabTL.setElaboratedKeywordLoc(SourceLocation());
2243 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2246 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
2249 TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
2250 TypeSpecifierType TagSpec,
2251 SourceLocation TagLoc,
2253 SourceLocation TemplateKWLoc,
2254 TemplateTy TemplateD,
2255 SourceLocation TemplateLoc,
2256 SourceLocation LAngleLoc,
2257 ASTTemplateArgsPtr TemplateArgsIn,
2258 SourceLocation RAngleLoc) {
2259 TemplateName Template = TemplateD.get();
2261 // Translate the parser's template argument list in our AST format.
2262 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2263 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2265 // Determine the tag kind
2266 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
2267 ElaboratedTypeKeyword Keyword
2268 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
2270 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2271 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
2272 DTN->getQualifier(),
2273 DTN->getIdentifier(),
2276 // Build type-source information.
2278 DependentTemplateSpecializationTypeLoc SpecTL
2279 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2280 SpecTL.setElaboratedKeywordLoc(TagLoc);
2281 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
2282 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2283 SpecTL.setTemplateNameLoc(TemplateLoc);
2284 SpecTL.setLAngleLoc(LAngleLoc);
2285 SpecTL.setRAngleLoc(RAngleLoc);
2286 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2287 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2288 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2291 if (TypeAliasTemplateDecl *TAT =
2292 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2293 // C++0x [dcl.type.elab]p2:
2294 // If the identifier resolves to a typedef-name or the simple-template-id
2295 // resolves to an alias template specialization, the
2296 // elaborated-type-specifier is ill-formed.
2297 Diag(TemplateLoc, diag::err_tag_reference_non_tag) << 4;
2298 Diag(TAT->getLocation(), diag::note_declared_at);
2301 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2302 if (Result.isNull())
2303 return TypeResult(true);
2305 // Check the tag kind
2306 if (const RecordType *RT = Result->getAs<RecordType>()) {
2307 RecordDecl *D = RT->getDecl();
2309 IdentifierInfo *Id = D->getIdentifier();
2310 assert(Id && "templated class must have an identifier");
2312 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
2314 Diag(TagLoc, diag::err_use_with_wrong_tag)
2316 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
2317 Diag(D->getLocation(), diag::note_previous_use);
2321 // Provide source-location information for the template specialization.
2323 TemplateSpecializationTypeLoc SpecTL
2324 = TLB.push<TemplateSpecializationTypeLoc>(Result);
2325 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2326 SpecTL.setTemplateNameLoc(TemplateLoc);
2327 SpecTL.setLAngleLoc(LAngleLoc);
2328 SpecTL.setRAngleLoc(RAngleLoc);
2329 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2330 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
2332 // Construct an elaborated type containing the nested-name-specifier (if any)
2334 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2335 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
2336 ElabTL.setElaboratedKeywordLoc(TagLoc);
2337 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2338 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
2341 static bool CheckTemplatePartialSpecializationArgs(
2342 Sema &S, SourceLocation NameLoc, TemplateParameterList *TemplateParams,
2343 unsigned ExplicitArgs, SmallVectorImpl<TemplateArgument> &TemplateArgs);
2345 static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
2346 NamedDecl *PrevDecl,
2348 bool IsPartialSpecialization);
2350 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
2352 static bool isTemplateArgumentTemplateParameter(
2353 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
2354 switch (Arg.getKind()) {
2355 case TemplateArgument::Null:
2356 case TemplateArgument::NullPtr:
2357 case TemplateArgument::Integral:
2358 case TemplateArgument::Declaration:
2359 case TemplateArgument::Pack:
2360 case TemplateArgument::TemplateExpansion:
2363 case TemplateArgument::Type: {
2364 QualType Type = Arg.getAsType();
2365 const TemplateTypeParmType *TPT =
2366 Arg.getAsType()->getAs<TemplateTypeParmType>();
2367 return TPT && !Type.hasQualifiers() &&
2368 TPT->getDepth() == Depth && TPT->getIndex() == Index;
2371 case TemplateArgument::Expression: {
2372 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
2373 if (!DRE || !DRE->getDecl())
2375 const NonTypeTemplateParmDecl *NTTP =
2376 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2377 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
2380 case TemplateArgument::Template:
2381 const TemplateTemplateParmDecl *TTP =
2382 dyn_cast_or_null<TemplateTemplateParmDecl>(
2383 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
2384 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
2386 llvm_unreachable("unexpected kind of template argument");
2389 static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
2390 ArrayRef<TemplateArgument> Args) {
2391 if (Params->size() != Args.size())
2394 unsigned Depth = Params->getDepth();
2396 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2397 TemplateArgument Arg = Args[I];
2399 // If the parameter is a pack expansion, the argument must be a pack
2400 // whose only element is a pack expansion.
2401 if (Params->getParam(I)->isParameterPack()) {
2402 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
2403 !Arg.pack_begin()->isPackExpansion())
2405 Arg = Arg.pack_begin()->getPackExpansionPattern();
2408 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
2415 /// Convert the parser's template argument list representation into our form.
2416 static TemplateArgumentListInfo
2417 makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
2418 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
2419 TemplateId.RAngleLoc);
2420 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
2421 TemplateId.NumArgs);
2422 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
2423 return TemplateArgs;
2426 DeclResult Sema::ActOnVarTemplateSpecialization(
2427 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
2428 TemplateParameterList *TemplateParams, StorageClass SC,
2429 bool IsPartialSpecialization) {
2430 // D must be variable template id.
2431 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
2432 "Variable template specialization is declared with a template it.");
2434 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
2435 TemplateArgumentListInfo TemplateArgs =
2436 makeTemplateArgumentListInfo(*this, *TemplateId);
2437 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
2438 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
2439 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
2441 TemplateName Name = TemplateId->Template.get();
2443 // The template-id must name a variable template.
2444 VarTemplateDecl *VarTemplate =
2445 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
2447 NamedDecl *FnTemplate;
2448 if (auto *OTS = Name.getAsOverloadedTemplate())
2449 FnTemplate = *OTS->begin();
2451 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
2453 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
2454 << FnTemplate->getDeclName();
2455 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
2456 << IsPartialSpecialization;
2459 // Check for unexpanded parameter packs in any of the template arguments.
2460 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2461 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
2462 UPPC_PartialSpecialization))
2465 // Check that the template argument list is well-formed for this
2467 SmallVector<TemplateArgument, 4> Converted;
2468 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
2472 // Find the variable template (partial) specialization declaration that
2473 // corresponds to these arguments.
2474 if (IsPartialSpecialization) {
2475 if (CheckTemplatePartialSpecializationArgs(
2476 *this, TemplateNameLoc, VarTemplate->getTemplateParameters(),
2477 TemplateArgs.size(), Converted))
2480 bool InstantiationDependent;
2481 if (!Name.isDependent() &&
2482 !TemplateSpecializationType::anyDependentTemplateArguments(
2483 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
2484 InstantiationDependent)) {
2485 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
2486 << VarTemplate->getDeclName();
2487 IsPartialSpecialization = false;
2490 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
2492 // C++ [temp.class.spec]p9b3:
2494 // -- The argument list of the specialization shall not be identical
2495 // to the implicit argument list of the primary template.
2496 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2497 << /*variable template*/ 1
2498 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
2499 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
2500 // FIXME: Recover from this by treating the declaration as a redeclaration
2501 // of the primary template.
2506 void *InsertPos = nullptr;
2507 VarTemplateSpecializationDecl *PrevDecl = nullptr;
2509 if (IsPartialSpecialization)
2510 // FIXME: Template parameter list matters too
2511 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
2513 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
2515 VarTemplateSpecializationDecl *Specialization = nullptr;
2517 // Check whether we can declare a variable template specialization in
2518 // the current scope.
2519 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
2521 IsPartialSpecialization))
2524 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2525 // Since the only prior variable template specialization with these
2526 // arguments was referenced but not declared, reuse that
2527 // declaration node as our own, updating its source location and
2528 // the list of outer template parameters to reflect our new declaration.
2529 Specialization = PrevDecl;
2530 Specialization->setLocation(TemplateNameLoc);
2532 } else if (IsPartialSpecialization) {
2533 // Create a new class template partial specialization declaration node.
2534 VarTemplatePartialSpecializationDecl *PrevPartial =
2535 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
2536 VarTemplatePartialSpecializationDecl *Partial =
2537 VarTemplatePartialSpecializationDecl::Create(
2538 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
2539 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
2540 Converted.data(), Converted.size(), TemplateArgs);
2543 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
2544 Specialization = Partial;
2546 // If we are providing an explicit specialization of a member variable
2547 // template specialization, make a note of that.
2548 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
2549 PrevPartial->setMemberSpecialization();
2551 // Check that all of the template parameters of the variable template
2552 // partial specialization are deducible from the template
2553 // arguments. If not, this variable template partial specialization
2554 // will never be used.
2555 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
2556 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2557 TemplateParams->getDepth(), DeducibleParams);
2559 if (!DeducibleParams.all()) {
2560 unsigned NumNonDeducible =
2561 DeducibleParams.size() - DeducibleParams.count();
2562 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2563 << /*variable template*/ 1 << (NumNonDeducible > 1)
2564 << SourceRange(TemplateNameLoc, RAngleLoc);
2565 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2566 if (!DeducibleParams[I]) {
2567 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2568 if (Param->getDeclName())
2569 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2570 << Param->getDeclName();
2572 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2578 // Create a new class template specialization declaration node for
2579 // this explicit specialization or friend declaration.
2580 Specialization = VarTemplateSpecializationDecl::Create(
2581 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
2582 VarTemplate, DI->getType(), DI, SC, Converted.data(), Converted.size());
2583 Specialization->setTemplateArgsInfo(TemplateArgs);
2586 VarTemplate->AddSpecialization(Specialization, InsertPos);
2589 // C++ [temp.expl.spec]p6:
2590 // If a template, a member template or the member of a class template is
2591 // explicitly specialized then that specialization shall be declared
2592 // before the first use of that specialization that would cause an implicit
2593 // instantiation to take place, in every translation unit in which such a
2594 // use occurs; no diagnostic is required.
2595 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
2597 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
2598 // Is there any previous explicit specialization declaration?
2599 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
2606 SourceRange Range(TemplateNameLoc, RAngleLoc);
2607 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
2610 Diag(PrevDecl->getPointOfInstantiation(),
2611 diag::note_instantiation_required_here)
2612 << (PrevDecl->getTemplateSpecializationKind() !=
2613 TSK_ImplicitInstantiation);
2618 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
2619 Specialization->setLexicalDeclContext(CurContext);
2621 // Add the specialization into its lexical context, so that it can
2622 // be seen when iterating through the list of declarations in that
2623 // context. However, specializations are not found by name lookup.
2624 CurContext->addDecl(Specialization);
2626 // Note that this is an explicit specialization.
2627 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2630 // Check that this isn't a redefinition of this specialization,
2631 // merging with previous declarations.
2632 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
2634 PrevSpec.addDecl(PrevDecl);
2635 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
2636 } else if (Specialization->isStaticDataMember() &&
2637 Specialization->isOutOfLine()) {
2638 Specialization->setAccess(VarTemplate->getAccess());
2641 // Link instantiations of static data members back to the template from
2642 // which they were instantiated.
2643 if (Specialization->isStaticDataMember())
2644 Specialization->setInstantiationOfStaticDataMember(
2645 VarTemplate->getTemplatedDecl(),
2646 Specialization->getSpecializationKind());
2648 return Specialization;
2652 /// \brief A partial specialization whose template arguments have matched
2653 /// a given template-id.
2654 struct PartialSpecMatchResult {
2655 VarTemplatePartialSpecializationDecl *Partial;
2656 TemplateArgumentList *Args;
2661 Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
2662 SourceLocation TemplateNameLoc,
2663 const TemplateArgumentListInfo &TemplateArgs) {
2664 assert(Template && "A variable template id without template?");
2666 // Check that the template argument list is well-formed for this template.
2667 SmallVector<TemplateArgument, 4> Converted;
2668 if (CheckTemplateArgumentList(
2669 Template, TemplateNameLoc,
2670 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
2674 // Find the variable template specialization declaration that
2675 // corresponds to these arguments.
2676 void *InsertPos = nullptr;
2677 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
2678 Converted, InsertPos))
2679 // If we already have a variable template specialization, return it.
2682 // This is the first time we have referenced this variable template
2683 // specialization. Create the canonical declaration and add it to
2684 // the set of specializations, based on the closest partial specialization
2685 // that it represents. That is,
2686 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
2687 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
2688 Converted.data(), Converted.size());
2689 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
2690 bool AmbiguousPartialSpec = false;
2691 typedef PartialSpecMatchResult MatchResult;
2692 SmallVector<MatchResult, 4> Matched;
2693 SourceLocation PointOfInstantiation = TemplateNameLoc;
2694 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
2696 // 1. Attempt to find the closest partial specialization that this
2697 // specializes, if any.
2698 // If any of the template arguments is dependent, then this is probably
2699 // a placeholder for an incomplete declarative context; which must be
2700 // complete by instantiation time. Thus, do not search through the partial
2701 // specializations yet.
2702 // TODO: Unify with InstantiateClassTemplateSpecialization()?
2703 // Perhaps better after unification of DeduceTemplateArguments() and
2704 // getMoreSpecializedPartialSpecialization().
2705 bool InstantiationDependent = false;
2706 if (!TemplateSpecializationType::anyDependentTemplateArguments(
2707 TemplateArgs, InstantiationDependent)) {
2709 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2710 Template->getPartialSpecializations(PartialSpecs);
2712 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2713 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2714 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2716 if (TemplateDeductionResult Result =
2717 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
2718 // Store the failed-deduction information for use in diagnostics, later.
2719 // TODO: Actually use the failed-deduction info?
2720 FailedCandidates.addCandidate()
2721 .set(Partial, MakeDeductionFailureInfo(Context, Result, Info));
2724 Matched.push_back(PartialSpecMatchResult());
2725 Matched.back().Partial = Partial;
2726 Matched.back().Args = Info.take();
2730 if (Matched.size() >= 1) {
2731 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
2732 if (Matched.size() == 1) {
2733 // -- If exactly one matching specialization is found, the
2734 // instantiation is generated from that specialization.
2735 // We don't need to do anything for this.
2737 // -- If more than one matching specialization is found, the
2738 // partial order rules (14.5.4.2) are used to determine
2739 // whether one of the specializations is more specialized
2740 // than the others. If none of the specializations is more
2741 // specialized than all of the other matching
2742 // specializations, then the use of the variable template is
2743 // ambiguous and the program is ill-formed.
2744 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
2745 PEnd = Matched.end();
2747 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2748 PointOfInstantiation) ==
2753 // Determine if the best partial specialization is more specialized than
2755 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2756 PEnd = Matched.end();
2758 if (P != Best && getMoreSpecializedPartialSpecialization(
2759 P->Partial, Best->Partial,
2760 PointOfInstantiation) != Best->Partial) {
2761 AmbiguousPartialSpec = true;
2767 // Instantiate using the best variable template partial specialization.
2768 InstantiationPattern = Best->Partial;
2769 InstantiationArgs = Best->Args;
2771 // -- If no match is found, the instantiation is generated
2772 // from the primary template.
2773 // InstantiationPattern = Template->getTemplatedDecl();
2777 // 2. Create the canonical declaration.
2778 // Note that we do not instantiate the variable just yet, since
2779 // instantiation is handled in DoMarkVarDeclReferenced().
2780 // FIXME: LateAttrs et al.?
2781 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
2782 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
2783 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
2787 if (AmbiguousPartialSpec) {
2788 // Partial ordering did not produce a clear winner. Complain.
2789 Decl->setInvalidDecl();
2790 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2793 // Print the matching partial specializations.
2794 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2795 PEnd = Matched.end();
2797 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2798 << getTemplateArgumentBindingsText(
2799 P->Partial->getTemplateParameters(), *P->Args);
2803 if (VarTemplatePartialSpecializationDecl *D =
2804 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
2805 Decl->setInstantiationOf(D, InstantiationArgs);
2807 assert(Decl && "No variable template specialization?");
2812 Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
2813 const DeclarationNameInfo &NameInfo,
2814 VarTemplateDecl *Template, SourceLocation TemplateLoc,
2815 const TemplateArgumentListInfo *TemplateArgs) {
2817 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
2819 if (Decl.isInvalid())
2822 VarDecl *Var = cast<VarDecl>(Decl.get());
2823 if (!Var->getTemplateSpecializationKind())
2824 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
2827 // Build an ordinary singleton decl ref.
2828 return BuildDeclarationNameExpr(SS, NameInfo, Var,
2829 /*FoundD=*/nullptr, TemplateArgs);
2832 ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
2833 SourceLocation TemplateKWLoc,
2836 const TemplateArgumentListInfo *TemplateArgs) {
2837 // FIXME: Can we do any checking at this point? I guess we could check the
2838 // template arguments that we have against the template name, if the template
2839 // name refers to a single template. That's not a terribly common case,
2841 // foo<int> could identify a single function unambiguously
2842 // This approach does NOT work, since f<int>(1);
2843 // gets resolved prior to resorting to overload resolution
2844 // i.e., template<class T> void f(double);
2845 // vs template<class T, class U> void f(U);
2847 // These should be filtered out by our callers.
2848 assert(!R.empty() && "empty lookup results when building templateid");
2849 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
2851 // In C++1y, check variable template ids.
2852 bool InstantiationDependent;
2853 if (R.getAsSingle<VarTemplateDecl>() &&
2854 !TemplateSpecializationType::anyDependentTemplateArguments(
2855 *TemplateArgs, InstantiationDependent)) {
2856 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
2857 R.getAsSingle<VarTemplateDecl>(),
2858 TemplateKWLoc, TemplateArgs);
2861 // We don't want lookup warnings at this point.
2862 R.suppressDiagnostics();
2864 UnresolvedLookupExpr *ULE
2865 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2866 SS.getWithLocInContext(Context),
2868 R.getLookupNameInfo(),
2869 RequiresADL, TemplateArgs,
2870 R.begin(), R.end());
2875 // We actually only call this from template instantiation.
2877 Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
2878 SourceLocation TemplateKWLoc,
2879 const DeclarationNameInfo &NameInfo,
2880 const TemplateArgumentListInfo *TemplateArgs) {
2882 assert(TemplateArgs || TemplateKWLoc.isValid());
2884 if (!(DC = computeDeclContext(SS, false)) ||
2885 DC->isDependentContext() ||
2886 RequireCompleteDeclContext(SS, DC))
2887 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
2889 bool MemberOfUnknownSpecialization;
2890 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2891 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
2892 MemberOfUnknownSpecialization);
2894 if (R.isAmbiguous())
2898 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
2899 << NameInfo.getName() << SS.getRange();
2903 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
2904 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
2906 << NameInfo.getName().getAsString() << SS.getRange();
2907 Diag(Temp->getLocation(), diag::note_referenced_class_template);
2911 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
2914 /// \brief Form a dependent template name.
2916 /// This action forms a dependent template name given the template
2917 /// name and its (presumably dependent) scope specifier. For
2918 /// example, given "MetaFun::template apply", the scope specifier \p
2919 /// SS will be "MetaFun::", \p TemplateKWLoc contains the location
2920 /// of the "template" keyword, and "apply" is the \p Name.
2921 TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
2923 SourceLocation TemplateKWLoc,
2924 UnqualifiedId &Name,
2925 ParsedType ObjectType,
2926 bool EnteringContext,
2927 TemplateTy &Result) {
2928 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
2930 getLangOpts().CPlusPlus11 ?
2931 diag::warn_cxx98_compat_template_outside_of_template :
2932 diag::ext_template_outside_of_template)
2933 << FixItHint::CreateRemoval(TemplateKWLoc);
2935 DeclContext *LookupCtx = nullptr;
2937 LookupCtx = computeDeclContext(SS, EnteringContext);
2938 if (!LookupCtx && ObjectType)
2939 LookupCtx = computeDeclContext(ObjectType.get());
2941 // C++0x [temp.names]p5:
2942 // If a name prefixed by the keyword template is not the name of
2943 // a template, the program is ill-formed. [Note: the keyword
2944 // template may not be applied to non-template members of class
2945 // templates. -end note ] [ Note: as is the case with the
2946 // typename prefix, the template prefix is allowed in cases
2947 // where it is not strictly necessary; i.e., when the
2948 // nested-name-specifier or the expression on the left of the ->
2949 // or . is not dependent on a template-parameter, or the use
2950 // does not appear in the scope of a template. -end note]
2952 // Note: C++03 was more strict here, because it banned the use of
2953 // the "template" keyword prior to a template-name that was not a
2954 // dependent name. C++ DR468 relaxed this requirement (the
2955 // "template" keyword is now permitted). We follow the C++0x
2956 // rules, even in C++03 mode with a warning, retroactively applying the DR.
2957 bool MemberOfUnknownSpecialization;
2958 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
2959 ObjectType, EnteringContext, Result,
2960 MemberOfUnknownSpecialization);
2961 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
2962 isa<CXXRecordDecl>(LookupCtx) &&
2963 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
2964 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
2965 // This is a dependent template. Handle it below.
2966 } else if (TNK == TNK_Non_template) {
2967 Diag(Name.getLocStart(),
2968 diag::err_template_kw_refers_to_non_template)
2969 << GetNameFromUnqualifiedId(Name).getName()
2970 << Name.getSourceRange()
2972 return TNK_Non_template;
2974 // We found something; return it.
2979 NestedNameSpecifier *Qualifier = SS.getScopeRep();
2981 switch (Name.getKind()) {
2982 case UnqualifiedId::IK_Identifier:
2983 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
2985 return TNK_Dependent_template_name;
2987 case UnqualifiedId::IK_OperatorFunctionId:
2988 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
2989 Name.OperatorFunctionId.Operator));
2990 return TNK_Function_template;
2992 case UnqualifiedId::IK_LiteralOperatorId:
2993 llvm_unreachable("literal operator id cannot have a dependent scope");
2999 Diag(Name.getLocStart(),
3000 diag::err_template_kw_refers_to_non_template)
3001 << GetNameFromUnqualifiedId(Name).getName()
3002 << Name.getSourceRange()
3004 return TNK_Non_template;
3007 bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
3008 TemplateArgumentLoc &AL,
3009 SmallVectorImpl<TemplateArgument> &Converted) {
3010 const TemplateArgument &Arg = AL.getArgument();
3012 TypeSourceInfo *TSI = nullptr;
3014 // Check template type parameter.
3015 switch(Arg.getKind()) {
3016 case TemplateArgument::Type:
3017 // C++ [temp.arg.type]p1:
3018 // A template-argument for a template-parameter which is a
3019 // type shall be a type-id.
3020 ArgType = Arg.getAsType();
3021 TSI = AL.getTypeSourceInfo();
3023 case TemplateArgument::Template: {
3024 // We have a template type parameter but the template argument
3025 // is a template without any arguments.
3026 SourceRange SR = AL.getSourceRange();
3027 TemplateName Name = Arg.getAsTemplate();
3028 Diag(SR.getBegin(), diag::err_template_missing_args)
3030 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3031 Diag(Decl->getLocation(), diag::note_template_decl_here);
3035 case TemplateArgument::Expression: {
3036 // We have a template type parameter but the template argument is an
3037 // expression; see if maybe it is missing the "typename" keyword.
3039 DeclarationNameInfo NameInfo;
3041 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3042 SS.Adopt(ArgExpr->getQualifierLoc());
3043 NameInfo = ArgExpr->getNameInfo();
3044 } else if (DependentScopeDeclRefExpr *ArgExpr =
3045 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3046 SS.Adopt(ArgExpr->getQualifierLoc());
3047 NameInfo = ArgExpr->getNameInfo();
3048 } else if (CXXDependentScopeMemberExpr *ArgExpr =
3049 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
3050 if (ArgExpr->isImplicitAccess()) {
3051 SS.Adopt(ArgExpr->getQualifierLoc());
3052 NameInfo = ArgExpr->getMemberNameInfo();
3056 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
3057 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3058 LookupParsedName(Result, CurScope, &SS);
3060 if (Result.getAsSingle<TypeDecl>() ||
3061 Result.getResultKind() ==
3062 LookupResult::NotFoundInCurrentInstantiation) {
3063 // Suggest that the user add 'typename' before the NNS.
3064 SourceLocation Loc = AL.getSourceRange().getBegin();
3065 Diag(Loc, getLangOpts().MSVCCompat
3066 ? diag::ext_ms_template_type_arg_missing_typename
3067 : diag::err_template_arg_must_be_type_suggest)
3068 << FixItHint::CreateInsertion(Loc, "typename ");
3069 Diag(Param->getLocation(), diag::note_template_param_here);
3071 // Recover by synthesizing a type using the location information that we
3074 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
3076 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
3077 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
3078 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3079 TL.setNameLoc(NameInfo.getLoc());
3080 TSI = TLB.getTypeSourceInfo(Context, ArgType);
3082 // Overwrite our input TemplateArgumentLoc so that we can recover
3084 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
3085 TemplateArgumentLocInfo(TSI));
3093 // We have a template type parameter but the template argument
3095 SourceRange SR = AL.getSourceRange();
3096 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
3097 Diag(Param->getLocation(), diag::note_template_param_here);
3103 if (CheckTemplateArgument(Param, TSI))
3106 // Add the converted template type argument.
3107 ArgType = Context.getCanonicalType(ArgType);
3110 // If an explicitly-specified template argument type is a lifetime type
3111 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
3112 if (getLangOpts().ObjCAutoRefCount &&
3113 ArgType->isObjCLifetimeType() &&
3114 !ArgType.getObjCLifetime()) {
3116 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
3117 ArgType = Context.getQualifiedType(ArgType, Qs);
3120 Converted.push_back(TemplateArgument(ArgType));
3124 /// \brief Substitute template arguments into the default template argument for
3125 /// the given template type parameter.
3127 /// \param SemaRef the semantic analysis object for which we are performing
3128 /// the substitution.
3130 /// \param Template the template that we are synthesizing template arguments
3133 /// \param TemplateLoc the location of the template name that started the
3134 /// template-id we are checking.
3136 /// \param RAngleLoc the location of the right angle bracket ('>') that
3137 /// terminates the template-id.
3139 /// \param Param the template template parameter whose default we are
3140 /// substituting into.
3142 /// \param Converted the list of template arguments provided for template
3143 /// parameters that precede \p Param in the template parameter list.
3144 /// \returns the substituted template argument, or NULL if an error occurred.
3145 static TypeSourceInfo *
3146 SubstDefaultTemplateArgument(Sema &SemaRef,
3147 TemplateDecl *Template,
3148 SourceLocation TemplateLoc,
3149 SourceLocation RAngleLoc,
3150 TemplateTypeParmDecl *Param,
3151 SmallVectorImpl<TemplateArgument> &Converted) {
3152 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
3154 // If the argument type is dependent, instantiate it now based
3155 // on the previously-computed template arguments.
3156 if (ArgType->getType()->isDependentType()) {
3157 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
3158 Template, Converted,
3159 SourceRange(TemplateLoc, RAngleLoc));
3160 if (Inst.isInvalid())
3163 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3164 Converted.data(), Converted.size());
3166 // Only substitute for the innermost template argument list.
3167 MultiLevelTemplateArgumentList TemplateArgLists;
3168 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3169 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3170 TemplateArgLists.addOuterTemplateArguments(None);
3172 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
3174 SemaRef.SubstType(ArgType, TemplateArgLists,
3175 Param->getDefaultArgumentLoc(), Param->getDeclName());
3181 /// \brief Substitute template arguments into the default template argument for
3182 /// the given non-type template parameter.
3184 /// \param SemaRef the semantic analysis object for which we are performing
3185 /// the substitution.
3187 /// \param Template the template that we are synthesizing template arguments
3190 /// \param TemplateLoc the location of the template name that started the
3191 /// template-id we are checking.
3193 /// \param RAngleLoc the location of the right angle bracket ('>') that
3194 /// terminates the template-id.
3196 /// \param Param the non-type template parameter whose default we are
3197 /// substituting into.
3199 /// \param Converted the list of template arguments provided for template
3200 /// parameters that precede \p Param in the template parameter list.
3202 /// \returns the substituted template argument, or NULL if an error occurred.
3204 SubstDefaultTemplateArgument(Sema &SemaRef,
3205 TemplateDecl *Template,
3206 SourceLocation TemplateLoc,
3207 SourceLocation RAngleLoc,
3208 NonTypeTemplateParmDecl *Param,
3209 SmallVectorImpl<TemplateArgument> &Converted) {
3210 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
3211 Template, Converted,
3212 SourceRange(TemplateLoc, RAngleLoc));
3213 if (Inst.isInvalid())
3216 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3217 Converted.data(), Converted.size());
3219 // Only substitute for the innermost template argument list.
3220 MultiLevelTemplateArgumentList TemplateArgLists;
3221 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3222 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3223 TemplateArgLists.addOuterTemplateArguments(None);
3225 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
3226 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
3227 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
3230 /// \brief Substitute template arguments into the default template argument for
3231 /// the given template template parameter.
3233 /// \param SemaRef the semantic analysis object for which we are performing
3234 /// the substitution.
3236 /// \param Template the template that we are synthesizing template arguments
3239 /// \param TemplateLoc the location of the template name that started the
3240 /// template-id we are checking.
3242 /// \param RAngleLoc the location of the right angle bracket ('>') that
3243 /// terminates the template-id.
3245 /// \param Param the template template parameter whose default we are
3246 /// substituting into.
3248 /// \param Converted the list of template arguments provided for template
3249 /// parameters that precede \p Param in the template parameter list.
3251 /// \param QualifierLoc Will be set to the nested-name-specifier (with
3252 /// source-location information) that precedes the template name.
3254 /// \returns the substituted template argument, or NULL if an error occurred.
3256 SubstDefaultTemplateArgument(Sema &SemaRef,
3257 TemplateDecl *Template,
3258 SourceLocation TemplateLoc,
3259 SourceLocation RAngleLoc,
3260 TemplateTemplateParmDecl *Param,
3261 SmallVectorImpl<TemplateArgument> &Converted,
3262 NestedNameSpecifierLoc &QualifierLoc) {
3263 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Template, Converted,
3264 SourceRange(TemplateLoc, RAngleLoc));
3265 if (Inst.isInvalid())
3266 return TemplateName();
3268 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3269 Converted.data(), Converted.size());
3271 // Only substitute for the innermost template argument list.
3272 MultiLevelTemplateArgumentList TemplateArgLists;
3273 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3274 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3275 TemplateArgLists.addOuterTemplateArguments(None);
3277 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
3278 // Substitute into the nested-name-specifier first,
3279 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
3282 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
3284 return TemplateName();
3287 return SemaRef.SubstTemplateName(
3289 Param->getDefaultArgument().getArgument().getAsTemplate(),
3290 Param->getDefaultArgument().getTemplateNameLoc(),
3294 /// \brief If the given template parameter has a default template
3295 /// argument, substitute into that default template argument and
3296 /// return the corresponding template argument.
3298 Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
3299 SourceLocation TemplateLoc,
3300 SourceLocation RAngleLoc,
3302 SmallVectorImpl<TemplateArgument>
3304 bool &HasDefaultArg) {
3305 HasDefaultArg = false;
3307 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
3308 if (!hasVisibleDefaultArgument(TypeParm))
3309 return TemplateArgumentLoc();
3311 HasDefaultArg = true;
3312 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
3318 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3320 return TemplateArgumentLoc();
3323 if (NonTypeTemplateParmDecl *NonTypeParm
3324 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3325 if (!hasVisibleDefaultArgument(NonTypeParm))
3326 return TemplateArgumentLoc();
3328 HasDefaultArg = true;
3329 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
3334 if (Arg.isInvalid())
3335 return TemplateArgumentLoc();
3337 Expr *ArgE = Arg.getAs<Expr>();
3338 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
3341 TemplateTemplateParmDecl *TempTempParm
3342 = cast<TemplateTemplateParmDecl>(Param);
3343 if (!hasVisibleDefaultArgument(TempTempParm))
3344 return TemplateArgumentLoc();
3346 HasDefaultArg = true;
3347 NestedNameSpecifierLoc QualifierLoc;
3348 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
3355 return TemplateArgumentLoc();
3357 return TemplateArgumentLoc(TemplateArgument(TName),
3358 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
3359 TempTempParm->getDefaultArgument().getTemplateNameLoc());
3362 /// \brief Check that the given template argument corresponds to the given
3363 /// template parameter.
3365 /// \param Param The template parameter against which the argument will be
3368 /// \param Arg The template argument, which may be updated due to conversions.
3370 /// \param Template The template in which the template argument resides.
3372 /// \param TemplateLoc The location of the template name for the template
3373 /// whose argument list we're matching.
3375 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
3376 /// the template argument list.
3378 /// \param ArgumentPackIndex The index into the argument pack where this
3379 /// argument will be placed. Only valid if the parameter is a parameter pack.
3381 /// \param Converted The checked, converted argument will be added to the
3382 /// end of this small vector.
3384 /// \param CTAK Describes how we arrived at this particular template argument:
3385 /// explicitly written, deduced, etc.
3387 /// \returns true on error, false otherwise.
3388 bool Sema::CheckTemplateArgument(NamedDecl *Param,
3389 TemplateArgumentLoc &Arg,
3390 NamedDecl *Template,
3391 SourceLocation TemplateLoc,
3392 SourceLocation RAngleLoc,
3393 unsigned ArgumentPackIndex,
3394 SmallVectorImpl<TemplateArgument> &Converted,
3395 CheckTemplateArgumentKind CTAK) {
3396 // Check template type parameters.
3397 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3398 return CheckTemplateTypeArgument(TTP, Arg, Converted);
3400 // Check non-type template parameters.
3401 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3402 // Do substitution on the type of the non-type template parameter
3403 // with the template arguments we've seen thus far. But if the
3404 // template has a dependent context then we cannot substitute yet.
3405 QualType NTTPType = NTTP->getType();
3406 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
3407 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
3409 if (NTTPType->isDependentType() &&
3410 !isa<TemplateTemplateParmDecl>(Template) &&
3411 !Template->getDeclContext()->isDependentContext()) {
3412 // Do substitution on the type of the non-type template parameter.
3413 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
3415 SourceRange(TemplateLoc, RAngleLoc));
3416 if (Inst.isInvalid())
3419 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3420 Converted.data(), Converted.size());
3421 NTTPType = SubstType(NTTPType,
3422 MultiLevelTemplateArgumentList(TemplateArgs),
3423 NTTP->getLocation(),
3424 NTTP->getDeclName());
3425 // If that worked, check the non-type template parameter type
3427 if (!NTTPType.isNull())
3428 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
3429 NTTP->getLocation());
3430 if (NTTPType.isNull())
3434 switch (Arg.getArgument().getKind()) {
3435 case TemplateArgument::Null:
3436 llvm_unreachable("Should never see a NULL template argument here");
3438 case TemplateArgument::Expression: {
3439 TemplateArgument Result;
3441 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
3443 if (Res.isInvalid())
3446 // If the resulting expression is new, then use it in place of the
3447 // old expression in the template argument.
3448 if (Res.get() != Arg.getArgument().getAsExpr()) {
3449 TemplateArgument TA(Res.get());
3450 Arg = TemplateArgumentLoc(TA, Res.get());
3453 Converted.push_back(Result);
3457 case TemplateArgument::Declaration:
3458 case TemplateArgument::Integral:
3459 case TemplateArgument::NullPtr:
3460 // We've already checked this template argument, so just copy
3461 // it to the list of converted arguments.
3462 Converted.push_back(Arg.getArgument());
3465 case TemplateArgument::Template:
3466 case TemplateArgument::TemplateExpansion:
3467 // We were given a template template argument. It may not be ill-formed;
3469 if (DependentTemplateName *DTN
3470 = Arg.getArgument().getAsTemplateOrTemplatePattern()
3471 .getAsDependentTemplateName()) {
3472 // We have a template argument such as \c T::template X, which we
3473 // parsed as a template template argument. However, since we now
3474 // know that we need a non-type template argument, convert this
3475 // template name into an expression.
3477 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
3478 Arg.getTemplateNameLoc());
3481 SS.Adopt(Arg.getTemplateQualifierLoc());
3482 // FIXME: the template-template arg was a DependentTemplateName,
3483 // so it was provided with a template keyword. However, its source
3484 // location is not stored in the template argument structure.
3485 SourceLocation TemplateKWLoc;
3486 ExprResult E = DependentScopeDeclRefExpr::Create(
3487 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
3490 // If we parsed the template argument as a pack expansion, create a
3491 // pack expansion expression.
3492 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
3493 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
3498 TemplateArgument Result;
3499 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
3503 Converted.push_back(Result);
3507 // We have a template argument that actually does refer to a class
3508 // template, alias template, or template template parameter, and
3509 // therefore cannot be a non-type template argument.
3510 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
3511 << Arg.getSourceRange();
3513 Diag(Param->getLocation(), diag::note_template_param_here);
3516 case TemplateArgument::Type: {
3517 // We have a non-type template parameter but the template
3518 // argument is a type.
3520 // C++ [temp.arg]p2:
3521 // In a template-argument, an ambiguity between a type-id and
3522 // an expression is resolved to a type-id, regardless of the
3523 // form of the corresponding template-parameter.
3525 // We warn specifically about this case, since it can be rather
3526 // confusing for users.
3527 QualType T = Arg.getArgument().getAsType();
3528 SourceRange SR = Arg.getSourceRange();
3529 if (T->isFunctionType())
3530 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
3532 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
3533 Diag(Param->getLocation(), diag::note_template_param_here);
3537 case TemplateArgument::Pack:
3538 llvm_unreachable("Caller must expand template argument packs");
3545 // Check template template parameters.
3546 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
3548 // Substitute into the template parameter list of the template
3549 // template parameter, since previously-supplied template arguments
3550 // may appear within the template template parameter.
3552 // Set up a template instantiation context.
3553 LocalInstantiationScope Scope(*this);
3554 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
3555 TempParm, Converted,
3556 SourceRange(TemplateLoc, RAngleLoc));
3557 if (Inst.isInvalid())
3560 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3561 Converted.data(), Converted.size());
3562 TempParm = cast_or_null<TemplateTemplateParmDecl>(
3563 SubstDecl(TempParm, CurContext,
3564 MultiLevelTemplateArgumentList(TemplateArgs)));
3569 switch (Arg.getArgument().getKind()) {
3570 case TemplateArgument::Null:
3571 llvm_unreachable("Should never see a NULL template argument here");
3573 case TemplateArgument::Template:
3574 case TemplateArgument::TemplateExpansion:
3575 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
3578 Converted.push_back(Arg.getArgument());
3581 case TemplateArgument::Expression:
3582 case TemplateArgument::Type:
3583 // We have a template template parameter but the template
3584 // argument does not refer to a template.
3585 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
3586 << getLangOpts().CPlusPlus11;
3589 case TemplateArgument::Declaration:
3590 llvm_unreachable("Declaration argument with template template parameter");
3591 case TemplateArgument::Integral:
3592 llvm_unreachable("Integral argument with template template parameter");
3593 case TemplateArgument::NullPtr:
3594 llvm_unreachable("Null pointer argument with template template parameter");
3596 case TemplateArgument::Pack:
3597 llvm_unreachable("Caller must expand template argument packs");
3603 /// \brief Diagnose an arity mismatch in the
3604 static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
3605 SourceLocation TemplateLoc,
3606 TemplateArgumentListInfo &TemplateArgs) {
3607 TemplateParameterList *Params = Template->getTemplateParameters();
3608 unsigned NumParams = Params->size();
3609 unsigned NumArgs = TemplateArgs.size();
3612 if (NumArgs > NumParams)
3613 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
3614 TemplateArgs.getRAngleLoc());
3615 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3616 << (NumArgs > NumParams)
3617 << (isa<ClassTemplateDecl>(Template)? 0 :
3618 isa<FunctionTemplateDecl>(Template)? 1 :
3619 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3620 << Template << Range;
3621 S.Diag(Template->getLocation(), diag::note_template_decl_here)
3622 << Params->getSourceRange();
3626 /// \brief Check whether the template parameter is a pack expansion, and if so,
3627 /// determine the number of parameters produced by that expansion. For instance:
3630 /// template<typename ...Ts> struct A {
3631 /// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
3635 /// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
3636 /// is not a pack expansion, so returns an empty Optional.
3637 static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
3638 if (NonTypeTemplateParmDecl *NTTP
3639 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3640 if (NTTP->isExpandedParameterPack())
3641 return NTTP->getNumExpansionTypes();
3644 if (TemplateTemplateParmDecl *TTP
3645 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3646 if (TTP->isExpandedParameterPack())
3647 return TTP->getNumExpansionTemplateParameters();
3653 /// Diagnose a missing template argument.
3654 template<typename TemplateParmDecl>
3655 static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
3657 const TemplateParmDecl *D,
3658 TemplateArgumentListInfo &Args) {
3659 // Dig out the most recent declaration of the template parameter; there may be
3660 // declarations of the template that are more recent than TD.
3661 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
3662 ->getTemplateParameters()
3663 ->getParam(D->getIndex()));
3665 // If there's a default argument that's not visible, diagnose that we're
3666 // missing a module import.
3667 llvm::SmallVector<Module*, 8> Modules;
3668 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
3669 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
3670 D->getDefaultArgumentLoc(), Modules,
3671 Sema::MissingImportKind::DefaultArgument,
3676 // FIXME: If there's a more recent default argument that *is* visible,
3677 // diagnose that it was declared too late.
3679 return diagnoseArityMismatch(S, TD, Loc, Args);
3682 /// \brief Check that the given template argument list is well-formed
3683 /// for specializing the given template.
3684 bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
3685 SourceLocation TemplateLoc,
3686 TemplateArgumentListInfo &TemplateArgs,
3687 bool PartialTemplateArgs,
3688 SmallVectorImpl<TemplateArgument> &Converted) {
3689 // Make a copy of the template arguments for processing. Only make the
3690 // changes at the end when successful in matching the arguments to the
3692 TemplateArgumentListInfo NewArgs = TemplateArgs;
3694 TemplateParameterList *Params = Template->getTemplateParameters();
3696 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
3698 // C++ [temp.arg]p1:
3699 // [...] The type and form of each template-argument specified in
3700 // a template-id shall match the type and form specified for the
3701 // corresponding parameter declared by the template in its
3702 // template-parameter-list.
3703 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
3704 SmallVector<TemplateArgument, 2> ArgumentPack;
3705 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
3706 LocalInstantiationScope InstScope(*this, true);
3707 for (TemplateParameterList::iterator Param = Params->begin(),
3708 ParamEnd = Params->end();
3709 Param != ParamEnd; /* increment in loop */) {
3710 // If we have an expanded parameter pack, make sure we don't have too
3712 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
3713 if (*Expansions == ArgumentPack.size()) {
3714 // We're done with this parameter pack. Pack up its arguments and add
3715 // them to the list.
3716 Converted.push_back(
3717 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
3718 ArgumentPack.clear();
3720 // This argument is assigned to the next parameter.
3723 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
3724 // Not enough arguments for this parameter pack.
3725 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3727 << (isa<ClassTemplateDecl>(Template)? 0 :
3728 isa<FunctionTemplateDecl>(Template)? 1 :
3729 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3731 Diag(Template->getLocation(), diag::note_template_decl_here)
3732 << Params->getSourceRange();
3737 if (ArgIdx < NumArgs) {
3738 // Check the template argument we were given.
3739 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
3740 TemplateLoc, RAngleLoc,
3741 ArgumentPack.size(), Converted))
3744 bool PackExpansionIntoNonPack =
3745 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
3746 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
3747 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
3748 // Core issue 1430: we have a pack expansion as an argument to an
3749 // alias template, and it's not part of a parameter pack. This
3750 // can't be canonicalized, so reject it now.
3751 Diag(NewArgs[ArgIdx].getLocation(),
3752 diag::err_alias_template_expansion_into_fixed_list)
3753 << NewArgs[ArgIdx].getSourceRange();
3754 Diag((*Param)->getLocation(), diag::note_template_param_here);
3758 // We're now done with this argument.
3761 if ((*Param)->isTemplateParameterPack()) {
3762 // The template parameter was a template parameter pack, so take the
3763 // deduced argument and place it on the argument pack. Note that we
3764 // stay on the same template parameter so that we can deduce more
3766 ArgumentPack.push_back(Converted.pop_back_val());
3768 // Move to the next template parameter.
3772 // If we just saw a pack expansion into a non-pack, then directly convert
3773 // the remaining arguments, because we don't know what parameters they'll
3775 if (PackExpansionIntoNonPack) {
3776 if (!ArgumentPack.empty()) {
3777 // If we were part way through filling in an expanded parameter pack,
3778 // fall back to just producing individual arguments.
3779 Converted.insert(Converted.end(),
3780 ArgumentPack.begin(), ArgumentPack.end());
3781 ArgumentPack.clear();
3784 while (ArgIdx < NumArgs) {
3785 Converted.push_back(NewArgs[ArgIdx].getArgument());
3795 // If we're checking a partial template argument list, we're done.
3796 if (PartialTemplateArgs) {
3797 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
3798 Converted.push_back(
3799 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
3804 // If we have a template parameter pack with no more corresponding
3805 // arguments, just break out now and we'll fill in the argument pack below.
3806 if ((*Param)->isTemplateParameterPack()) {
3807 assert(!getExpandedPackSize(*Param) &&
3808 "Should have dealt with this already");
3810 // A non-expanded parameter pack before the end of the parameter list
3811 // only occurs for an ill-formed template parameter list, unless we've
3812 // got a partial argument list for a function template, so just bail out.
3813 if (Param + 1 != ParamEnd)
3816 Converted.push_back(
3817 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
3818 ArgumentPack.clear();
3824 // Check whether we have a default argument.
3825 TemplateArgumentLoc Arg;
3827 // Retrieve the default template argument from the template
3828 // parameter. For each kind of template parameter, we substitute the
3829 // template arguments provided thus far and any "outer" template arguments
3830 // (when the template parameter was part of a nested template) into
3831 // the default argument.
3832 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
3833 if (!hasVisibleDefaultArgument(TTP))
3834 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
3837 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
3846 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
3848 } else if (NonTypeTemplateParmDecl *NTTP
3849 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
3850 if (!hasVisibleDefaultArgument(NTTP))
3851 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
3854 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
3862 Expr *Ex = E.getAs<Expr>();
3863 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
3865 TemplateTemplateParmDecl *TempParm
3866 = cast<TemplateTemplateParmDecl>(*Param);
3868 if (!hasVisibleDefaultArgument(TempParm))
3869 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
3872 NestedNameSpecifierLoc QualifierLoc;
3873 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
3882 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
3883 TempParm->getDefaultArgument().getTemplateNameLoc());
3886 // Introduce an instantiation record that describes where we are using
3887 // the default template argument.
3888 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
3889 SourceRange(TemplateLoc, RAngleLoc));
3890 if (Inst.isInvalid())
3893 // Check the default template argument.
3894 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
3895 RAngleLoc, 0, Converted))
3898 // Core issue 150 (assumed resolution): if this is a template template
3899 // parameter, keep track of the default template arguments from the
3900 // template definition.
3901 if (isTemplateTemplateParameter)
3902 NewArgs.addArgument(Arg);
3904 // Move to the next template parameter and argument.
3909 // If we're performing a partial argument substitution, allow any trailing
3910 // pack expansions; they might be empty. This can happen even if
3911 // PartialTemplateArgs is false (the list of arguments is complete but
3912 // still dependent).
3913 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
3914 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
3915 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
3916 Converted.push_back(NewArgs[ArgIdx++].getArgument());
3919 // If we have any leftover arguments, then there were too many arguments.
3920 // Complain and fail.
3921 if (ArgIdx < NumArgs)
3922 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
3924 // No problems found with the new argument list, propagate changes back
3926 TemplateArgs = NewArgs;
3932 class UnnamedLocalNoLinkageFinder
3933 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
3938 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
3941 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
3943 bool Visit(QualType T) {
3944 return inherited::Visit(T.getTypePtr());
3947 #define TYPE(Class, Parent) \
3948 bool Visit##Class##Type(const Class##Type *);
3949 #define ABSTRACT_TYPE(Class, Parent) \
3950 bool Visit##Class##Type(const Class##Type *) { return false; }
3951 #define NON_CANONICAL_TYPE(Class, Parent) \
3952 bool Visit##Class##Type(const Class##Type *) { return false; }
3953 #include "clang/AST/TypeNodes.def"
3955 bool VisitTagDecl(const TagDecl *Tag);
3956 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
3960 bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
3964 bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
3965 return Visit(T->getElementType());
3968 bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
3969 return Visit(T->getPointeeType());
3972 bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
3973 const BlockPointerType* T) {
3974 return Visit(T->getPointeeType());
3977 bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
3978 const LValueReferenceType* T) {
3979 return Visit(T->getPointeeType());
3982 bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
3983 const RValueReferenceType* T) {
3984 return Visit(T->getPointeeType());
3987 bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
3988 const MemberPointerType* T) {
3989 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
3992 bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
3993 const ConstantArrayType* T) {
3994 return Visit(T->getElementType());
3997 bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
3998 const IncompleteArrayType* T) {
3999 return Visit(T->getElementType());
4002 bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
4003 const VariableArrayType* T) {
4004 return Visit(T->getElementType());
4007 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
4008 const DependentSizedArrayType* T) {
4009 return Visit(T->getElementType());
4012 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
4013 const DependentSizedExtVectorType* T) {
4014 return Visit(T->getElementType());
4017 bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
4018 return Visit(T->getElementType());
4021 bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
4022 return Visit(T->getElementType());
4025 bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
4026 const FunctionProtoType* T) {
4027 for (const auto &A : T->param_types()) {
4032 return Visit(T->getReturnType());
4035 bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
4036 const FunctionNoProtoType* T) {
4037 return Visit(T->getReturnType());
4040 bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
4041 const UnresolvedUsingType*) {
4045 bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
4049 bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
4050 return Visit(T->getUnderlyingType());
4053 bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
4057 bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
4058 const UnaryTransformType*) {
4062 bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
4063 return Visit(T->getDeducedType());
4066 bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
4067 return VisitTagDecl(T->getDecl());
4070 bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
4071 return VisitTagDecl(T->getDecl());
4074 bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
4075 const TemplateTypeParmType*) {
4079 bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
4080 const SubstTemplateTypeParmPackType *) {
4084 bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
4085 const TemplateSpecializationType*) {
4089 bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
4090 const InjectedClassNameType* T) {
4091 return VisitTagDecl(T->getDecl());
4094 bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
4095 const DependentNameType* T) {
4096 return VisitNestedNameSpecifier(T->getQualifier());
4099 bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
4100 const DependentTemplateSpecializationType* T) {
4101 return VisitNestedNameSpecifier(T->getQualifier());
4104 bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
4105 const PackExpansionType* T) {
4106 return Visit(T->getPattern());
4109 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
4113 bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
4114 const ObjCInterfaceType *) {
4118 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
4119 const ObjCObjectPointerType *) {
4123 bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
4124 return Visit(T->getValueType());
4127 bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
4128 if (Tag->getDeclContext()->isFunctionOrMethod()) {
4129 S.Diag(SR.getBegin(),
4130 S.getLangOpts().CPlusPlus11 ?
4131 diag::warn_cxx98_compat_template_arg_local_type :
4132 diag::ext_template_arg_local_type)
4133 << S.Context.getTypeDeclType(Tag) << SR;
4137 if (!Tag->hasNameForLinkage()) {
4138 S.Diag(SR.getBegin(),
4139 S.getLangOpts().CPlusPlus11 ?
4140 diag::warn_cxx98_compat_template_arg_unnamed_type :
4141 diag::ext_template_arg_unnamed_type) << SR;
4142 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
4149 bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
4150 NestedNameSpecifier *NNS) {
4151 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
4154 switch (NNS->getKind()) {
4155 case NestedNameSpecifier::Identifier:
4156 case NestedNameSpecifier::Namespace:
4157 case NestedNameSpecifier::NamespaceAlias:
4158 case NestedNameSpecifier::Global:
4159 case NestedNameSpecifier::Super:
4162 case NestedNameSpecifier::TypeSpec:
4163 case NestedNameSpecifier::TypeSpecWithTemplate:
4164 return Visit(QualType(NNS->getAsType(), 0));
4166 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
4170 /// \brief Check a template argument against its corresponding
4171 /// template type parameter.
4173 /// This routine implements the semantics of C++ [temp.arg.type]. It
4174 /// returns true if an error occurred, and false otherwise.
4175 bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
4176 TypeSourceInfo *ArgInfo) {
4177 assert(ArgInfo && "invalid TypeSourceInfo");
4178 QualType Arg = ArgInfo->getType();
4179 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
4181 if (Arg->isVariablyModifiedType()) {
4182 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
4183 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
4184 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
4187 // C++03 [temp.arg.type]p2:
4188 // A local type, a type with no linkage, an unnamed type or a type
4189 // compounded from any of these types shall not be used as a
4190 // template-argument for a template type-parameter.
4192 // C++11 allows these, and even in C++03 we allow them as an extension with
4195 if (LangOpts.CPlusPlus11)
4197 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_unnamed_type,
4199 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_local_type,
4202 NeedsCheck = Arg->hasUnnamedOrLocalType();
4205 UnnamedLocalNoLinkageFinder Finder(*this, SR);
4206 (void)Finder.Visit(Context.getCanonicalType(Arg));
4212 enum NullPointerValueKind {
4218 /// \brief Determine whether the given template argument is a null pointer
4219 /// value of the appropriate type.
4220 static NullPointerValueKind
4221 isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
4222 QualType ParamType, Expr *Arg) {
4223 if (Arg->isValueDependent() || Arg->isTypeDependent())
4224 return NPV_NotNullPointer;
4226 if (!S.getLangOpts().CPlusPlus11)
4227 return NPV_NotNullPointer;
4229 // Determine whether we have a constant expression.
4230 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
4231 if (ArgRV.isInvalid())
4235 Expr::EvalResult EvalResult;
4236 SmallVector<PartialDiagnosticAt, 8> Notes;
4237 EvalResult.Diag = &Notes;
4238 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
4239 EvalResult.HasSideEffects) {
4240 SourceLocation DiagLoc = Arg->getExprLoc();
4242 // If our only note is the usual "invalid subexpression" note, just point
4243 // the caret at its location rather than producing an essentially
4245 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
4246 diag::note_invalid_subexpr_in_const_expr) {
4247 DiagLoc = Notes[0].first;
4251 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
4252 << Arg->getType() << Arg->getSourceRange();
4253 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
4254 S.Diag(Notes[I].first, Notes[I].second);
4256 S.Diag(Param->getLocation(), diag::note_template_param_here);
4260 // C++11 [temp.arg.nontype]p1:
4261 // - an address constant expression of type std::nullptr_t
4262 if (Arg->getType()->isNullPtrType())
4263 return NPV_NullPointer;
4265 // - a constant expression that evaluates to a null pointer value (4.10); or
4266 // - a constant expression that evaluates to a null member pointer value
4268 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
4269 (EvalResult.Val.isMemberPointer() &&
4270 !EvalResult.Val.getMemberPointerDecl())) {
4271 // If our expression has an appropriate type, we've succeeded.
4272 bool ObjCLifetimeConversion;
4273 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
4274 S.IsQualificationConversion(Arg->getType(), ParamType, false,
4275 ObjCLifetimeConversion))
4276 return NPV_NullPointer;
4278 // The types didn't match, but we know we got a null pointer; complain,
4279 // then recover as if the types were correct.
4280 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
4281 << Arg->getType() << ParamType << Arg->getSourceRange();
4282 S.Diag(Param->getLocation(), diag::note_template_param_here);
4283 return NPV_NullPointer;
4286 // If we don't have a null pointer value, but we do have a NULL pointer
4287 // constant, suggest a cast to the appropriate type.
4288 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
4289 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
4290 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
4291 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
4292 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
4294 S.Diag(Param->getLocation(), diag::note_template_param_here);
4295 return NPV_NullPointer;
4298 // FIXME: If we ever want to support general, address-constant expressions
4299 // as non-type template arguments, we should return the ExprResult here to
4300 // be interpreted by the caller.
4301 return NPV_NotNullPointer;
4304 /// \brief Checks whether the given template argument is compatible with its
4305 /// template parameter.
4306 static bool CheckTemplateArgumentIsCompatibleWithParameter(
4307 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
4308 Expr *Arg, QualType ArgType) {
4309 bool ObjCLifetimeConversion;
4310 if (ParamType->isPointerType() &&
4311 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
4312 S.IsQualificationConversion(ArgType, ParamType, false,
4313 ObjCLifetimeConversion)) {
4314 // For pointer-to-object types, qualification conversions are
4317 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
4318 if (!ParamRef->getPointeeType()->isFunctionType()) {
4319 // C++ [temp.arg.nontype]p5b3:
4320 // For a non-type template-parameter of type reference to
4321 // object, no conversions apply. The type referred to by the
4322 // reference may be more cv-qualified than the (otherwise
4323 // identical) type of the template- argument. The
4324 // template-parameter is bound directly to the
4325 // template-argument, which shall be an lvalue.
4327 // FIXME: Other qualifiers?
4328 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
4329 unsigned ArgQuals = ArgType.getCVRQualifiers();
4331 if ((ParamQuals | ArgQuals) != ParamQuals) {
4332 S.Diag(Arg->getLocStart(),
4333 diag::err_template_arg_ref_bind_ignores_quals)
4334 << ParamType << Arg->getType() << Arg->getSourceRange();
4335 S.Diag(Param->getLocation(), diag::note_template_param_here);
4341 // At this point, the template argument refers to an object or
4342 // function with external linkage. We now need to check whether the
4343 // argument and parameter types are compatible.
4344 if (!S.Context.hasSameUnqualifiedType(ArgType,
4345 ParamType.getNonReferenceType())) {
4346 // We can't perform this conversion or binding.
4347 if (ParamType->isReferenceType())
4348 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
4349 << ParamType << ArgIn->getType() << Arg->getSourceRange();
4351 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4352 << ArgIn->getType() << ParamType << Arg->getSourceRange();
4353 S.Diag(Param->getLocation(), diag::note_template_param_here);
4361 /// \brief Checks whether the given template argument is the address
4362 /// of an object or function according to C++ [temp.arg.nontype]p1.
4364 CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
4365 NonTypeTemplateParmDecl *Param,
4368 TemplateArgument &Converted) {
4369 bool Invalid = false;
4371 QualType ArgType = Arg->getType();
4373 bool AddressTaken = false;
4374 SourceLocation AddrOpLoc;
4375 if (S.getLangOpts().MicrosoftExt) {
4376 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
4377 // dereference and address-of operators.
4378 Arg = Arg->IgnoreParenCasts();
4380 bool ExtWarnMSTemplateArg = false;
4381 UnaryOperatorKind FirstOpKind;
4382 SourceLocation FirstOpLoc;
4383 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4384 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
4385 if (UnOpKind == UO_Deref)
4386 ExtWarnMSTemplateArg = true;
4387 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
4388 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
4389 if (!AddrOpLoc.isValid()) {
4390 FirstOpKind = UnOpKind;
4391 FirstOpLoc = UnOp->getOperatorLoc();
4396 if (FirstOpLoc.isValid()) {
4397 if (ExtWarnMSTemplateArg)
4398 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
4399 << ArgIn->getSourceRange();
4401 if (FirstOpKind == UO_AddrOf)
4402 AddressTaken = true;
4403 else if (Arg->getType()->isPointerType()) {
4404 // We cannot let pointers get dereferenced here, that is obviously not a
4405 // constant expression.
4406 assert(FirstOpKind == UO_Deref);
4407 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4408 << Arg->getSourceRange();
4412 // See through any implicit casts we added to fix the type.
4413 Arg = Arg->IgnoreImpCasts();
4415 // C++ [temp.arg.nontype]p1:
4417 // A template-argument for a non-type, non-template
4418 // template-parameter shall be one of: [...]
4420 // -- the address of an object or function with external
4421 // linkage, including function templates and function
4422 // template-ids but excluding non-static class members,
4423 // expressed as & id-expression where the & is optional if
4424 // the name refers to a function or array, or if the
4425 // corresponding template-parameter is a reference; or
4427 // In C++98/03 mode, give an extension warning on any extra parentheses.
4428 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4429 bool ExtraParens = false;
4430 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4431 if (!Invalid && !ExtraParens) {
4432 S.Diag(Arg->getLocStart(),
4433 S.getLangOpts().CPlusPlus11
4434 ? diag::warn_cxx98_compat_template_arg_extra_parens
4435 : diag::ext_template_arg_extra_parens)
4436 << Arg->getSourceRange();
4440 Arg = Parens->getSubExpr();
4443 while (SubstNonTypeTemplateParmExpr *subst =
4444 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4445 Arg = subst->getReplacement()->IgnoreImpCasts();
4447 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4448 if (UnOp->getOpcode() == UO_AddrOf) {
4449 Arg = UnOp->getSubExpr();
4450 AddressTaken = true;
4451 AddrOpLoc = UnOp->getOperatorLoc();
4455 while (SubstNonTypeTemplateParmExpr *subst =
4456 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4457 Arg = subst->getReplacement()->IgnoreImpCasts();
4460 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
4461 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
4463 // If our parameter has pointer type, check for a null template value.
4464 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
4465 NullPointerValueKind NPV;
4466 // dllimport'd entities aren't constant but are available inside of template
4468 if (Entity && Entity->hasAttr<DLLImportAttr>())
4469 NPV = NPV_NotNullPointer;
4471 NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
4473 case NPV_NullPointer:
4474 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
4475 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4476 /*isNullPtr=*/true);
4482 case NPV_NotNullPointer:
4487 // Stop checking the precise nature of the argument if it is value dependent,
4488 // it should be checked when instantiated.
4489 if (Arg->isValueDependent()) {
4490 Converted = TemplateArgument(ArgIn);
4494 if (isa<CXXUuidofExpr>(Arg)) {
4495 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
4496 ArgIn, Arg, ArgType))
4499 Converted = TemplateArgument(ArgIn);
4504 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4505 << Arg->getSourceRange();
4506 S.Diag(Param->getLocation(), diag::note_template_param_here);
4510 // Cannot refer to non-static data members
4511 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
4512 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
4513 << Entity << Arg->getSourceRange();
4514 S.Diag(Param->getLocation(), diag::note_template_param_here);
4518 // Cannot refer to non-static member functions
4519 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
4520 if (!Method->isStatic()) {
4521 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
4522 << Method << Arg->getSourceRange();
4523 S.Diag(Param->getLocation(), diag::note_template_param_here);
4528 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
4529 VarDecl *Var = dyn_cast<VarDecl>(Entity);
4531 // A non-type template argument must refer to an object or function.
4532 if (!Func && !Var) {
4533 // We found something, but we don't know specifically what it is.
4534 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
4535 << Arg->getSourceRange();
4536 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4540 // Address / reference template args must have external linkage in C++98.
4541 if (Entity->getFormalLinkage() == InternalLinkage) {
4542 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
4543 diag::warn_cxx98_compat_template_arg_object_internal :
4544 diag::ext_template_arg_object_internal)
4545 << !Func << Entity << Arg->getSourceRange();
4546 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4548 } else if (!Entity->hasLinkage()) {
4549 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
4550 << !Func << Entity << Arg->getSourceRange();
4551 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4557 // If the template parameter has pointer type, the function decays.
4558 if (ParamType->isPointerType() && !AddressTaken)
4559 ArgType = S.Context.getPointerType(Func->getType());
4560 else if (AddressTaken && ParamType->isReferenceType()) {
4561 // If we originally had an address-of operator, but the
4562 // parameter has reference type, complain and (if things look
4563 // like they will work) drop the address-of operator.
4564 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
4565 ParamType.getNonReferenceType())) {
4566 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4568 S.Diag(Param->getLocation(), diag::note_template_param_here);
4572 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4574 << FixItHint::CreateRemoval(AddrOpLoc);
4575 S.Diag(Param->getLocation(), diag::note_template_param_here);
4577 ArgType = Func->getType();
4580 // A value of reference type is not an object.
4581 if (Var->getType()->isReferenceType()) {
4582 S.Diag(Arg->getLocStart(),
4583 diag::err_template_arg_reference_var)
4584 << Var->getType() << Arg->getSourceRange();
4585 S.Diag(Param->getLocation(), diag::note_template_param_here);
4589 // A template argument must have static storage duration.
4590 if (Var->getTLSKind()) {
4591 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
4592 << Arg->getSourceRange();
4593 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
4597 // If the template parameter has pointer type, we must have taken
4598 // the address of this object.
4599 if (ParamType->isReferenceType()) {
4601 // If we originally had an address-of operator, but the
4602 // parameter has reference type, complain and (if things look
4603 // like they will work) drop the address-of operator.
4604 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
4605 ParamType.getNonReferenceType())) {
4606 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4608 S.Diag(Param->getLocation(), diag::note_template_param_here);
4612 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4614 << FixItHint::CreateRemoval(AddrOpLoc);
4615 S.Diag(Param->getLocation(), diag::note_template_param_here);
4617 ArgType = Var->getType();
4619 } else if (!AddressTaken && ParamType->isPointerType()) {
4620 if (Var->getType()->isArrayType()) {
4621 // Array-to-pointer decay.
4622 ArgType = S.Context.getArrayDecayedType(Var->getType());
4624 // If the template parameter has pointer type but the address of
4625 // this object was not taken, complain and (possibly) recover by
4626 // taking the address of the entity.
4627 ArgType = S.Context.getPointerType(Var->getType());
4628 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
4629 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4631 S.Diag(Param->getLocation(), diag::note_template_param_here);
4635 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4637 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
4639 S.Diag(Param->getLocation(), diag::note_template_param_here);
4644 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
4648 // Create the template argument.
4650 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
4651 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
4655 /// \brief Checks whether the given template argument is a pointer to
4656 /// member constant according to C++ [temp.arg.nontype]p1.
4657 static bool CheckTemplateArgumentPointerToMember(Sema &S,
4658 NonTypeTemplateParmDecl *Param,
4661 TemplateArgument &Converted) {
4662 bool Invalid = false;
4664 // Check for a null pointer value.
4665 Expr *Arg = ResultArg;
4666 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
4669 case NPV_NullPointer:
4670 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
4671 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4673 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft())
4674 S.RequireCompleteType(Arg->getExprLoc(), ParamType, 0);
4676 case NPV_NotNullPointer:
4680 bool ObjCLifetimeConversion;
4681 if (S.IsQualificationConversion(Arg->getType(),
4682 ParamType.getNonReferenceType(),
4683 false, ObjCLifetimeConversion)) {
4684 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
4685 Arg->getValueKind()).get();
4687 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
4688 ParamType.getNonReferenceType())) {
4689 // We can't perform this conversion.
4690 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4691 << Arg->getType() << ParamType << Arg->getSourceRange();
4692 S.Diag(Param->getLocation(), diag::note_template_param_here);
4696 // See through any implicit casts we added to fix the type.
4697 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
4698 Arg = Cast->getSubExpr();
4700 // C++ [temp.arg.nontype]p1:
4702 // A template-argument for a non-type, non-template
4703 // template-parameter shall be one of: [...]
4705 // -- a pointer to member expressed as described in 5.3.1.
4706 DeclRefExpr *DRE = nullptr;
4708 // In C++98/03 mode, give an extension warning on any extra parentheses.
4709 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4710 bool ExtraParens = false;
4711 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4712 if (!Invalid && !ExtraParens) {
4713 S.Diag(Arg->getLocStart(),
4714 S.getLangOpts().CPlusPlus11 ?
4715 diag::warn_cxx98_compat_template_arg_extra_parens :
4716 diag::ext_template_arg_extra_parens)
4717 << Arg->getSourceRange();
4721 Arg = Parens->getSubExpr();
4724 while (SubstNonTypeTemplateParmExpr *subst =
4725 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4726 Arg = subst->getReplacement()->IgnoreImpCasts();
4728 // A pointer-to-member constant written &Class::member.
4729 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4730 if (UnOp->getOpcode() == UO_AddrOf) {
4731 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
4732 if (DRE && !DRE->getQualifier())
4736 // A constant of pointer-to-member type.
4737 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
4738 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
4739 if (VD->getType()->isMemberPointerType()) {
4740 if (isa<NonTypeTemplateParmDecl>(VD)) {
4741 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
4742 Converted = TemplateArgument(Arg);
4744 VD = cast<ValueDecl>(VD->getCanonicalDecl());
4745 Converted = TemplateArgument(VD, ParamType);
4756 return S.Diag(Arg->getLocStart(),
4757 diag::err_template_arg_not_pointer_to_member_form)
4758 << Arg->getSourceRange();
4760 if (isa<FieldDecl>(DRE->getDecl()) ||
4761 isa<IndirectFieldDecl>(DRE->getDecl()) ||
4762 isa<CXXMethodDecl>(DRE->getDecl())) {
4763 assert((isa<FieldDecl>(DRE->getDecl()) ||
4764 isa<IndirectFieldDecl>(DRE->getDecl()) ||
4765 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
4766 "Only non-static member pointers can make it here");
4768 // Okay: this is the address of a non-static member, and therefore
4769 // a member pointer constant.
4770 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
4771 Converted = TemplateArgument(Arg);
4773 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
4774 Converted = TemplateArgument(D, ParamType);
4779 // We found something else, but we don't know specifically what it is.
4780 S.Diag(Arg->getLocStart(),
4781 diag::err_template_arg_not_pointer_to_member_form)
4782 << Arg->getSourceRange();
4783 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4787 /// \brief Check a template argument against its corresponding
4788 /// non-type template parameter.
4790 /// This routine implements the semantics of C++ [temp.arg.nontype].
4791 /// If an error occurred, it returns ExprError(); otherwise, it
4792 /// returns the converted template argument. \p ParamType is the
4793 /// type of the non-type template parameter after it has been instantiated.
4794 ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
4795 QualType ParamType, Expr *Arg,
4796 TemplateArgument &Converted,
4797 CheckTemplateArgumentKind CTAK) {
4798 SourceLocation StartLoc = Arg->getLocStart();
4800 // If either the parameter has a dependent type or the argument is
4801 // type-dependent, there's nothing we can check now.
4802 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
4803 // FIXME: Produce a cloned, canonical expression?
4804 Converted = TemplateArgument(Arg);
4808 // We should have already dropped all cv-qualifiers by now.
4809 assert(!ParamType.hasQualifiers() &&
4810 "non-type template parameter type cannot be qualified");
4812 if (CTAK == CTAK_Deduced &&
4813 !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) {
4814 // C++ [temp.deduct.type]p17:
4815 // If, in the declaration of a function template with a non-type
4816 // template-parameter, the non-type template-parameter is used
4817 // in an expression in the function parameter-list and, if the
4818 // corresponding template-argument is deduced, the
4819 // template-argument type shall match the type of the
4820 // template-parameter exactly, except that a template-argument
4821 // deduced from an array bound may be of any integral type.
4822 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
4823 << Arg->getType().getUnqualifiedType()
4824 << ParamType.getUnqualifiedType();
4825 Diag(Param->getLocation(), diag::note_template_param_here);
4829 if (getLangOpts().CPlusPlus1z) {
4830 // FIXME: We can do some limited checking for a value-dependent but not
4831 // type-dependent argument.
4832 if (Arg->isValueDependent()) {
4833 Converted = TemplateArgument(Arg);
4837 // C++1z [temp.arg.nontype]p1:
4838 // A template-argument for a non-type template parameter shall be
4839 // a converted constant expression of the type of the template-parameter.
4841 ExprResult ArgResult = CheckConvertedConstantExpression(
4842 Arg, ParamType, Value, CCEK_TemplateArg);
4843 if (ArgResult.isInvalid())
4846 QualType CanonParamType = Context.getCanonicalType(ParamType);
4848 // Convert the APValue to a TemplateArgument.
4849 switch (Value.getKind()) {
4850 case APValue::Uninitialized:
4851 assert(ParamType->isNullPtrType());
4852 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
4855 assert(ParamType->isIntegralOrEnumerationType());
4856 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
4858 case APValue::MemberPointer: {
4859 assert(ParamType->isMemberPointerType());
4861 // FIXME: We need TemplateArgument representation and mangling for these.
4862 if (!Value.getMemberPointerPath().empty()) {
4863 Diag(Arg->getLocStart(),
4864 diag::err_template_arg_member_ptr_base_derived_not_supported)
4865 << Value.getMemberPointerDecl() << ParamType
4866 << Arg->getSourceRange();
4870 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
4871 Converted = VD ? TemplateArgument(VD, CanonParamType)
4872 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
4875 case APValue::LValue: {
4876 // For a non-type template-parameter of pointer or reference type,
4877 // the value of the constant expression shall not refer to
4878 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
4879 ParamType->isNullPtrType());
4880 // -- a temporary object
4881 // -- a string literal
4882 // -- the result of a typeid expression, or
4883 // -- a predefind __func__ variable
4884 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
4885 if (isa<CXXUuidofExpr>(E)) {
4886 Converted = TemplateArgument(const_cast<Expr*>(E));
4889 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4890 << Arg->getSourceRange();
4893 auto *VD = const_cast<ValueDecl *>(
4894 Value.getLValueBase().dyn_cast<const ValueDecl *>());
4896 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
4897 VD && VD->getType()->isArrayType() &&
4898 Value.getLValuePath()[0].ArrayIndex == 0 &&
4899 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
4900 // Per defect report (no number yet):
4901 // ... other than a pointer to the first element of a complete array
4903 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
4904 Value.isLValueOnePastTheEnd()) {
4905 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
4906 << Value.getAsString(Context, ParamType);
4909 assert((VD || !ParamType->isReferenceType()) &&
4910 "null reference should not be a constant expression");
4911 assert((!VD || !ParamType->isNullPtrType()) &&
4912 "non-null value of type nullptr_t?");
4913 Converted = VD ? TemplateArgument(VD, CanonParamType)
4914 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
4917 case APValue::AddrLabelDiff:
4918 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
4919 case APValue::Float:
4920 case APValue::ComplexInt:
4921 case APValue::ComplexFloat:
4922 case APValue::Vector:
4923 case APValue::Array:
4924 case APValue::Struct:
4925 case APValue::Union:
4926 llvm_unreachable("invalid kind for template argument");
4929 return ArgResult.get();
4932 // C++ [temp.arg.nontype]p5:
4933 // The following conversions are performed on each expression used
4934 // as a non-type template-argument. If a non-type
4935 // template-argument cannot be converted to the type of the
4936 // corresponding template-parameter then the program is
4938 if (ParamType->isIntegralOrEnumerationType()) {
4940 // -- for a non-type template-parameter of integral or
4941 // enumeration type, conversions permitted in a converted
4942 // constant expression are applied.
4945 // -- for a non-type template-parameter of integral or
4946 // enumeration type, integral promotions (4.5) and integral
4947 // conversions (4.7) are applied.
4949 if (getLangOpts().CPlusPlus11) {
4950 // We can't check arbitrary value-dependent arguments.
4951 // FIXME: If there's no viable conversion to the template parameter type,
4952 // we should be able to diagnose that prior to instantiation.
4953 if (Arg->isValueDependent()) {
4954 Converted = TemplateArgument(Arg);
4958 // C++ [temp.arg.nontype]p1:
4959 // A template-argument for a non-type, non-template template-parameter
4962 // -- for a non-type template-parameter of integral or enumeration
4963 // type, a converted constant expression of the type of the
4964 // template-parameter; or
4966 ExprResult ArgResult =
4967 CheckConvertedConstantExpression(Arg, ParamType, Value,
4969 if (ArgResult.isInvalid())
4972 // Widen the argument value to sizeof(parameter type). This is almost
4973 // always a no-op, except when the parameter type is bool. In
4974 // that case, this may extend the argument from 1 bit to 8 bits.
4975 QualType IntegerType = ParamType;
4976 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
4977 IntegerType = Enum->getDecl()->getIntegerType();
4978 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
4980 Converted = TemplateArgument(Context, Value,
4981 Context.getCanonicalType(ParamType));
4985 ExprResult ArgResult = DefaultLvalueConversion(Arg);
4986 if (ArgResult.isInvalid())
4988 Arg = ArgResult.get();
4990 QualType ArgType = Arg->getType();
4992 // C++ [temp.arg.nontype]p1:
4993 // A template-argument for a non-type, non-template
4994 // template-parameter shall be one of:
4996 // -- an integral constant-expression of integral or enumeration
4998 // -- the name of a non-type template-parameter; or
4999 SourceLocation NonConstantLoc;
5001 if (!ArgType->isIntegralOrEnumerationType()) {
5002 Diag(Arg->getLocStart(),
5003 diag::err_template_arg_not_integral_or_enumeral)
5004 << ArgType << Arg->getSourceRange();
5005 Diag(Param->getLocation(), diag::note_template_param_here);
5007 } else if (!Arg->isValueDependent()) {
5008 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
5012 TmplArgICEDiagnoser(QualType T) : T(T) { }
5014 void diagnoseNotICE(Sema &S, SourceLocation Loc,
5015 SourceRange SR) override {
5016 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
5018 } Diagnoser(ArgType);
5020 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
5026 // From here on out, all we care about is the unqualified form
5027 // of the argument type.
5028 ArgType = ArgType.getUnqualifiedType();
5030 // Try to convert the argument to the parameter's type.
5031 if (Context.hasSameType(ParamType, ArgType)) {
5032 // Okay: no conversion necessary
5033 } else if (ParamType->isBooleanType()) {
5034 // This is an integral-to-boolean conversion.
5035 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
5036 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
5037 !ParamType->isEnumeralType()) {
5038 // This is an integral promotion or conversion.
5039 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
5041 // We can't perform this conversion.
5042 Diag(Arg->getLocStart(),
5043 diag::err_template_arg_not_convertible)
5044 << Arg->getType() << ParamType << Arg->getSourceRange();
5045 Diag(Param->getLocation(), diag::note_template_param_here);
5049 // Add the value of this argument to the list of converted
5050 // arguments. We use the bitwidth and signedness of the template
5052 if (Arg->isValueDependent()) {
5053 // The argument is value-dependent. Create a new
5054 // TemplateArgument with the converted expression.
5055 Converted = TemplateArgument(Arg);
5059 QualType IntegerType = Context.getCanonicalType(ParamType);
5060 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
5061 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
5063 if (ParamType->isBooleanType()) {
5064 // Value must be zero or one.
5066 unsigned AllowedBits = Context.getTypeSize(IntegerType);
5067 if (Value.getBitWidth() != AllowedBits)
5068 Value = Value.extOrTrunc(AllowedBits);
5069 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
5071 llvm::APSInt OldValue = Value;
5073 // Coerce the template argument's value to the value it will have
5074 // based on the template parameter's type.
5075 unsigned AllowedBits = Context.getTypeSize(IntegerType);
5076 if (Value.getBitWidth() != AllowedBits)
5077 Value = Value.extOrTrunc(AllowedBits);
5078 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
5080 // Complain if an unsigned parameter received a negative value.
5081 if (IntegerType->isUnsignedIntegerOrEnumerationType()
5082 && (OldValue.isSigned() && OldValue.isNegative())) {
5083 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
5084 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5085 << Arg->getSourceRange();
5086 Diag(Param->getLocation(), diag::note_template_param_here);
5089 // Complain if we overflowed the template parameter's type.
5090 unsigned RequiredBits;
5091 if (IntegerType->isUnsignedIntegerOrEnumerationType())
5092 RequiredBits = OldValue.getActiveBits();
5093 else if (OldValue.isUnsigned())
5094 RequiredBits = OldValue.getActiveBits() + 1;
5096 RequiredBits = OldValue.getMinSignedBits();
5097 if (RequiredBits > AllowedBits) {
5098 Diag(Arg->getLocStart(),
5099 diag::warn_template_arg_too_large)
5100 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5101 << Arg->getSourceRange();
5102 Diag(Param->getLocation(), diag::note_template_param_here);
5106 Converted = TemplateArgument(Context, Value,
5107 ParamType->isEnumeralType()
5108 ? Context.getCanonicalType(ParamType)
5113 QualType ArgType = Arg->getType();
5114 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
5116 // Handle pointer-to-function, reference-to-function, and
5117 // pointer-to-member-function all in (roughly) the same way.
5118 if (// -- For a non-type template-parameter of type pointer to
5119 // function, only the function-to-pointer conversion (4.3) is
5120 // applied. If the template-argument represents a set of
5121 // overloaded functions (or a pointer to such), the matching
5122 // function is selected from the set (13.4).
5123 (ParamType->isPointerType() &&
5124 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
5125 // -- For a non-type template-parameter of type reference to
5126 // function, no conversions apply. If the template-argument
5127 // represents a set of overloaded functions, the matching
5128 // function is selected from the set (13.4).
5129 (ParamType->isReferenceType() &&
5130 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
5131 // -- For a non-type template-parameter of type pointer to
5132 // member function, no conversions apply. If the
5133 // template-argument represents a set of overloaded member
5134 // functions, the matching member function is selected from
5136 (ParamType->isMemberPointerType() &&
5137 ParamType->getAs<MemberPointerType>()->getPointeeType()
5138 ->isFunctionType())) {
5140 if (Arg->getType() == Context.OverloadTy) {
5141 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
5144 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
5147 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5148 ArgType = Arg->getType();
5153 if (!ParamType->isMemberPointerType()) {
5154 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5161 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5167 if (ParamType->isPointerType()) {
5168 // -- for a non-type template-parameter of type pointer to
5169 // object, qualification conversions (4.4) and the
5170 // array-to-pointer conversion (4.2) are applied.
5171 // C++0x also allows a value of std::nullptr_t.
5172 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
5173 "Only object pointers allowed here");
5175 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5182 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
5183 // -- For a non-type template-parameter of type reference to
5184 // object, no conversions apply. The type referred to by the
5185 // reference may be more cv-qualified than the (otherwise
5186 // identical) type of the template-argument. The
5187 // template-parameter is bound directly to the
5188 // template-argument, which must be an lvalue.
5189 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
5190 "Only object references allowed here");
5192 if (Arg->getType() == Context.OverloadTy) {
5193 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
5194 ParamRefType->getPointeeType(),
5197 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
5200 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5201 ArgType = Arg->getType();
5206 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5213 // Deal with parameters of type std::nullptr_t.
5214 if (ParamType->isNullPtrType()) {
5215 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5216 Converted = TemplateArgument(Arg);
5220 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
5221 case NPV_NotNullPointer:
5222 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
5223 << Arg->getType() << ParamType;
5224 Diag(Param->getLocation(), diag::note_template_param_here);
5230 case NPV_NullPointer:
5231 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
5232 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
5238 // -- For a non-type template-parameter of type pointer to data
5239 // member, qualification conversions (4.4) are applied.
5240 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
5242 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5248 /// \brief Check a template argument against its corresponding
5249 /// template template parameter.
5251 /// This routine implements the semantics of C++ [temp.arg.template].
5252 /// It returns true if an error occurred, and false otherwise.
5253 bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
5254 TemplateArgumentLoc &Arg,
5255 unsigned ArgumentPackIndex) {
5256 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
5257 TemplateDecl *Template = Name.getAsTemplateDecl();
5259 // Any dependent template name is fine.
5260 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
5264 // C++0x [temp.arg.template]p1:
5265 // A template-argument for a template template-parameter shall be
5266 // the name of a class template or an alias template, expressed as an
5267 // id-expression. When the template-argument names a class template, only
5268 // primary class templates are considered when matching the
5269 // template template argument with the corresponding parameter;
5270 // partial specializations are not considered even if their
5271 // parameter lists match that of the template template parameter.
5273 // Note that we also allow template template parameters here, which
5274 // will happen when we are dealing with, e.g., class template
5275 // partial specializations.
5276 if (!isa<ClassTemplateDecl>(Template) &&
5277 !isa<TemplateTemplateParmDecl>(Template) &&
5278 !isa<TypeAliasTemplateDecl>(Template)) {
5279 assert(isa<FunctionTemplateDecl>(Template) &&
5280 "Only function templates are possible here");
5281 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
5282 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
5286 TemplateParameterList *Params = Param->getTemplateParameters();
5287 if (Param->isExpandedParameterPack())
5288 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
5290 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
5293 TPL_TemplateTemplateArgumentMatch,
5297 /// \brief Given a non-type template argument that refers to a
5298 /// declaration and the type of its corresponding non-type template
5299 /// parameter, produce an expression that properly refers to that
5302 Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5304 SourceLocation Loc) {
5305 // C++ [temp.param]p8:
5307 // A non-type template-parameter of type "array of T" or
5308 // "function returning T" is adjusted to be of type "pointer to
5309 // T" or "pointer to function returning T", respectively.
5310 if (ParamType->isArrayType())
5311 ParamType = Context.getArrayDecayedType(ParamType);
5312 else if (ParamType->isFunctionType())
5313 ParamType = Context.getPointerType(ParamType);
5315 // For a NULL non-type template argument, return nullptr casted to the
5316 // parameter's type.
5317 if (Arg.getKind() == TemplateArgument::NullPtr) {
5318 return ImpCastExprToType(
5319 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
5321 ParamType->getAs<MemberPointerType>()
5322 ? CK_NullToMemberPointer
5323 : CK_NullToPointer);
5325 assert(Arg.getKind() == TemplateArgument::Declaration &&
5326 "Only declaration template arguments permitted here");
5328 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
5330 if (VD->getDeclContext()->isRecord() &&
5331 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
5332 isa<IndirectFieldDecl>(VD))) {
5333 // If the value is a class member, we might have a pointer-to-member.
5334 // Determine whether the non-type template template parameter is of
5335 // pointer-to-member type. If so, we need to build an appropriate
5336 // expression for a pointer-to-member, since a "normal" DeclRefExpr
5337 // would refer to the member itself.
5338 if (ParamType->isMemberPointerType()) {
5340 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
5341 NestedNameSpecifier *Qualifier
5342 = NestedNameSpecifier::Create(Context, nullptr, false,
5343 ClassType.getTypePtr());
5345 SS.MakeTrivial(Context, Qualifier, Loc);
5347 // The actual value-ness of this is unimportant, but for
5348 // internal consistency's sake, references to instance methods
5350 ExprValueKind VK = VK_LValue;
5351 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
5354 ExprResult RefExpr = BuildDeclRefExpr(VD,
5355 VD->getType().getNonReferenceType(),
5359 if (RefExpr.isInvalid())
5362 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
5364 // We might need to perform a trailing qualification conversion, since
5365 // the element type on the parameter could be more qualified than the
5366 // element type in the expression we constructed.
5367 bool ObjCLifetimeConversion;
5368 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
5369 ParamType.getUnqualifiedType(), false,
5370 ObjCLifetimeConversion))
5371 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
5373 assert(!RefExpr.isInvalid() &&
5374 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
5375 ParamType.getUnqualifiedType()));
5380 QualType T = VD->getType().getNonReferenceType();
5382 if (ParamType->isPointerType()) {
5383 // When the non-type template parameter is a pointer, take the
5384 // address of the declaration.
5385 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
5386 if (RefExpr.isInvalid())
5389 if (T->isFunctionType() || T->isArrayType()) {
5390 // Decay functions and arrays.
5391 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
5392 if (RefExpr.isInvalid())
5398 // Take the address of everything else
5399 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
5402 ExprValueKind VK = VK_RValue;
5404 // If the non-type template parameter has reference type, qualify the
5405 // resulting declaration reference with the extra qualifiers on the
5406 // type that the reference refers to.
5407 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
5409 T = Context.getQualifiedType(T,
5410 TargetRef->getPointeeType().getQualifiers());
5411 } else if (isa<FunctionDecl>(VD)) {
5412 // References to functions are always lvalues.
5416 return BuildDeclRefExpr(VD, T, VK, Loc);
5419 /// \brief Construct a new expression that refers to the given
5420 /// integral template argument with the given source-location
5423 /// This routine takes care of the mapping from an integral template
5424 /// argument (which may have any integral type) to the appropriate
5427 Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5428 SourceLocation Loc) {
5429 assert(Arg.getKind() == TemplateArgument::Integral &&
5430 "Operation is only valid for integral template arguments");
5431 QualType OrigT = Arg.getIntegralType();
5433 // If this is an enum type that we're instantiating, we need to use an integer
5434 // type the same size as the enumerator. We don't want to build an
5435 // IntegerLiteral with enum type. The integer type of an enum type can be of
5436 // any integral type with C++11 enum classes, make sure we create the right
5437 // type of literal for it.
5439 if (const EnumType *ET = OrigT->getAs<EnumType>())
5440 T = ET->getDecl()->getIntegerType();
5443 if (T->isAnyCharacterType()) {
5444 CharacterLiteral::CharacterKind Kind;
5445 if (T->isWideCharType())
5446 Kind = CharacterLiteral::Wide;
5447 else if (T->isChar16Type())
5448 Kind = CharacterLiteral::UTF16;
5449 else if (T->isChar32Type())
5450 Kind = CharacterLiteral::UTF32;
5452 Kind = CharacterLiteral::Ascii;
5454 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
5456 } else if (T->isBooleanType()) {
5457 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
5459 } else if (T->isNullPtrType()) {
5460 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
5462 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
5465 if (OrigT->isEnumeralType()) {
5466 // FIXME: This is a hack. We need a better way to handle substituted
5467 // non-type template parameters.
5468 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
5470 Context.getTrivialTypeSourceInfo(OrigT, Loc),
5477 /// \brief Match two template parameters within template parameter lists.
5478 static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
5480 Sema::TemplateParameterListEqualKind Kind,
5481 SourceLocation TemplateArgLoc) {
5482 // Check the actual kind (type, non-type, template).
5483 if (Old->getKind() != New->getKind()) {
5485 unsigned NextDiag = diag::err_template_param_different_kind;
5486 if (TemplateArgLoc.isValid()) {
5487 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5488 NextDiag = diag::note_template_param_different_kind;
5490 S.Diag(New->getLocation(), NextDiag)
5491 << (Kind != Sema::TPL_TemplateMatch);
5492 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
5493 << (Kind != Sema::TPL_TemplateMatch);
5499 // Check that both are parameter packs are neither are parameter packs.
5500 // However, if we are matching a template template argument to a
5501 // template template parameter, the template template parameter can have
5502 // a parameter pack where the template template argument does not.
5503 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
5504 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5505 Old->isTemplateParameterPack())) {
5507 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
5508 if (TemplateArgLoc.isValid()) {
5509 S.Diag(TemplateArgLoc,
5510 diag::err_template_arg_template_params_mismatch);
5511 NextDiag = diag::note_template_parameter_pack_non_pack;
5514 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
5515 : isa<NonTypeTemplateParmDecl>(New)? 1
5517 S.Diag(New->getLocation(), NextDiag)
5518 << ParamKind << New->isParameterPack();
5519 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
5520 << ParamKind << Old->isParameterPack();
5526 // For non-type template parameters, check the type of the parameter.
5527 if (NonTypeTemplateParmDecl *OldNTTP
5528 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
5529 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
5531 // If we are matching a template template argument to a template
5532 // template parameter and one of the non-type template parameter types
5533 // is dependent, then we must wait until template instantiation time
5534 // to actually compare the arguments.
5535 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5536 (OldNTTP->getType()->isDependentType() ||
5537 NewNTTP->getType()->isDependentType()))
5540 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
5542 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
5543 if (TemplateArgLoc.isValid()) {
5544 S.Diag(TemplateArgLoc,
5545 diag::err_template_arg_template_params_mismatch);
5546 NextDiag = diag::note_template_nontype_parm_different_type;
5548 S.Diag(NewNTTP->getLocation(), NextDiag)
5549 << NewNTTP->getType()
5550 << (Kind != Sema::TPL_TemplateMatch);
5551 S.Diag(OldNTTP->getLocation(),
5552 diag::note_template_nontype_parm_prev_declaration)
5553 << OldNTTP->getType();
5562 // For template template parameters, check the template parameter types.
5563 // The template parameter lists of template template
5564 // parameters must agree.
5565 if (TemplateTemplateParmDecl *OldTTP
5566 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
5567 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
5568 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
5569 OldTTP->getTemplateParameters(),
5571 (Kind == Sema::TPL_TemplateMatch
5572 ? Sema::TPL_TemplateTemplateParmMatch
5580 /// \brief Diagnose a known arity mismatch when comparing template argument
5583 void DiagnoseTemplateParameterListArityMismatch(Sema &S,
5584 TemplateParameterList *New,
5585 TemplateParameterList *Old,
5586 Sema::TemplateParameterListEqualKind Kind,
5587 SourceLocation TemplateArgLoc) {
5588 unsigned NextDiag = diag::err_template_param_list_different_arity;
5589 if (TemplateArgLoc.isValid()) {
5590 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5591 NextDiag = diag::note_template_param_list_different_arity;
5593 S.Diag(New->getTemplateLoc(), NextDiag)
5594 << (New->size() > Old->size())
5595 << (Kind != Sema::TPL_TemplateMatch)
5596 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
5597 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
5598 << (Kind != Sema::TPL_TemplateMatch)
5599 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
5602 /// \brief Determine whether the given template parameter lists are
5605 /// \param New The new template parameter list, typically written in the
5606 /// source code as part of a new template declaration.
5608 /// \param Old The old template parameter list, typically found via
5609 /// name lookup of the template declared with this template parameter
5612 /// \param Complain If true, this routine will produce a diagnostic if
5613 /// the template parameter lists are not equivalent.
5615 /// \param Kind describes how we are to match the template parameter lists.
5617 /// \param TemplateArgLoc If this source location is valid, then we
5618 /// are actually checking the template parameter list of a template
5619 /// argument (New) against the template parameter list of its
5620 /// corresponding template template parameter (Old). We produce
5621 /// slightly different diagnostics in this scenario.
5623 /// \returns True if the template parameter lists are equal, false
5626 Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
5627 TemplateParameterList *Old,
5629 TemplateParameterListEqualKind Kind,
5630 SourceLocation TemplateArgLoc) {
5631 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
5633 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5639 // C++0x [temp.arg.template]p3:
5640 // A template-argument matches a template template-parameter (call it P)
5641 // when each of the template parameters in the template-parameter-list of
5642 // the template-argument's corresponding class template or alias template
5643 // (call it A) matches the corresponding template parameter in the
5644 // template-parameter-list of P. [...]
5645 TemplateParameterList::iterator NewParm = New->begin();
5646 TemplateParameterList::iterator NewParmEnd = New->end();
5647 for (TemplateParameterList::iterator OldParm = Old->begin(),
5648 OldParmEnd = Old->end();
5649 OldParm != OldParmEnd; ++OldParm) {
5650 if (Kind != TPL_TemplateTemplateArgumentMatch ||
5651 !(*OldParm)->isTemplateParameterPack()) {
5652 if (NewParm == NewParmEnd) {
5654 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5660 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5661 Kind, TemplateArgLoc))
5668 // C++0x [temp.arg.template]p3:
5669 // [...] When P's template- parameter-list contains a template parameter
5670 // pack (14.5.3), the template parameter pack will match zero or more
5671 // template parameters or template parameter packs in the
5672 // template-parameter-list of A with the same type and form as the
5673 // template parameter pack in P (ignoring whether those template
5674 // parameters are template parameter packs).
5675 for (; NewParm != NewParmEnd; ++NewParm) {
5676 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5677 Kind, TemplateArgLoc))
5682 // Make sure we exhausted all of the arguments.
5683 if (NewParm != NewParmEnd) {
5685 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5694 /// \brief Check whether a template can be declared within this scope.
5696 /// If the template declaration is valid in this scope, returns
5697 /// false. Otherwise, issues a diagnostic and returns true.
5699 Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
5703 // Find the nearest enclosing declaration scope.
5704 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5705 (S->getFlags() & Scope::TemplateParamScope) != 0)
5709 // A template [...] shall not have C linkage.
5710 DeclContext *Ctx = S->getEntity();
5711 if (Ctx && Ctx->isExternCContext())
5712 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
5713 << TemplateParams->getSourceRange();
5715 while (Ctx && isa<LinkageSpecDecl>(Ctx))
5716 Ctx = Ctx->getParent();
5719 // A template-declaration can appear only as a namespace scope or
5720 // class scope declaration.
5722 if (Ctx->isFileContext())
5724 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
5725 // C++ [temp.mem]p2:
5726 // A local class shall not have member templates.
5727 if (RD->isLocalClass())
5728 return Diag(TemplateParams->getTemplateLoc(),
5729 diag::err_template_inside_local_class)
5730 << TemplateParams->getSourceRange();
5736 return Diag(TemplateParams->getTemplateLoc(),
5737 diag::err_template_outside_namespace_or_class_scope)
5738 << TemplateParams->getSourceRange();
5741 /// \brief Determine what kind of template specialization the given declaration
5743 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
5745 return TSK_Undeclared;
5747 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
5748 return Record->getTemplateSpecializationKind();
5749 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
5750 return Function->getTemplateSpecializationKind();
5751 if (VarDecl *Var = dyn_cast<VarDecl>(D))
5752 return Var->getTemplateSpecializationKind();
5754 return TSK_Undeclared;
5757 /// \brief Check whether a specialization is well-formed in the current
5760 /// This routine determines whether a template specialization can be declared
5761 /// in the current context (C++ [temp.expl.spec]p2).
5763 /// \param S the semantic analysis object for which this check is being
5766 /// \param Specialized the entity being specialized or instantiated, which
5767 /// may be a kind of template (class template, function template, etc.) or
5768 /// a member of a class template (member function, static data member,
5771 /// \param PrevDecl the previous declaration of this entity, if any.
5773 /// \param Loc the location of the explicit specialization or instantiation of
5776 /// \param IsPartialSpecialization whether this is a partial specialization of
5777 /// a class template.
5779 /// \returns true if there was an error that we cannot recover from, false
5781 static bool CheckTemplateSpecializationScope(Sema &S,
5782 NamedDecl *Specialized,
5783 NamedDecl *PrevDecl,
5785 bool IsPartialSpecialization) {
5786 // Keep these "kind" numbers in sync with the %select statements in the
5787 // various diagnostics emitted by this routine.
5789 if (isa<ClassTemplateDecl>(Specialized))
5790 EntityKind = IsPartialSpecialization? 1 : 0;
5791 else if (isa<VarTemplateDecl>(Specialized))
5792 EntityKind = IsPartialSpecialization ? 3 : 2;
5793 else if (isa<FunctionTemplateDecl>(Specialized))
5795 else if (isa<CXXMethodDecl>(Specialized))
5797 else if (isa<VarDecl>(Specialized))
5799 else if (isa<RecordDecl>(Specialized))
5801 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
5804 S.Diag(Loc, diag::err_template_spec_unknown_kind)
5805 << S.getLangOpts().CPlusPlus11;
5806 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5810 // C++ [temp.expl.spec]p2:
5811 // An explicit specialization shall be declared in the namespace
5812 // of which the template is a member, or, for member templates, in
5813 // the namespace of which the enclosing class or enclosing class
5814 // template is a member. An explicit specialization of a member
5815 // function, member class or static data member of a class
5816 // template shall be declared in the namespace of which the class
5817 // template is a member. Such a declaration may also be a
5818 // definition. If the declaration is not a definition, the
5819 // specialization may be defined later in the name- space in which
5820 // the explicit specialization was declared, or in a namespace
5821 // that encloses the one in which the explicit specialization was
5823 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
5824 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
5829 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
5830 if (S.getLangOpts().MicrosoftExt) {
5831 // Do not warn for class scope explicit specialization during
5832 // instantiation, warning was already emitted during pattern
5833 // semantic analysis.
5834 if (!S.ActiveTemplateInstantiations.size())
5835 S.Diag(Loc, diag::ext_function_specialization_in_class)
5838 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5844 if (S.CurContext->isRecord() &&
5845 !S.CurContext->Equals(Specialized->getDeclContext())) {
5846 // Make sure that we're specializing in the right record context.
5847 // Otherwise, things can go horribly wrong.
5848 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5853 // C++ [temp.class.spec]p6:
5854 // A class template partial specialization may be declared or redeclared
5855 // in any namespace scope in which its definition may be defined (14.5.1
5857 DeclContext *SpecializedContext
5858 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
5859 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
5861 // Make sure that this redeclaration (or definition) occurs in an enclosing
5863 // Note that HandleDeclarator() performs this check for explicit
5864 // specializations of function templates, static data members, and member
5865 // functions, so we skip the check here for those kinds of entities.
5866 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
5867 // Should we refactor that check, so that it occurs later?
5868 if (!DC->Encloses(SpecializedContext) &&
5869 !(isa<FunctionTemplateDecl>(Specialized) ||
5870 isa<FunctionDecl>(Specialized) ||
5871 isa<VarTemplateDecl>(Specialized) ||
5872 isa<VarDecl>(Specialized))) {
5873 if (isa<TranslationUnitDecl>(SpecializedContext))
5874 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
5875 << EntityKind << Specialized;
5876 else if (isa<NamespaceDecl>(SpecializedContext)) {
5877 int Diag = diag::err_template_spec_redecl_out_of_scope;
5878 if (S.getLangOpts().MicrosoftExt)
5879 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
5880 S.Diag(Loc, Diag) << EntityKind << Specialized
5881 << cast<NamedDecl>(SpecializedContext);
5883 llvm_unreachable("unexpected namespace context for specialization");
5885 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5886 } else if ((!PrevDecl ||
5887 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
5888 getTemplateSpecializationKind(PrevDecl) ==
5889 TSK_ImplicitInstantiation)) {
5890 // C++ [temp.exp.spec]p2:
5891 // An explicit specialization shall be declared in the namespace of which
5892 // the template is a member, or, for member templates, in the namespace
5893 // of which the enclosing class or enclosing class template is a member.
5894 // An explicit specialization of a member function, member class or
5895 // static data member of a class template shall be declared in the
5896 // namespace of which the class template is a member.
5898 // C++11 [temp.expl.spec]p2:
5899 // An explicit specialization shall be declared in a namespace enclosing
5900 // the specialized template.
5901 // C++11 [temp.explicit]p3:
5902 // An explicit instantiation shall appear in an enclosing namespace of its
5904 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
5905 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
5906 if (isa<TranslationUnitDecl>(SpecializedContext)) {
5907 assert(!IsCPlusPlus11Extension &&
5908 "DC encloses TU but isn't in enclosing namespace set");
5909 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
5910 << EntityKind << Specialized;
5911 } else if (isa<NamespaceDecl>(SpecializedContext)) {
5913 if (!IsCPlusPlus11Extension)
5914 Diag = diag::err_template_spec_decl_out_of_scope;
5915 else if (!S.getLangOpts().CPlusPlus11)
5916 Diag = diag::ext_template_spec_decl_out_of_scope;
5918 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
5920 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
5923 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5930 static SourceRange findTemplateParameter(unsigned Depth, Expr *E) {
5931 if (!E->isInstantiationDependent())
5932 return SourceLocation();
5933 DependencyChecker Checker(Depth);
5934 Checker.TraverseStmt(E);
5935 if (Checker.Match && Checker.MatchLoc.isInvalid())
5936 return E->getSourceRange();
5937 return Checker.MatchLoc;
5940 static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
5941 if (!TL.getType()->isDependentType())
5942 return SourceLocation();
5943 DependencyChecker Checker(Depth);
5944 Checker.TraverseTypeLoc(TL);
5945 if (Checker.Match && Checker.MatchLoc.isInvalid())
5946 return TL.getSourceRange();
5947 return Checker.MatchLoc;
5950 /// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
5951 /// that checks non-type template partial specialization arguments.
5952 static bool CheckNonTypeTemplatePartialSpecializationArgs(
5953 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
5954 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
5955 for (unsigned I = 0; I != NumArgs; ++I) {
5956 if (Args[I].getKind() == TemplateArgument::Pack) {
5957 if (CheckNonTypeTemplatePartialSpecializationArgs(
5958 S, TemplateNameLoc, Param, Args[I].pack_begin(),
5959 Args[I].pack_size(), IsDefaultArgument))
5965 if (Args[I].getKind() != TemplateArgument::Expression)
5968 Expr *ArgExpr = Args[I].getAsExpr();
5970 // We can have a pack expansion of any of the bullets below.
5971 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
5972 ArgExpr = Expansion->getPattern();
5974 // Strip off any implicit casts we added as part of type checking.
5975 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
5976 ArgExpr = ICE->getSubExpr();
5978 // C++ [temp.class.spec]p8:
5979 // A non-type argument is non-specialized if it is the name of a
5980 // non-type parameter. All other non-type arguments are
5983 // Below, we check the two conditions that only apply to
5984 // specialized non-type arguments, so skip any non-specialized
5986 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
5987 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
5990 // C++ [temp.class.spec]p9:
5991 // Within the argument list of a class template partial
5992 // specialization, the following restrictions apply:
5993 // -- A partially specialized non-type argument expression
5994 // shall not involve a template parameter of the partial
5995 // specialization except when the argument expression is a
5996 // simple identifier.
5997 SourceRange ParamUseRange =
5998 findTemplateParameter(Param->getDepth(), ArgExpr);
5999 if (ParamUseRange.isValid()) {
6000 if (IsDefaultArgument) {
6001 S.Diag(TemplateNameLoc,
6002 diag::err_dependent_non_type_arg_in_partial_spec);
6003 S.Diag(ParamUseRange.getBegin(),
6004 diag::note_dependent_non_type_default_arg_in_partial_spec)
6007 S.Diag(ParamUseRange.getBegin(),
6008 diag::err_dependent_non_type_arg_in_partial_spec)
6014 // -- The type of a template parameter corresponding to a
6015 // specialized non-type argument shall not be dependent on a
6016 // parameter of the specialization.
6018 // FIXME: We need to delay this check until instantiation in some cases:
6020 // template<template<typename> class X> struct A {
6021 // template<typename T, X<T> N> struct B;
6022 // template<typename T> struct B<T, 0>;
6024 // template<typename> using X = int;
6025 // A<X>::B<int, 0> b;
6026 ParamUseRange = findTemplateParameter(
6027 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
6028 if (ParamUseRange.isValid()) {
6029 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
6030 diag::err_dependent_typed_non_type_arg_in_partial_spec)
6031 << Param->getType() << ParamUseRange;
6032 S.Diag(Param->getLocation(), diag::note_template_param_here)
6033 << (IsDefaultArgument ? ParamUseRange : SourceRange());
6041 /// \brief Check the non-type template arguments of a class template
6042 /// partial specialization according to C++ [temp.class.spec]p9.
6044 /// \param TemplateNameLoc the location of the template name.
6045 /// \param TemplateParams the template parameters of the primary class
6047 /// \param NumExplicit the number of explicitly-specified template arguments.
6048 /// \param TemplateArgs the template arguments of the class template
6049 /// partial specialization.
6051 /// \returns \c true if there was an error, \c false otherwise.
6052 static bool CheckTemplatePartialSpecializationArgs(
6053 Sema &S, SourceLocation TemplateNameLoc,
6054 TemplateParameterList *TemplateParams, unsigned NumExplicit,
6055 SmallVectorImpl<TemplateArgument> &TemplateArgs) {
6056 const TemplateArgument *ArgList = TemplateArgs.data();
6058 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6059 NonTypeTemplateParmDecl *Param
6060 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
6064 if (CheckNonTypeTemplatePartialSpecializationArgs(
6065 S, TemplateNameLoc, Param, &ArgList[I], 1, I >= NumExplicit))
6073 Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
6075 SourceLocation KWLoc,
6076 SourceLocation ModulePrivateLoc,
6077 TemplateIdAnnotation &TemplateId,
6078 AttributeList *Attr,
6079 MultiTemplateParamsArg
6080 TemplateParameterLists,
6081 SkipBodyInfo *SkipBody) {
6082 assert(TUK != TUK_Reference && "References are not specializations");
6084 CXXScopeSpec &SS = TemplateId.SS;
6086 // NOTE: KWLoc is the location of the tag keyword. This will instead
6087 // store the location of the outermost template keyword in the declaration.
6088 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
6089 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
6090 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
6091 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
6092 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
6094 // Find the class template we're specializing
6095 TemplateName Name = TemplateId.Template.get();
6096 ClassTemplateDecl *ClassTemplate
6097 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
6099 if (!ClassTemplate) {
6100 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
6101 << (Name.getAsTemplateDecl() &&
6102 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
6106 bool isExplicitSpecialization = false;
6107 bool isPartialSpecialization = false;
6109 // Check the validity of the template headers that introduce this
6111 // FIXME: We probably shouldn't complain about these headers for
6112 // friend declarations.
6113 bool Invalid = false;
6114 TemplateParameterList *TemplateParams =
6115 MatchTemplateParametersToScopeSpecifier(
6116 KWLoc, TemplateNameLoc, SS, &TemplateId,
6117 TemplateParameterLists, TUK == TUK_Friend, isExplicitSpecialization,
6122 if (TemplateParams && TemplateParams->size() > 0) {
6123 isPartialSpecialization = true;
6125 if (TUK == TUK_Friend) {
6126 Diag(KWLoc, diag::err_partial_specialization_friend)
6127 << SourceRange(LAngleLoc, RAngleLoc);
6131 // C++ [temp.class.spec]p10:
6132 // The template parameter list of a specialization shall not
6133 // contain default template argument values.
6134 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6135 Decl *Param = TemplateParams->getParam(I);
6136 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6137 if (TTP->hasDefaultArgument()) {
6138 Diag(TTP->getDefaultArgumentLoc(),
6139 diag::err_default_arg_in_partial_spec);
6140 TTP->removeDefaultArgument();
6142 } else if (NonTypeTemplateParmDecl *NTTP
6143 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6144 if (Expr *DefArg = NTTP->getDefaultArgument()) {
6145 Diag(NTTP->getDefaultArgumentLoc(),
6146 diag::err_default_arg_in_partial_spec)
6147 << DefArg->getSourceRange();
6148 NTTP->removeDefaultArgument();
6151 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
6152 if (TTP->hasDefaultArgument()) {
6153 Diag(TTP->getDefaultArgument().getLocation(),
6154 diag::err_default_arg_in_partial_spec)
6155 << TTP->getDefaultArgument().getSourceRange();
6156 TTP->removeDefaultArgument();
6160 } else if (TemplateParams) {
6161 if (TUK == TUK_Friend)
6162 Diag(KWLoc, diag::err_template_spec_friend)
6163 << FixItHint::CreateRemoval(
6164 SourceRange(TemplateParams->getTemplateLoc(),
6165 TemplateParams->getRAngleLoc()))
6166 << SourceRange(LAngleLoc, RAngleLoc);
6168 isExplicitSpecialization = true;
6170 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
6173 // Check that the specialization uses the same tag kind as the
6174 // original template.
6175 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6176 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
6177 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
6178 Kind, TUK == TUK_Definition, KWLoc,
6179 ClassTemplate->getIdentifier())) {
6180 Diag(KWLoc, diag::err_use_with_wrong_tag)
6182 << FixItHint::CreateReplacement(KWLoc,
6183 ClassTemplate->getTemplatedDecl()->getKindName());
6184 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
6185 diag::note_previous_use);
6186 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
6189 // Translate the parser's template argument list in our AST format.
6190 TemplateArgumentListInfo TemplateArgs =
6191 makeTemplateArgumentListInfo(*this, TemplateId);
6193 // Check for unexpanded parameter packs in any of the template arguments.
6194 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
6195 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
6196 UPPC_PartialSpecialization))
6199 // Check that the template argument list is well-formed for this
6201 SmallVector<TemplateArgument, 4> Converted;
6202 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
6203 TemplateArgs, false, Converted))
6206 // Find the class template (partial) specialization declaration that
6207 // corresponds to these arguments.
6208 if (isPartialSpecialization) {
6209 if (CheckTemplatePartialSpecializationArgs(
6210 *this, TemplateNameLoc, ClassTemplate->getTemplateParameters(),
6211 TemplateArgs.size(), Converted))
6214 bool InstantiationDependent;
6215 if (!Name.isDependent() &&
6216 !TemplateSpecializationType::anyDependentTemplateArguments(
6217 TemplateArgs.getArgumentArray(),
6218 TemplateArgs.size(),
6219 InstantiationDependent)) {
6220 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
6221 << ClassTemplate->getDeclName();
6222 isPartialSpecialization = false;
6226 void *InsertPos = nullptr;
6227 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
6229 if (isPartialSpecialization)
6230 // FIXME: Template parameter list matters, too
6231 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
6233 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
6235 ClassTemplateSpecializationDecl *Specialization = nullptr;
6237 // Check whether we can declare a class template specialization in
6238 // the current scope.
6239 if (TUK != TUK_Friend &&
6240 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
6242 isPartialSpecialization))
6245 // The canonical type
6247 if (isPartialSpecialization) {
6248 // Build the canonical type that describes the converted template
6249 // arguments of the class template partial specialization.
6250 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6251 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
6255 if (Context.hasSameType(CanonType,
6256 ClassTemplate->getInjectedClassNameSpecialization())) {
6257 // C++ [temp.class.spec]p9b3:
6259 // -- The argument list of the specialization shall not be identical
6260 // to the implicit argument list of the primary template.
6261 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
6262 << /*class template*/0 << (TUK == TUK_Definition)
6263 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
6264 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
6265 ClassTemplate->getIdentifier(),
6269 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
6270 /*FriendLoc*/SourceLocation(),
6271 TemplateParameterLists.size() - 1,
6272 TemplateParameterLists.data());
6275 // Create a new class template partial specialization declaration node.
6276 ClassTemplatePartialSpecializationDecl *PrevPartial
6277 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
6278 ClassTemplatePartialSpecializationDecl *Partial
6279 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
6280 ClassTemplate->getDeclContext(),
6281 KWLoc, TemplateNameLoc,
6289 SetNestedNameSpecifier(Partial, SS);
6290 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
6291 Partial->setTemplateParameterListsInfo(
6292 Context, TemplateParameterLists.drop_back(1));
6296 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
6297 Specialization = Partial;
6299 // If we are providing an explicit specialization of a member class
6300 // template specialization, make a note of that.
6301 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
6302 PrevPartial->setMemberSpecialization();
6304 // Check that all of the template parameters of the class template
6305 // partial specialization are deducible from the template
6306 // arguments. If not, this class template partial specialization
6307 // will never be used.
6308 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
6309 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
6310 TemplateParams->getDepth(),
6313 if (!DeducibleParams.all()) {
6314 unsigned NumNonDeducible = DeducibleParams.size()-DeducibleParams.count();
6315 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
6316 << /*class template*/0 << (NumNonDeducible > 1)
6317 << SourceRange(TemplateNameLoc, RAngleLoc);
6318 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
6319 if (!DeducibleParams[I]) {
6320 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
6321 if (Param->getDeclName())
6322 Diag(Param->getLocation(),
6323 diag::note_partial_spec_unused_parameter)
6324 << Param->getDeclName();
6326 Diag(Param->getLocation(),
6327 diag::note_partial_spec_unused_parameter)
6333 // Create a new class template specialization declaration node for
6334 // this explicit specialization or friend declaration.
6336 = ClassTemplateSpecializationDecl::Create(Context, Kind,
6337 ClassTemplate->getDeclContext(),
6338 KWLoc, TemplateNameLoc,
6343 SetNestedNameSpecifier(Specialization, SS);
6344 if (TemplateParameterLists.size() > 0) {
6345 Specialization->setTemplateParameterListsInfo(Context,
6346 TemplateParameterLists);
6350 ClassTemplate->AddSpecialization(Specialization, InsertPos);
6352 CanonType = Context.getTypeDeclType(Specialization);
6355 // C++ [temp.expl.spec]p6:
6356 // If a template, a member template or the member of a class template is
6357 // explicitly specialized then that specialization shall be declared
6358 // before the first use of that specialization that would cause an implicit
6359 // instantiation to take place, in every translation unit in which such a
6360 // use occurs; no diagnostic is required.
6361 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
6363 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
6364 // Is there any previous explicit specialization declaration?
6365 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6372 SourceRange Range(TemplateNameLoc, RAngleLoc);
6373 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
6374 << Context.getTypeDeclType(Specialization) << Range;
6376 Diag(PrevDecl->getPointOfInstantiation(),
6377 diag::note_instantiation_required_here)
6378 << (PrevDecl->getTemplateSpecializationKind()
6379 != TSK_ImplicitInstantiation);
6384 // If this is not a friend, note that this is an explicit specialization.
6385 if (TUK != TUK_Friend)
6386 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
6388 // Check that this isn't a redefinition of this specialization.
6389 if (TUK == TUK_Definition) {
6390 RecordDecl *Def = Specialization->getDefinition();
6391 NamedDecl *Hidden = nullptr;
6392 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
6393 SkipBody->ShouldSkip = true;
6394 makeMergedDefinitionVisible(Hidden, KWLoc);
6395 // From here on out, treat this as just a redeclaration.
6396 TUK = TUK_Declaration;
6398 SourceRange Range(TemplateNameLoc, RAngleLoc);
6399 Diag(TemplateNameLoc, diag::err_redefinition)
6400 << Context.getTypeDeclType(Specialization) << Range;
6401 Diag(Def->getLocation(), diag::note_previous_definition);
6402 Specialization->setInvalidDecl();
6408 ProcessDeclAttributeList(S, Specialization, Attr);
6410 // Add alignment attributes if necessary; these attributes are checked when
6411 // the ASTContext lays out the structure.
6412 if (TUK == TUK_Definition) {
6413 AddAlignmentAttributesForRecord(Specialization);
6414 AddMsStructLayoutForRecord(Specialization);
6417 if (ModulePrivateLoc.isValid())
6418 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
6419 << (isPartialSpecialization? 1 : 0)
6420 << FixItHint::CreateRemoval(ModulePrivateLoc);
6422 // Build the fully-sugared type for this class template
6423 // specialization as the user wrote in the specialization
6424 // itself. This means that we'll pretty-print the type retrieved
6425 // from the specialization's declaration the way that the user
6426 // actually wrote the specialization, rather than formatting the
6427 // name based on the "canonical" representation used to store the
6428 // template arguments in the specialization.
6429 TypeSourceInfo *WrittenTy
6430 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
6431 TemplateArgs, CanonType);
6432 if (TUK != TUK_Friend) {
6433 Specialization->setTypeAsWritten(WrittenTy);
6434 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
6437 // C++ [temp.expl.spec]p9:
6438 // A template explicit specialization is in the scope of the
6439 // namespace in which the template was defined.
6441 // We actually implement this paragraph where we set the semantic
6442 // context (in the creation of the ClassTemplateSpecializationDecl),
6443 // but we also maintain the lexical context where the actual
6444 // definition occurs.
6445 Specialization->setLexicalDeclContext(CurContext);
6447 // We may be starting the definition of this specialization.
6448 if (TUK == TUK_Definition)
6449 Specialization->startDefinition();
6451 if (TUK == TUK_Friend) {
6452 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
6456 Friend->setAccess(AS_public);
6457 CurContext->addDecl(Friend);
6459 // Add the specialization into its lexical context, so that it can
6460 // be seen when iterating through the list of declarations in that
6461 // context. However, specializations are not found by name lookup.
6462 CurContext->addDecl(Specialization);
6464 return Specialization;
6467 Decl *Sema::ActOnTemplateDeclarator(Scope *S,
6468 MultiTemplateParamsArg TemplateParameterLists,
6470 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
6471 ActOnDocumentableDecl(NewDecl);
6475 /// \brief Strips various properties off an implicit instantiation
6476 /// that has just been explicitly specialized.
6477 static void StripImplicitInstantiation(NamedDecl *D) {
6478 D->dropAttr<DLLImportAttr>();
6479 D->dropAttr<DLLExportAttr>();
6481 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
6482 FD->setInlineSpecified(false);
6485 /// \brief Compute the diagnostic location for an explicit instantiation
6486 // declaration or definition.
6487 static SourceLocation DiagLocForExplicitInstantiation(
6488 NamedDecl* D, SourceLocation PointOfInstantiation) {
6489 // Explicit instantiations following a specialization have no effect and
6490 // hence no PointOfInstantiation. In that case, walk decl backwards
6491 // until a valid name loc is found.
6492 SourceLocation PrevDiagLoc = PointOfInstantiation;
6493 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
6494 Prev = Prev->getPreviousDecl()) {
6495 PrevDiagLoc = Prev->getLocation();
6497 assert(PrevDiagLoc.isValid() &&
6498 "Explicit instantiation without point of instantiation?");
6502 /// \brief Diagnose cases where we have an explicit template specialization
6503 /// before/after an explicit template instantiation, producing diagnostics
6504 /// for those cases where they are required and determining whether the
6505 /// new specialization/instantiation will have any effect.
6507 /// \param NewLoc the location of the new explicit specialization or
6510 /// \param NewTSK the kind of the new explicit specialization or instantiation.
6512 /// \param PrevDecl the previous declaration of the entity.
6514 /// \param PrevTSK the kind of the old explicit specialization or instantiatin.
6516 /// \param PrevPointOfInstantiation if valid, indicates where the previus
6517 /// declaration was instantiated (either implicitly or explicitly).
6519 /// \param HasNoEffect will be set to true to indicate that the new
6520 /// specialization or instantiation has no effect and should be ignored.
6522 /// \returns true if there was an error that should prevent the introduction of
6523 /// the new declaration into the AST, false otherwise.
6525 Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6526 TemplateSpecializationKind NewTSK,
6527 NamedDecl *PrevDecl,
6528 TemplateSpecializationKind PrevTSK,
6529 SourceLocation PrevPointOfInstantiation,
6530 bool &HasNoEffect) {
6531 HasNoEffect = false;
6534 case TSK_Undeclared:
6535 case TSK_ImplicitInstantiation:
6537 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
6538 "previous declaration must be implicit!");
6541 case TSK_ExplicitSpecialization:
6543 case TSK_Undeclared:
6544 case TSK_ExplicitSpecialization:
6545 // Okay, we're just specializing something that is either already
6546 // explicitly specialized or has merely been mentioned without any
6550 case TSK_ImplicitInstantiation:
6551 if (PrevPointOfInstantiation.isInvalid()) {
6552 // The declaration itself has not actually been instantiated, so it is
6553 // still okay to specialize it.
6554 StripImplicitInstantiation(PrevDecl);
6559 case TSK_ExplicitInstantiationDeclaration:
6560 case TSK_ExplicitInstantiationDefinition:
6561 assert((PrevTSK == TSK_ImplicitInstantiation ||
6562 PrevPointOfInstantiation.isValid()) &&
6563 "Explicit instantiation without point of instantiation?");
6565 // C++ [temp.expl.spec]p6:
6566 // If a template, a member template or the member of a class template
6567 // is explicitly specialized then that specialization shall be declared
6568 // before the first use of that specialization that would cause an
6569 // implicit instantiation to take place, in every translation unit in
6570 // which such a use occurs; no diagnostic is required.
6571 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
6572 // Is there any previous explicit specialization declaration?
6573 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
6577 Diag(NewLoc, diag::err_specialization_after_instantiation)
6579 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
6580 << (PrevTSK != TSK_ImplicitInstantiation);
6585 case TSK_ExplicitInstantiationDeclaration:
6587 case TSK_ExplicitInstantiationDeclaration:
6588 // This explicit instantiation declaration is redundant (that's okay).
6592 case TSK_Undeclared:
6593 case TSK_ImplicitInstantiation:
6594 // We're explicitly instantiating something that may have already been
6595 // implicitly instantiated; that's fine.
6598 case TSK_ExplicitSpecialization:
6599 // C++0x [temp.explicit]p4:
6600 // For a given set of template parameters, if an explicit instantiation
6601 // of a template appears after a declaration of an explicit
6602 // specialization for that template, the explicit instantiation has no
6607 case TSK_ExplicitInstantiationDefinition:
6608 // C++0x [temp.explicit]p10:
6609 // If an entity is the subject of both an explicit instantiation
6610 // declaration and an explicit instantiation definition in the same
6611 // translation unit, the definition shall follow the declaration.
6613 diag::err_explicit_instantiation_declaration_after_definition);
6615 // Explicit instantiations following a specialization have no effect and
6616 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
6617 // until a valid name loc is found.
6618 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6619 diag::note_explicit_instantiation_definition_here);
6624 case TSK_ExplicitInstantiationDefinition:
6626 case TSK_Undeclared:
6627 case TSK_ImplicitInstantiation:
6628 // We're explicitly instantiating something that may have already been
6629 // implicitly instantiated; that's fine.
6632 case TSK_ExplicitSpecialization:
6633 // C++ DR 259, C++0x [temp.explicit]p4:
6634 // For a given set of template parameters, if an explicit
6635 // instantiation of a template appears after a declaration of
6636 // an explicit specialization for that template, the explicit
6637 // instantiation has no effect.
6639 // In C++98/03 mode, we only give an extension warning here, because it
6640 // is not harmful to try to explicitly instantiate something that
6641 // has been explicitly specialized.
6642 Diag(NewLoc, getLangOpts().CPlusPlus11 ?
6643 diag::warn_cxx98_compat_explicit_instantiation_after_specialization :
6644 diag::ext_explicit_instantiation_after_specialization)
6646 Diag(PrevDecl->getLocation(),
6647 diag::note_previous_template_specialization);
6651 case TSK_ExplicitInstantiationDeclaration:
6652 // We're explicity instantiating a definition for something for which we
6653 // were previously asked to suppress instantiations. That's fine.
6655 // C++0x [temp.explicit]p4:
6656 // For a given set of template parameters, if an explicit instantiation
6657 // of a template appears after a declaration of an explicit
6658 // specialization for that template, the explicit instantiation has no
6660 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
6661 // Is there any previous explicit specialization declaration?
6662 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6670 case TSK_ExplicitInstantiationDefinition:
6671 // C++0x [temp.spec]p5:
6672 // For a given template and a given set of template-arguments,
6673 // - an explicit instantiation definition shall appear at most once
6676 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
6677 Diag(NewLoc, (getLangOpts().MSVCCompat)
6678 ? diag::ext_explicit_instantiation_duplicate
6679 : diag::err_explicit_instantiation_duplicate)
6681 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6682 diag::note_previous_explicit_instantiation);
6688 llvm_unreachable("Missing specialization/instantiation case?");
6691 /// \brief Perform semantic analysis for the given dependent function
6692 /// template specialization.
6694 /// The only possible way to get a dependent function template specialization
6695 /// is with a friend declaration, like so:
6698 /// template \<class T> void foo(T);
6699 /// template \<class T> class A {
6700 /// friend void foo<>(T);
6704 /// There really isn't any useful analysis we can do here, so we
6705 /// just store the information.
6707 Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6708 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6709 LookupResult &Previous) {
6710 // Remove anything from Previous that isn't a function template in
6711 // the correct context.
6712 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
6713 LookupResult::Filter F = Previous.makeFilter();
6714 while (F.hasNext()) {
6715 NamedDecl *D = F.next()->getUnderlyingDecl();
6716 if (!isa<FunctionTemplateDecl>(D) ||
6717 !FDLookupContext->InEnclosingNamespaceSetOf(
6718 D->getDeclContext()->getRedeclContext()))
6723 // Should this be diagnosed here?
6724 if (Previous.empty()) return true;
6726 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
6727 ExplicitTemplateArgs);
6731 /// \brief Perform semantic analysis for the given function template
6734 /// This routine performs all of the semantic analysis required for an
6735 /// explicit function template specialization. On successful completion,
6736 /// the function declaration \p FD will become a function template
6739 /// \param FD the function declaration, which will be updated to become a
6740 /// function template specialization.
6742 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
6743 /// if any. Note that this may be valid info even when 0 arguments are
6744 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
6745 /// as it anyway contains info on the angle brackets locations.
6747 /// \param Previous the set of declarations that may be specialized by
6748 /// this function specialization.
6749 bool Sema::CheckFunctionTemplateSpecialization(
6750 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
6751 LookupResult &Previous) {
6752 // The set of function template specializations that could match this
6753 // explicit function template specialization.
6754 UnresolvedSet<8> Candidates;
6755 TemplateSpecCandidateSet FailedCandidates(FD->getLocation());
6757 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
6758 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6760 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
6761 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
6762 // Only consider templates found within the same semantic lookup scope as
6764 if (!FDLookupContext->InEnclosingNamespaceSetOf(
6765 Ovl->getDeclContext()->getRedeclContext()))
6768 // When matching a constexpr member function template specialization
6769 // against the primary template, we don't yet know whether the
6770 // specialization has an implicit 'const' (because we don't know whether
6771 // it will be a static member function until we know which template it
6772 // specializes), so adjust it now assuming it specializes this template.
6773 QualType FT = FD->getType();
6774 if (FD->isConstexpr()) {
6775 CXXMethodDecl *OldMD =
6776 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
6777 if (OldMD && OldMD->isConst()) {
6778 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
6779 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6780 EPI.TypeQuals |= Qualifiers::Const;
6781 FT = Context.getFunctionType(FPT->getReturnType(),
6782 FPT->getParamTypes(), EPI);
6786 // C++ [temp.expl.spec]p11:
6787 // A trailing template-argument can be left unspecified in the
6788 // template-id naming an explicit function template specialization
6789 // provided it can be deduced from the function argument type.
6790 // Perform template argument deduction to determine whether we may be
6791 // specializing this template.
6792 // FIXME: It is somewhat wasteful to build
6793 TemplateDeductionInfo Info(FailedCandidates.getLocation());
6794 FunctionDecl *Specialization = nullptr;
6795 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
6796 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
6797 ExplicitTemplateArgs, FT, Specialization, Info)) {
6798 // Template argument deduction failed; record why it failed, so
6799 // that we can provide nifty diagnostics.
6800 FailedCandidates.addCandidate()
6801 .set(FunTmpl->getTemplatedDecl(),
6802 MakeDeductionFailureInfo(Context, TDK, Info));
6807 // Record this candidate.
6808 Candidates.addDecl(Specialization, I.getAccess());
6812 // Find the most specialized function template.
6813 UnresolvedSetIterator Result = getMostSpecialized(
6814 Candidates.begin(), Candidates.end(), FailedCandidates,
6816 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
6817 PDiag(diag::err_function_template_spec_ambiguous)
6818 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
6819 PDiag(diag::note_function_template_spec_matched));
6821 if (Result == Candidates.end())
6824 // Ignore access information; it doesn't figure into redeclaration checking.
6825 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
6827 FunctionTemplateSpecializationInfo *SpecInfo
6828 = Specialization->getTemplateSpecializationInfo();
6829 assert(SpecInfo && "Function template specialization info missing?");
6831 // Note: do not overwrite location info if previous template
6832 // specialization kind was explicit.
6833 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
6834 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
6835 Specialization->setLocation(FD->getLocation());
6836 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
6837 // function can differ from the template declaration with respect to
6838 // the constexpr specifier.
6839 Specialization->setConstexpr(FD->isConstexpr());
6842 // FIXME: Check if the prior specialization has a point of instantiation.
6843 // If so, we have run afoul of .
6845 // If this is a friend declaration, then we're not really declaring
6846 // an explicit specialization.
6847 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
6849 // Check the scope of this explicit specialization.
6851 CheckTemplateSpecializationScope(*this,
6852 Specialization->getPrimaryTemplate(),
6853 Specialization, FD->getLocation(),
6857 // C++ [temp.expl.spec]p6:
6858 // If a template, a member template or the member of a class template is
6859 // explicitly specialized then that specialization shall be declared
6860 // before the first use of that specialization that would cause an implicit
6861 // instantiation to take place, in every translation unit in which such a
6862 // use occurs; no diagnostic is required.
6863 bool HasNoEffect = false;
6865 CheckSpecializationInstantiationRedecl(FD->getLocation(),
6866 TSK_ExplicitSpecialization,
6868 SpecInfo->getTemplateSpecializationKind(),
6869 SpecInfo->getPointOfInstantiation(),
6873 // Mark the prior declaration as an explicit specialization, so that later
6874 // clients know that this is an explicit specialization.
6876 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
6877 MarkUnusedFileScopedDecl(Specialization);
6880 // Turn the given function declaration into a function template
6881 // specialization, with the template arguments from the previous
6883 // Take copies of (semantic and syntactic) template argument lists.
6884 const TemplateArgumentList* TemplArgs = new (Context)
6885 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
6886 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
6887 TemplArgs, /*InsertPos=*/nullptr,
6888 SpecInfo->getTemplateSpecializationKind(),
6889 ExplicitTemplateArgs);
6891 // The "previous declaration" for this function template specialization is
6892 // the prior function template specialization.
6894 Previous.addDecl(Specialization);
6898 /// \brief Perform semantic analysis for the given non-template member
6901 /// This routine performs all of the semantic analysis required for an
6902 /// explicit member function specialization. On successful completion,
6903 /// the function declaration \p FD will become a member function
6906 /// \param Member the member declaration, which will be updated to become a
6909 /// \param Previous the set of declarations, one of which may be specialized
6910 /// by this function specialization; the set will be modified to contain the
6911 /// redeclared member.
6913 Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
6914 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
6916 // Try to find the member we are instantiating.
6917 NamedDecl *Instantiation = nullptr;
6918 NamedDecl *InstantiatedFrom = nullptr;
6919 MemberSpecializationInfo *MSInfo = nullptr;
6921 if (Previous.empty()) {
6922 // Nowhere to look anyway.
6923 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
6924 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6926 NamedDecl *D = (*I)->getUnderlyingDecl();
6927 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
6928 QualType Adjusted = Function->getType();
6929 if (!hasExplicitCallingConv(Adjusted))
6930 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
6931 if (Context.hasSameType(Adjusted, Method->getType())) {
6932 Instantiation = Method;
6933 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
6934 MSInfo = Method->getMemberSpecializationInfo();
6939 } else if (isa<VarDecl>(Member)) {
6941 if (Previous.isSingleResult() &&
6942 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
6943 if (PrevVar->isStaticDataMember()) {
6944 Instantiation = PrevVar;
6945 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
6946 MSInfo = PrevVar->getMemberSpecializationInfo();
6948 } else if (isa<RecordDecl>(Member)) {
6949 CXXRecordDecl *PrevRecord;
6950 if (Previous.isSingleResult() &&
6951 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
6952 Instantiation = PrevRecord;
6953 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
6954 MSInfo = PrevRecord->getMemberSpecializationInfo();
6956 } else if (isa<EnumDecl>(Member)) {
6958 if (Previous.isSingleResult() &&
6959 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
6960 Instantiation = PrevEnum;
6961 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
6962 MSInfo = PrevEnum->getMemberSpecializationInfo();
6966 if (!Instantiation) {
6967 // There is no previous declaration that matches. Since member
6968 // specializations are always out-of-line, the caller will complain about
6969 // this mismatch later.
6973 // If this is a friend, just bail out here before we start turning
6974 // things into explicit specializations.
6975 if (Member->getFriendObjectKind() != Decl::FOK_None) {
6976 // Preserve instantiation information.
6977 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
6978 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
6979 cast<CXXMethodDecl>(InstantiatedFrom),
6980 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
6981 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
6982 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
6983 cast<CXXRecordDecl>(InstantiatedFrom),
6984 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
6988 Previous.addDecl(Instantiation);
6992 // Make sure that this is a specialization of a member.
6993 if (!InstantiatedFrom) {
6994 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
6996 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
7000 // C++ [temp.expl.spec]p6:
7001 // If a template, a member template or the member of a class template is
7002 // explicitly specialized then that specialization shall be declared
7003 // before the first use of that specialization that would cause an implicit
7004 // instantiation to take place, in every translation unit in which such a
7005 // use occurs; no diagnostic is required.
7006 assert(MSInfo && "Member specialization info missing?");
7008 bool HasNoEffect = false;
7009 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
7010 TSK_ExplicitSpecialization,
7012 MSInfo->getTemplateSpecializationKind(),
7013 MSInfo->getPointOfInstantiation(),
7017 // Check the scope of this explicit specialization.
7018 if (CheckTemplateSpecializationScope(*this,
7020 Instantiation, Member->getLocation(),
7024 // Note that this is an explicit instantiation of a member.
7025 // the original declaration to note that it is an explicit specialization
7026 // (if it was previously an implicit instantiation). This latter step
7027 // makes bookkeeping easier.
7028 if (isa<FunctionDecl>(Member)) {
7029 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
7030 if (InstantiationFunction->getTemplateSpecializationKind() ==
7031 TSK_ImplicitInstantiation) {
7032 InstantiationFunction->setTemplateSpecializationKind(
7033 TSK_ExplicitSpecialization);
7034 InstantiationFunction->setLocation(Member->getLocation());
7037 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
7038 cast<CXXMethodDecl>(InstantiatedFrom),
7039 TSK_ExplicitSpecialization);
7040 MarkUnusedFileScopedDecl(InstantiationFunction);
7041 } else if (isa<VarDecl>(Member)) {
7042 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
7043 if (InstantiationVar->getTemplateSpecializationKind() ==
7044 TSK_ImplicitInstantiation) {
7045 InstantiationVar->setTemplateSpecializationKind(
7046 TSK_ExplicitSpecialization);
7047 InstantiationVar->setLocation(Member->getLocation());
7050 cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
7051 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
7052 MarkUnusedFileScopedDecl(InstantiationVar);
7053 } else if (isa<CXXRecordDecl>(Member)) {
7054 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
7055 if (InstantiationClass->getTemplateSpecializationKind() ==
7056 TSK_ImplicitInstantiation) {
7057 InstantiationClass->setTemplateSpecializationKind(
7058 TSK_ExplicitSpecialization);
7059 InstantiationClass->setLocation(Member->getLocation());
7062 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
7063 cast<CXXRecordDecl>(InstantiatedFrom),
7064 TSK_ExplicitSpecialization);
7066 assert(isa<EnumDecl>(Member) && "Only member enums remain");
7067 EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
7068 if (InstantiationEnum->getTemplateSpecializationKind() ==
7069 TSK_ImplicitInstantiation) {
7070 InstantiationEnum->setTemplateSpecializationKind(
7071 TSK_ExplicitSpecialization);
7072 InstantiationEnum->setLocation(Member->getLocation());
7075 cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
7076 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
7079 // Save the caller the trouble of having to figure out which declaration
7080 // this specialization matches.
7082 Previous.addDecl(Instantiation);
7086 /// \brief Check the scope of an explicit instantiation.
7088 /// \returns true if a serious error occurs, false otherwise.
7089 static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
7090 SourceLocation InstLoc,
7091 bool WasQualifiedName) {
7092 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
7093 DeclContext *CurContext = S.CurContext->getRedeclContext();
7095 if (CurContext->isRecord()) {
7096 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
7101 // C++11 [temp.explicit]p3:
7102 // An explicit instantiation shall appear in an enclosing namespace of its
7103 // template. If the name declared in the explicit instantiation is an
7104 // unqualified name, the explicit instantiation shall appear in the
7105 // namespace where its template is declared or, if that namespace is inline
7106 // (7.3.1), any namespace from its enclosing namespace set.
7108 // This is DR275, which we do not retroactively apply to C++98/03.
7109 if (WasQualifiedName) {
7110 if (CurContext->Encloses(OrigContext))
7113 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
7117 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
7118 if (WasQualifiedName)
7120 S.getLangOpts().CPlusPlus11?
7121 diag::err_explicit_instantiation_out_of_scope :
7122 diag::warn_explicit_instantiation_out_of_scope_0x)
7126 S.getLangOpts().CPlusPlus11?
7127 diag::err_explicit_instantiation_unqualified_wrong_namespace :
7128 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
7132 S.getLangOpts().CPlusPlus11?
7133 diag::err_explicit_instantiation_must_be_global :
7134 diag::warn_explicit_instantiation_must_be_global_0x)
7136 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
7140 /// \brief Determine whether the given scope specifier has a template-id in it.
7141 static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
7145 // C++11 [temp.explicit]p3:
7146 // If the explicit instantiation is for a member function, a member class
7147 // or a static data member of a class template specialization, the name of
7148 // the class template specialization in the qualified-id for the member
7149 // name shall be a simple-template-id.
7151 // C++98 has the same restriction, just worded differently.
7152 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
7153 NNS = NNS->getPrefix())
7154 if (const Type *T = NNS->getAsType())
7155 if (isa<TemplateSpecializationType>(T))
7161 // Explicit instantiation of a class template specialization
7163 Sema::ActOnExplicitInstantiation(Scope *S,
7164 SourceLocation ExternLoc,
7165 SourceLocation TemplateLoc,
7167 SourceLocation KWLoc,
7168 const CXXScopeSpec &SS,
7169 TemplateTy TemplateD,
7170 SourceLocation TemplateNameLoc,
7171 SourceLocation LAngleLoc,
7172 ASTTemplateArgsPtr TemplateArgsIn,
7173 SourceLocation RAngleLoc,
7174 AttributeList *Attr) {
7175 // Find the class template we're specializing
7176 TemplateName Name = TemplateD.get();
7177 TemplateDecl *TD = Name.getAsTemplateDecl();
7178 // Check that the specialization uses the same tag kind as the
7179 // original template.
7180 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7181 assert(Kind != TTK_Enum &&
7182 "Invalid enum tag in class template explicit instantiation!");
7184 if (isa<TypeAliasTemplateDecl>(TD)) {
7185 Diag(KWLoc, diag::err_tag_reference_non_tag) << Kind;
7186 Diag(TD->getTemplatedDecl()->getLocation(),
7187 diag::note_previous_use);
7191 ClassTemplateDecl *ClassTemplate = cast<ClassTemplateDecl>(TD);
7193 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
7194 Kind, /*isDefinition*/false, KWLoc,
7195 ClassTemplate->getIdentifier())) {
7196 Diag(KWLoc, diag::err_use_with_wrong_tag)
7198 << FixItHint::CreateReplacement(KWLoc,
7199 ClassTemplate->getTemplatedDecl()->getKindName());
7200 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
7201 diag::note_previous_use);
7202 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7205 // C++0x [temp.explicit]p2:
7206 // There are two forms of explicit instantiation: an explicit instantiation
7207 // definition and an explicit instantiation declaration. An explicit
7208 // instantiation declaration begins with the extern keyword. [...]
7209 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
7210 ? TSK_ExplicitInstantiationDefinition
7211 : TSK_ExplicitInstantiationDeclaration;
7213 if (TSK == TSK_ExplicitInstantiationDeclaration) {
7214 // Check for dllexport class template instantiation declarations.
7215 for (AttributeList *A = Attr; A; A = A->getNext()) {
7216 if (A->getKind() == AttributeList::AT_DLLExport) {
7218 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7219 Diag(A->getLoc(), diag::note_attribute);
7224 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
7226 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7227 Diag(A->getLocation(), diag::note_attribute);
7231 // Translate the parser's template argument list in our AST format.
7232 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
7233 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
7235 // Check that the template argument list is well-formed for this
7237 SmallVector<TemplateArgument, 4> Converted;
7238 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7239 TemplateArgs, false, Converted))
7242 // Find the class template specialization declaration that
7243 // corresponds to these arguments.
7244 void *InsertPos = nullptr;
7245 ClassTemplateSpecializationDecl *PrevDecl
7246 = ClassTemplate->findSpecialization(Converted, InsertPos);
7248 TemplateSpecializationKind PrevDecl_TSK
7249 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
7251 // C++0x [temp.explicit]p2:
7252 // [...] An explicit instantiation shall appear in an enclosing
7253 // namespace of its template. [...]
7255 // This is C++ DR 275.
7256 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
7260 ClassTemplateSpecializationDecl *Specialization = nullptr;
7262 bool HasNoEffect = false;
7264 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
7265 PrevDecl, PrevDecl_TSK,
7266 PrevDecl->getPointOfInstantiation(),
7270 // Even though HasNoEffect == true means that this explicit instantiation
7271 // has no effect on semantics, we go on to put its syntax in the AST.
7273 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
7274 PrevDecl_TSK == TSK_Undeclared) {
7275 // Since the only prior class template specialization with these
7276 // arguments was referenced but not declared, reuse that
7277 // declaration node as our own, updating the source location
7278 // for the template name to reflect our new declaration.
7279 // (Other source locations will be updated later.)
7280 Specialization = PrevDecl;
7281 Specialization->setLocation(TemplateNameLoc);
7286 if (!Specialization) {
7287 // Create a new class template specialization declaration node for
7288 // this explicit specialization.
7290 = ClassTemplateSpecializationDecl::Create(Context, Kind,
7291 ClassTemplate->getDeclContext(),
7292 KWLoc, TemplateNameLoc,
7297 SetNestedNameSpecifier(Specialization, SS);
7299 if (!HasNoEffect && !PrevDecl) {
7300 // Insert the new specialization.
7301 ClassTemplate->AddSpecialization(Specialization, InsertPos);
7305 // Build the fully-sugared type for this explicit instantiation as
7306 // the user wrote in the explicit instantiation itself. This means
7307 // that we'll pretty-print the type retrieved from the
7308 // specialization's declaration the way that the user actually wrote
7309 // the explicit instantiation, rather than formatting the name based
7310 // on the "canonical" representation used to store the template
7311 // arguments in the specialization.
7312 TypeSourceInfo *WrittenTy
7313 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7315 Context.getTypeDeclType(Specialization));
7316 Specialization->setTypeAsWritten(WrittenTy);
7318 // Set source locations for keywords.
7319 Specialization->setExternLoc(ExternLoc);
7320 Specialization->setTemplateKeywordLoc(TemplateLoc);
7321 Specialization->setRBraceLoc(SourceLocation());
7324 ProcessDeclAttributeList(S, Specialization, Attr);
7326 // Add the explicit instantiation into its lexical context. However,
7327 // since explicit instantiations are never found by name lookup, we
7328 // just put it into the declaration context directly.
7329 Specialization->setLexicalDeclContext(CurContext);
7330 CurContext->addDecl(Specialization);
7332 // Syntax is now OK, so return if it has no other effect on semantics.
7334 // Set the template specialization kind.
7335 Specialization->setTemplateSpecializationKind(TSK);
7336 return Specialization;
7339 // C++ [temp.explicit]p3:
7340 // A definition of a class template or class member template
7341 // shall be in scope at the point of the explicit instantiation of
7342 // the class template or class member template.
7344 // This check comes when we actually try to perform the
7346 ClassTemplateSpecializationDecl *Def
7347 = cast_or_null<ClassTemplateSpecializationDecl>(
7348 Specialization->getDefinition());
7350 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
7351 else if (TSK == TSK_ExplicitInstantiationDefinition) {
7352 MarkVTableUsed(TemplateNameLoc, Specialization, true);
7353 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
7356 // Instantiate the members of this class template specialization.
7357 Def = cast_or_null<ClassTemplateSpecializationDecl>(
7358 Specialization->getDefinition());
7360 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
7362 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
7363 // TSK_ExplicitInstantiationDefinition
7364 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
7365 TSK == TSK_ExplicitInstantiationDefinition) {
7366 // FIXME: Need to notify the ASTMutationListener that we did this.
7367 Def->setTemplateSpecializationKind(TSK);
7369 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
7370 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7371 // In the MS ABI, an explicit instantiation definition can add a dll
7372 // attribute to a template with a previous instantiation declaration.
7373 // MinGW doesn't allow this.
7374 auto *A = cast<InheritableAttr>(
7375 getDLLAttr(Specialization)->clone(getASTContext()));
7376 A->setInherited(true);
7378 checkClassLevelDLLAttribute(Def);
7380 // Propagate attribute to base class templates.
7381 for (auto &B : Def->bases()) {
7382 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
7383 B.getType()->getAsCXXRecordDecl()))
7384 propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getLocStart());
7389 // Set the template specialization kind. Make sure it is set before
7390 // instantiating the members which will trigger ASTConsumer callbacks.
7391 Specialization->setTemplateSpecializationKind(TSK);
7392 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
7395 // Set the template specialization kind.
7396 Specialization->setTemplateSpecializationKind(TSK);
7399 return Specialization;
7402 // Explicit instantiation of a member class of a class template.
7404 Sema::ActOnExplicitInstantiation(Scope *S,
7405 SourceLocation ExternLoc,
7406 SourceLocation TemplateLoc,
7408 SourceLocation KWLoc,
7410 IdentifierInfo *Name,
7411 SourceLocation NameLoc,
7412 AttributeList *Attr) {
7415 bool IsDependent = false;
7416 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
7417 KWLoc, SS, Name, NameLoc, Attr, AS_none,
7418 /*ModulePrivateLoc=*/SourceLocation(),
7419 MultiTemplateParamsArg(), Owned, IsDependent,
7420 SourceLocation(), false, TypeResult(),
7421 /*IsTypeSpecifier*/false);
7422 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
7427 TagDecl *Tag = cast<TagDecl>(TagD);
7428 assert(!Tag->isEnum() && "shouldn't see enumerations here");
7430 if (Tag->isInvalidDecl())
7433 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
7434 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
7436 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
7437 << Context.getTypeDeclType(Record);
7438 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
7442 // C++0x [temp.explicit]p2:
7443 // If the explicit instantiation is for a class or member class, the
7444 // elaborated-type-specifier in the declaration shall include a
7445 // simple-template-id.
7447 // C++98 has the same restriction, just worded differently.
7448 if (!ScopeSpecifierHasTemplateId(SS))
7449 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
7450 << Record << SS.getRange();
7452 // C++0x [temp.explicit]p2:
7453 // There are two forms of explicit instantiation: an explicit instantiation
7454 // definition and an explicit instantiation declaration. An explicit
7455 // instantiation declaration begins with the extern keyword. [...]
7456 TemplateSpecializationKind TSK
7457 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7458 : TSK_ExplicitInstantiationDeclaration;
7460 // C++0x [temp.explicit]p2:
7461 // [...] An explicit instantiation shall appear in an enclosing
7462 // namespace of its template. [...]
7464 // This is C++ DR 275.
7465 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
7467 // Verify that it is okay to explicitly instantiate here.
7468 CXXRecordDecl *PrevDecl
7469 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
7470 if (!PrevDecl && Record->getDefinition())
7473 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
7474 bool HasNoEffect = false;
7475 assert(MSInfo && "No member specialization information?");
7476 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
7478 MSInfo->getTemplateSpecializationKind(),
7479 MSInfo->getPointOfInstantiation(),
7486 CXXRecordDecl *RecordDef
7487 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
7489 // C++ [temp.explicit]p3:
7490 // A definition of a member class of a class template shall be in scope
7491 // at the point of an explicit instantiation of the member class.
7493 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
7495 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
7496 << 0 << Record->getDeclName() << Record->getDeclContext();
7497 Diag(Pattern->getLocation(), diag::note_forward_declaration)
7501 if (InstantiateClass(NameLoc, Record, Def,
7502 getTemplateInstantiationArgs(Record),
7506 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
7512 // Instantiate all of the members of the class.
7513 InstantiateClassMembers(NameLoc, RecordDef,
7514 getTemplateInstantiationArgs(Record), TSK);
7516 if (TSK == TSK_ExplicitInstantiationDefinition)
7517 MarkVTableUsed(NameLoc, RecordDef, true);
7519 // FIXME: We don't have any representation for explicit instantiations of
7520 // member classes. Such a representation is not needed for compilation, but it
7521 // should be available for clients that want to see all of the declarations in
7526 DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
7527 SourceLocation ExternLoc,
7528 SourceLocation TemplateLoc,
7530 // Explicit instantiations always require a name.
7531 // TODO: check if/when DNInfo should replace Name.
7532 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7533 DeclarationName Name = NameInfo.getName();
7535 if (!D.isInvalidType())
7536 Diag(D.getDeclSpec().getLocStart(),
7537 diag::err_explicit_instantiation_requires_name)
7538 << D.getDeclSpec().getSourceRange()
7539 << D.getSourceRange();
7544 // The scope passed in may not be a decl scope. Zip up the scope tree until
7545 // we find one that is.
7546 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7547 (S->getFlags() & Scope::TemplateParamScope) != 0)
7550 // Determine the type of the declaration.
7551 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
7552 QualType R = T->getType();
7557 // A storage-class-specifier shall not be specified in [...] an explicit
7558 // instantiation (14.7.2) directive.
7559 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
7560 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
7563 } else if (D.getDeclSpec().getStorageClassSpec()
7564 != DeclSpec::SCS_unspecified) {
7565 // Complain about then remove the storage class specifier.
7566 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
7567 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7569 D.getMutableDeclSpec().ClearStorageClassSpecs();
7572 // C++0x [temp.explicit]p1:
7573 // [...] An explicit instantiation of a function template shall not use the
7574 // inline or constexpr specifiers.
7575 // Presumably, this also applies to member functions of class templates as
7577 if (D.getDeclSpec().isInlineSpecified())
7578 Diag(D.getDeclSpec().getInlineSpecLoc(),
7579 getLangOpts().CPlusPlus11 ?
7580 diag::err_explicit_instantiation_inline :
7581 diag::warn_explicit_instantiation_inline_0x)
7582 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7583 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
7584 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
7585 // not already specified.
7586 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7587 diag::err_explicit_instantiation_constexpr);
7589 // C++0x [temp.explicit]p2:
7590 // There are two forms of explicit instantiation: an explicit instantiation
7591 // definition and an explicit instantiation declaration. An explicit
7592 // instantiation declaration begins with the extern keyword. [...]
7593 TemplateSpecializationKind TSK
7594 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7595 : TSK_ExplicitInstantiationDeclaration;
7597 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
7598 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
7600 if (!R->isFunctionType()) {
7601 // C++ [temp.explicit]p1:
7602 // A [...] static data member of a class template can be explicitly
7603 // instantiated from the member definition associated with its class
7605 // C++1y [temp.explicit]p1:
7606 // A [...] variable [...] template specialization can be explicitly
7607 // instantiated from its template.
7608 if (Previous.isAmbiguous())
7611 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
7612 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
7614 if (!PrevTemplate) {
7615 if (!Prev || !Prev->isStaticDataMember()) {
7616 // We expect to see a data data member here.
7617 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
7619 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7621 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
7625 if (!Prev->getInstantiatedFromStaticDataMember()) {
7626 // FIXME: Check for explicit specialization?
7627 Diag(D.getIdentifierLoc(),
7628 diag::err_explicit_instantiation_data_member_not_instantiated)
7630 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
7631 // FIXME: Can we provide a note showing where this was declared?
7635 // Explicitly instantiate a variable template.
7637 // C++1y [dcl.spec.auto]p6:
7638 // ... A program that uses auto or decltype(auto) in a context not
7639 // explicitly allowed in this section is ill-formed.
7641 // This includes auto-typed variable template instantiations.
7642 if (R->isUndeducedType()) {
7643 Diag(T->getTypeLoc().getLocStart(),
7644 diag::err_auto_not_allowed_var_inst);
7648 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7649 // C++1y [temp.explicit]p3:
7650 // If the explicit instantiation is for a variable, the unqualified-id
7651 // in the declaration shall be a template-id.
7652 Diag(D.getIdentifierLoc(),
7653 diag::err_explicit_instantiation_without_template_id)
7655 Diag(PrevTemplate->getLocation(),
7656 diag::note_explicit_instantiation_here);
7660 // Translate the parser's template argument list into our AST format.
7661 TemplateArgumentListInfo TemplateArgs =
7662 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
7664 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
7665 D.getIdentifierLoc(), TemplateArgs);
7666 if (Res.isInvalid())
7669 // Ignore access control bits, we don't need them for redeclaration
7671 Prev = cast<VarDecl>(Res.get());
7674 // C++0x [temp.explicit]p2:
7675 // If the explicit instantiation is for a member function, a member class
7676 // or a static data member of a class template specialization, the name of
7677 // the class template specialization in the qualified-id for the member
7678 // name shall be a simple-template-id.
7680 // C++98 has the same restriction, just worded differently.
7682 // This does not apply to variable template specializations, where the
7683 // template-id is in the unqualified-id instead.
7684 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
7685 Diag(D.getIdentifierLoc(),
7686 diag::ext_explicit_instantiation_without_qualified_id)
7687 << Prev << D.getCXXScopeSpec().getRange();
7689 // Check the scope of this explicit instantiation.
7690 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
7692 // Verify that it is okay to explicitly instantiate here.
7693 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
7694 SourceLocation POI = Prev->getPointOfInstantiation();
7695 bool HasNoEffect = false;
7696 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
7697 PrevTSK, POI, HasNoEffect))
7701 // Instantiate static data member or variable template.
7703 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
7705 // Merge attributes.
7706 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
7707 ProcessDeclAttributeList(S, Prev, Attr);
7709 if (TSK == TSK_ExplicitInstantiationDefinition)
7710 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
7713 // Check the new variable specialization against the parsed input.
7714 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
7715 Diag(T->getTypeLoc().getLocStart(),
7716 diag::err_invalid_var_template_spec_type)
7717 << 0 << PrevTemplate << R << Prev->getType();
7718 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
7719 << 2 << PrevTemplate->getDeclName();
7723 // FIXME: Create an ExplicitInstantiation node?
7724 return (Decl*) nullptr;
7727 // If the declarator is a template-id, translate the parser's template
7728 // argument list into our AST format.
7729 bool HasExplicitTemplateArgs = false;
7730 TemplateArgumentListInfo TemplateArgs;
7731 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7732 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
7733 HasExplicitTemplateArgs = true;
7736 // C++ [temp.explicit]p1:
7737 // A [...] function [...] can be explicitly instantiated from its template.
7738 // A member function [...] of a class template can be explicitly
7739 // instantiated from the member definition associated with its class
7741 UnresolvedSet<8> Matches;
7742 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
7743 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7745 NamedDecl *Prev = *P;
7746 if (!HasExplicitTemplateArgs) {
7747 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
7748 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType());
7749 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
7752 Matches.addDecl(Method, P.getAccess());
7753 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
7759 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
7763 TemplateDeductionInfo Info(FailedCandidates.getLocation());
7764 FunctionDecl *Specialization = nullptr;
7765 if (TemplateDeductionResult TDK
7766 = DeduceTemplateArguments(FunTmpl,
7767 (HasExplicitTemplateArgs ? &TemplateArgs
7769 R, Specialization, Info)) {
7770 // Keep track of almost-matches.
7771 FailedCandidates.addCandidate()
7772 .set(FunTmpl->getTemplatedDecl(),
7773 MakeDeductionFailureInfo(Context, TDK, Info));
7778 Matches.addDecl(Specialization, P.getAccess());
7781 // Find the most specialized function template specialization.
7782 UnresolvedSetIterator Result = getMostSpecialized(
7783 Matches.begin(), Matches.end(), FailedCandidates,
7784 D.getIdentifierLoc(),
7785 PDiag(diag::err_explicit_instantiation_not_known) << Name,
7786 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
7787 PDiag(diag::note_explicit_instantiation_candidate));
7789 if (Result == Matches.end())
7792 // Ignore access control bits, we don't need them for redeclaration checking.
7793 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
7795 // C++11 [except.spec]p4
7796 // In an explicit instantiation an exception-specification may be specified,
7797 // but is not required.
7798 // If an exception-specification is specified in an explicit instantiation
7799 // directive, it shall be compatible with the exception-specifications of
7800 // other declarations of that function.
7801 if (auto *FPT = R->getAs<FunctionProtoType>())
7802 if (FPT->hasExceptionSpec()) {
7804 diag::err_mismatched_exception_spec_explicit_instantiation;
7805 if (getLangOpts().MicrosoftExt)
7806 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
7807 bool Result = CheckEquivalentExceptionSpec(
7808 PDiag(DiagID) << Specialization->getType(),
7809 PDiag(diag::note_explicit_instantiation_here),
7810 Specialization->getType()->getAs<FunctionProtoType>(),
7811 Specialization->getLocation(), FPT, D.getLocStart());
7812 // In Microsoft mode, mismatching exception specifications just cause a
7814 if (!getLangOpts().MicrosoftExt && Result)
7818 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
7819 Diag(D.getIdentifierLoc(),
7820 diag::err_explicit_instantiation_member_function_not_instantiated)
7822 << (Specialization->getTemplateSpecializationKind() ==
7823 TSK_ExplicitSpecialization);
7824 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
7828 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
7829 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
7830 PrevDecl = Specialization;
7833 bool HasNoEffect = false;
7834 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
7836 PrevDecl->getTemplateSpecializationKind(),
7837 PrevDecl->getPointOfInstantiation(),
7841 // FIXME: We may still want to build some representation of this
7842 // explicit specialization.
7844 return (Decl*) nullptr;
7847 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
7848 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
7850 ProcessDeclAttributeList(S, Specialization, Attr);
7852 if (Specialization->isDefined()) {
7853 // Let the ASTConsumer know that this function has been explicitly
7854 // instantiated now, and its linkage might have changed.
7855 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
7856 } else if (TSK == TSK_ExplicitInstantiationDefinition)
7857 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
7859 // C++0x [temp.explicit]p2:
7860 // If the explicit instantiation is for a member function, a member class
7861 // or a static data member of a class template specialization, the name of
7862 // the class template specialization in the qualified-id for the member
7863 // name shall be a simple-template-id.
7865 // C++98 has the same restriction, just worded differently.
7866 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
7867 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
7868 D.getCXXScopeSpec().isSet() &&
7869 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
7870 Diag(D.getIdentifierLoc(),
7871 diag::ext_explicit_instantiation_without_qualified_id)
7872 << Specialization << D.getCXXScopeSpec().getRange();
7874 CheckExplicitInstantiationScope(*this,
7875 FunTmpl? (NamedDecl *)FunTmpl
7876 : Specialization->getInstantiatedFromMemberFunction(),
7877 D.getIdentifierLoc(),
7878 D.getCXXScopeSpec().isSet());
7880 // FIXME: Create some kind of ExplicitInstantiationDecl here.
7881 return (Decl*) nullptr;
7885 Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
7886 const CXXScopeSpec &SS, IdentifierInfo *Name,
7887 SourceLocation TagLoc, SourceLocation NameLoc) {
7888 // This has to hold, because SS is expected to be defined.
7889 assert(Name && "Expected a name in a dependent tag");
7891 NestedNameSpecifier *NNS = SS.getScopeRep();
7895 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7897 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
7898 Diag(NameLoc, diag::err_dependent_tag_decl)
7899 << (TUK == TUK_Definition) << Kind << SS.getRange();
7903 // Create the resulting type.
7904 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
7905 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
7907 // Create type-source location information for this type.
7909 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
7910 TL.setElaboratedKeywordLoc(TagLoc);
7911 TL.setQualifierLoc(SS.getWithLocInContext(Context));
7912 TL.setNameLoc(NameLoc);
7913 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
7917 Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
7918 const CXXScopeSpec &SS, const IdentifierInfo &II,
7919 SourceLocation IdLoc) {
7923 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
7925 getLangOpts().CPlusPlus11 ?
7926 diag::warn_cxx98_compat_typename_outside_of_template :
7927 diag::ext_typename_outside_of_template)
7928 << FixItHint::CreateRemoval(TypenameLoc);
7930 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
7931 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
7932 TypenameLoc, QualifierLoc, II, IdLoc);
7936 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
7937 if (isa<DependentNameType>(T)) {
7938 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
7939 TL.setElaboratedKeywordLoc(TypenameLoc);
7940 TL.setQualifierLoc(QualifierLoc);
7941 TL.setNameLoc(IdLoc);
7943 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
7944 TL.setElaboratedKeywordLoc(TypenameLoc);
7945 TL.setQualifierLoc(QualifierLoc);
7946 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
7949 return CreateParsedType(T, TSI);
7953 Sema::ActOnTypenameType(Scope *S,
7954 SourceLocation TypenameLoc,
7955 const CXXScopeSpec &SS,
7956 SourceLocation TemplateKWLoc,
7957 TemplateTy TemplateIn,
7958 SourceLocation TemplateNameLoc,
7959 SourceLocation LAngleLoc,
7960 ASTTemplateArgsPtr TemplateArgsIn,
7961 SourceLocation RAngleLoc) {
7962 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
7964 getLangOpts().CPlusPlus11 ?
7965 diag::warn_cxx98_compat_typename_outside_of_template :
7966 diag::ext_typename_outside_of_template)
7967 << FixItHint::CreateRemoval(TypenameLoc);
7969 // Translate the parser's template argument list in our AST format.
7970 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
7971 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
7973 TemplateName Template = TemplateIn.get();
7974 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
7975 // Construct a dependent template specialization type.
7976 assert(DTN && "dependent template has non-dependent name?");
7977 assert(DTN->getQualifier() == SS.getScopeRep());
7978 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
7979 DTN->getQualifier(),
7980 DTN->getIdentifier(),
7983 // Create source-location information for this type.
7984 TypeLocBuilder Builder;
7985 DependentTemplateSpecializationTypeLoc SpecTL
7986 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
7987 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
7988 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
7989 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
7990 SpecTL.setTemplateNameLoc(TemplateNameLoc);
7991 SpecTL.setLAngleLoc(LAngleLoc);
7992 SpecTL.setRAngleLoc(RAngleLoc);
7993 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7994 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
7995 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
7998 QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
8002 // Provide source-location information for the template specialization type.
8003 TypeLocBuilder Builder;
8004 TemplateSpecializationTypeLoc SpecTL
8005 = Builder.push<TemplateSpecializationTypeLoc>(T);
8006 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
8007 SpecTL.setTemplateNameLoc(TemplateNameLoc);
8008 SpecTL.setLAngleLoc(LAngleLoc);
8009 SpecTL.setRAngleLoc(RAngleLoc);
8010 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8011 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
8013 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
8014 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
8015 TL.setElaboratedKeywordLoc(TypenameLoc);
8016 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8018 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
8019 return CreateParsedType(T, TSI);
8023 /// Determine whether this failed name lookup should be treated as being
8024 /// disabled by a usage of std::enable_if.
8025 static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
8026 SourceRange &CondRange) {
8027 // We must be looking for a ::type...
8028 if (!II.isStr("type"))
8031 // ... within an explicitly-written template specialization...
8032 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
8034 TypeLoc EnableIfTy = NNS.getTypeLoc();
8035 TemplateSpecializationTypeLoc EnableIfTSTLoc =
8036 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
8037 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
8039 const TemplateSpecializationType *EnableIfTST =
8040 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
8042 // ... which names a complete class template declaration...
8043 const TemplateDecl *EnableIfDecl =
8044 EnableIfTST->getTemplateName().getAsTemplateDecl();
8045 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
8048 // ... called "enable_if".
8049 const IdentifierInfo *EnableIfII =
8050 EnableIfDecl->getDeclName().getAsIdentifierInfo();
8051 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
8054 // Assume the first template argument is the condition.
8055 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
8059 /// \brief Build the type that describes a C++ typename specifier,
8060 /// e.g., "typename T::type".
8062 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
8063 SourceLocation KeywordLoc,
8064 NestedNameSpecifierLoc QualifierLoc,
8065 const IdentifierInfo &II,
8066 SourceLocation IILoc) {
8068 SS.Adopt(QualifierLoc);
8070 DeclContext *Ctx = computeDeclContext(SS);
8072 // If the nested-name-specifier is dependent and couldn't be
8073 // resolved to a type, build a typename type.
8074 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
8075 return Context.getDependentNameType(Keyword,
8076 QualifierLoc.getNestedNameSpecifier(),
8080 // If the nested-name-specifier refers to the current instantiation,
8081 // the "typename" keyword itself is superfluous. In C++03, the
8082 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
8083 // allows such extraneous "typename" keywords, and we retroactively
8084 // apply this DR to C++03 code with only a warning. In any case we continue.
8086 if (RequireCompleteDeclContext(SS, Ctx))
8089 DeclarationName Name(&II);
8090 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
8091 LookupQualifiedName(Result, Ctx, SS);
8092 unsigned DiagID = 0;
8093 Decl *Referenced = nullptr;
8094 switch (Result.getResultKind()) {
8095 case LookupResult::NotFound: {
8096 // If we're looking up 'type' within a template named 'enable_if', produce
8097 // a more specific diagnostic.
8098 SourceRange CondRange;
8099 if (isEnableIf(QualifierLoc, II, CondRange)) {
8100 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
8101 << Ctx << CondRange;
8105 DiagID = diag::err_typename_nested_not_found;
8109 case LookupResult::FoundUnresolvedValue: {
8110 // We found a using declaration that is a value. Most likely, the using
8111 // declaration itself is meant to have the 'typename' keyword.
8112 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
8114 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
8115 << Name << Ctx << FullRange;
8116 if (UnresolvedUsingValueDecl *Using
8117 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
8118 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
8119 Diag(Loc, diag::note_using_value_decl_missing_typename)
8120 << FixItHint::CreateInsertion(Loc, "typename ");
8123 // Fall through to create a dependent typename type, from which we can recover
8126 case LookupResult::NotFoundInCurrentInstantiation:
8127 // Okay, it's a member of an unknown instantiation.
8128 return Context.getDependentNameType(Keyword,
8129 QualifierLoc.getNestedNameSpecifier(),
8132 case LookupResult::Found:
8133 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
8134 // We found a type. Build an ElaboratedType, since the
8135 // typename-specifier was just sugar.
8136 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
8137 return Context.getElaboratedType(ETK_Typename,
8138 QualifierLoc.getNestedNameSpecifier(),
8139 Context.getTypeDeclType(Type));
8142 DiagID = diag::err_typename_nested_not_type;
8143 Referenced = Result.getFoundDecl();
8146 case LookupResult::FoundOverloaded:
8147 DiagID = diag::err_typename_nested_not_type;
8148 Referenced = *Result.begin();
8151 case LookupResult::Ambiguous:
8155 // If we get here, it's because name lookup did not find a
8156 // type. Emit an appropriate diagnostic and return an error.
8157 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
8159 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
8161 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
8167 // See Sema::RebuildTypeInCurrentInstantiation
8168 class CurrentInstantiationRebuilder
8169 : public TreeTransform<CurrentInstantiationRebuilder> {
8171 DeclarationName Entity;
8174 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
8176 CurrentInstantiationRebuilder(Sema &SemaRef,
8178 DeclarationName Entity)
8179 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
8180 Loc(Loc), Entity(Entity) { }
8182 /// \brief Determine whether the given type \p T has already been
8185 /// For the purposes of type reconstruction, a type has already been
8186 /// transformed if it is NULL or if it is not dependent.
8187 bool AlreadyTransformed(QualType T) {
8188 return T.isNull() || !T->isDependentType();
8191 /// \brief Returns the location of the entity whose type is being
8193 SourceLocation getBaseLocation() { return Loc; }
8195 /// \brief Returns the name of the entity whose type is being rebuilt.
8196 DeclarationName getBaseEntity() { return Entity; }
8198 /// \brief Sets the "base" location and entity when that
8199 /// information is known based on another transformation.
8200 void setBase(SourceLocation Loc, DeclarationName Entity) {
8202 this->Entity = Entity;
8205 ExprResult TransformLambdaExpr(LambdaExpr *E) {
8206 // Lambdas never need to be transformed.
8212 /// \brief Rebuilds a type within the context of the current instantiation.
8214 /// The type \p T is part of the type of an out-of-line member definition of
8215 /// a class template (or class template partial specialization) that was parsed
8216 /// and constructed before we entered the scope of the class template (or
8217 /// partial specialization thereof). This routine will rebuild that type now
8218 /// that we have entered the declarator's scope, which may produce different
8219 /// canonical types, e.g.,
8222 /// template<typename T>
8224 /// typedef T* pointer;
8228 /// template<typename T>
8229 /// typename X<T>::pointer X<T>::data() { ... }
8232 /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
8233 /// since we do not know that we can look into X<T> when we parsed the type.
8234 /// This function will rebuild the type, performing the lookup of "pointer"
8235 /// in X<T> and returning an ElaboratedType whose canonical type is the same
8236 /// as the canonical type of T*, allowing the return types of the out-of-line
8237 /// definition and the declaration to match.
8238 TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
8240 DeclarationName Name) {
8241 if (!T || !T->getType()->isDependentType())
8244 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
8245 return Rebuilder.TransformType(T);
8248 ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
8249 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
8251 return Rebuilder.TransformExpr(E);
8254 bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
8258 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
8259 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
8261 NestedNameSpecifierLoc Rebuilt
8262 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
8270 /// \brief Rebuild the template parameters now that we know we're in a current
8272 bool Sema::RebuildTemplateParamsInCurrentInstantiation(
8273 TemplateParameterList *Params) {
8274 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8275 Decl *Param = Params->getParam(I);
8277 // There is nothing to rebuild in a type parameter.
8278 if (isa<TemplateTypeParmDecl>(Param))
8281 // Rebuild the template parameter list of a template template parameter.
8282 if (TemplateTemplateParmDecl *TTP
8283 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
8284 if (RebuildTemplateParamsInCurrentInstantiation(
8285 TTP->getTemplateParameters()))
8291 // Rebuild the type of a non-type template parameter.
8292 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
8293 TypeSourceInfo *NewTSI
8294 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
8295 NTTP->getLocation(),
8296 NTTP->getDeclName());
8300 if (NewTSI != NTTP->getTypeSourceInfo()) {
8301 NTTP->setTypeSourceInfo(NewTSI);
8302 NTTP->setType(NewTSI->getType());
8309 /// \brief Produces a formatted string that describes the binding of
8310 /// template parameters to template arguments.
8312 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8313 const TemplateArgumentList &Args) {
8314 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
8318 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8319 const TemplateArgument *Args,
8321 SmallString<128> Str;
8322 llvm::raw_svector_ostream Out(Str);
8324 if (!Params || Params->size() == 0 || NumArgs == 0)
8325 return std::string();
8327 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8336 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
8337 Out << Id->getName();
8343 Args[I].print(getPrintingPolicy(), Out);
8350 void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
8351 CachedTokens &Toks) {
8355 LateParsedTemplate *LPT = new LateParsedTemplate;
8357 // Take tokens to avoid allocations
8358 LPT->Toks.swap(Toks);
8360 LateParsedTemplateMap.insert(std::make_pair(FD, LPT));
8362 FD->setLateTemplateParsed(true);
8365 void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
8368 FD->setLateTemplateParsed(false);
8371 bool Sema::IsInsideALocalClassWithinATemplateFunction() {
8372 DeclContext *DC = CurContext;
8375 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
8376 const FunctionDecl *FD = RD->isLocalClass();
8377 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
8378 } else if (DC->isTranslationUnit() || DC->isNamespace())
8381 DC = DC->getParent();