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, false);
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, false);
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(DefaultArg, false);
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;
896 LookupName(Previous, S);
899 if (Previous.isAmbiguous())
902 NamedDecl *PrevDecl = nullptr;
903 if (Previous.begin() != Previous.end())
904 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
906 // If there is a previous declaration with the same name, check
907 // whether this is a valid redeclaration.
908 ClassTemplateDecl *PrevClassTemplate
909 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
911 // We may have found the injected-class-name of a class template,
912 // class template partial specialization, or class template specialization.
913 // In these cases, grab the template that is being defined or specialized.
914 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
915 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
916 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
918 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
919 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
921 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
922 ->getSpecializedTemplate();
926 if (TUK == TUK_Friend) {
927 // C++ [namespace.memdef]p3:
928 // [...] When looking for a prior declaration of a class or a function
929 // declared as a friend, and when the name of the friend class or
930 // function is neither a qualified name nor a template-id, scopes outside
931 // the innermost enclosing namespace scope are not considered.
933 DeclContext *OutermostContext = CurContext;
934 while (!OutermostContext->isFileContext())
935 OutermostContext = OutermostContext->getLookupParent();
938 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
939 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
940 SemanticContext = PrevDecl->getDeclContext();
942 // Declarations in outer scopes don't matter. However, the outermost
943 // context we computed is the semantic context for our new
945 PrevDecl = PrevClassTemplate = nullptr;
946 SemanticContext = OutermostContext;
948 // Check that the chosen semantic context doesn't already contain a
949 // declaration of this name as a non-tag type.
950 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
952 DeclContext *LookupContext = SemanticContext;
953 while (LookupContext->isTransparentContext())
954 LookupContext = LookupContext->getLookupParent();
955 LookupQualifiedName(Previous, LookupContext);
957 if (Previous.isAmbiguous())
960 if (Previous.begin() != Previous.end())
961 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
964 } else if (PrevDecl &&
965 !isDeclInScope(PrevDecl, SemanticContext, S, SS.isValid()))
966 PrevDecl = PrevClassTemplate = nullptr;
968 if (PrevClassTemplate) {
969 // Ensure that the template parameter lists are compatible. Skip this check
970 // for a friend in a dependent context: the template parameter list itself
971 // could be dependent.
972 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
973 !TemplateParameterListsAreEqual(TemplateParams,
974 PrevClassTemplate->getTemplateParameters(),
979 // C++ [temp.class]p4:
980 // In a redeclaration, partial specialization, explicit
981 // specialization or explicit instantiation of a class template,
982 // the class-key shall agree in kind with the original class
983 // template declaration (7.1.5.3).
984 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
985 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
986 TUK == TUK_Definition, KWLoc, *Name)) {
987 Diag(KWLoc, diag::err_use_with_wrong_tag)
989 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
990 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
991 Kind = PrevRecordDecl->getTagKind();
994 // Check for redefinition of this class template.
995 if (TUK == TUK_Definition) {
996 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
997 // If we have a prior definition that is not visible, treat this as
998 // simply making that previous definition visible.
999 NamedDecl *Hidden = nullptr;
1000 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
1001 SkipBody->ShouldSkip = true;
1002 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1003 assert(Tmpl && "original definition of a class template is not a "
1005 makeMergedDefinitionVisible(Hidden, KWLoc);
1006 makeMergedDefinitionVisible(Tmpl, KWLoc);
1010 Diag(NameLoc, diag::err_redefinition) << Name;
1011 Diag(Def->getLocation(), diag::note_previous_definition);
1012 // FIXME: Would it make sense to try to "forget" the previous
1013 // definition, as part of error recovery?
1017 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
1018 // Maybe we will complain about the shadowed template parameter.
1019 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1020 // Just pretend that we didn't see the previous declaration.
1022 } else if (PrevDecl) {
1024 // A class template shall not have the same name as any other
1025 // template, class, function, object, enumeration, enumerator,
1026 // namespace, or type in the same scope (3.3), except as specified
1028 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1029 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1033 // Check the template parameter list of this declaration, possibly
1034 // merging in the template parameter list from the previous class
1035 // template declaration. Skip this check for a friend in a dependent
1036 // context, because the template parameter list might be dependent.
1037 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1038 CheckTemplateParameterList(
1040 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1042 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1043 SemanticContext->isDependentContext())
1044 ? TPC_ClassTemplateMember
1045 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1046 : TPC_ClassTemplate))
1050 // If the name of the template was qualified, we must be defining the
1051 // template out-of-line.
1052 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1053 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
1054 : diag::err_member_decl_does_not_match)
1055 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
1060 CXXRecordDecl *NewClass =
1061 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
1063 PrevClassTemplate->getTemplatedDecl() : nullptr,
1064 /*DelayTypeCreation=*/true);
1065 SetNestedNameSpecifier(NewClass, SS);
1066 if (NumOuterTemplateParamLists > 0)
1067 NewClass->setTemplateParameterListsInfo(Context,
1068 NumOuterTemplateParamLists,
1069 OuterTemplateParamLists);
1071 // Add alignment attributes if necessary; these attributes are checked when
1072 // the ASTContext lays out the structure.
1073 if (TUK == TUK_Definition) {
1074 AddAlignmentAttributesForRecord(NewClass);
1075 AddMsStructLayoutForRecord(NewClass);
1078 ClassTemplateDecl *NewTemplate
1079 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1080 DeclarationName(Name), TemplateParams,
1081 NewClass, PrevClassTemplate);
1082 NewClass->setDescribedClassTemplate(NewTemplate);
1084 if (ModulePrivateLoc.isValid())
1085 NewTemplate->setModulePrivate();
1087 // Build the type for the class template declaration now.
1088 QualType T = NewTemplate->getInjectedClassNameSpecialization();
1089 T = Context.getInjectedClassNameType(NewClass, T);
1090 assert(T->isDependentType() && "Class template type is not dependent?");
1093 // If we are providing an explicit specialization of a member that is a
1094 // class template, make a note of that.
1095 if (PrevClassTemplate &&
1096 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1097 PrevClassTemplate->setMemberSpecialization();
1099 // Set the access specifier.
1100 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
1101 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
1103 // Set the lexical context of these templates
1104 NewClass->setLexicalDeclContext(CurContext);
1105 NewTemplate->setLexicalDeclContext(CurContext);
1107 if (TUK == TUK_Definition)
1108 NewClass->startDefinition();
1111 ProcessDeclAttributeList(S, NewClass, Attr);
1113 if (PrevClassTemplate)
1114 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1116 AddPushedVisibilityAttribute(NewClass);
1118 if (TUK != TUK_Friend) {
1119 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1121 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1122 Outer = Outer->getParent();
1123 PushOnScopeChains(NewTemplate, Outer);
1125 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
1126 NewTemplate->setAccess(PrevClassTemplate->getAccess());
1127 NewClass->setAccess(PrevClassTemplate->getAccess());
1130 NewTemplate->setObjectOfFriendDecl();
1132 // Friend templates are visible in fairly strange ways.
1133 if (!CurContext->isDependentContext()) {
1134 DeclContext *DC = SemanticContext->getRedeclContext();
1135 DC->makeDeclVisibleInContext(NewTemplate);
1136 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1137 PushOnScopeChains(NewTemplate, EnclosingScope,
1138 /* AddToContext = */ false);
1141 FriendDecl *Friend = FriendDecl::Create(
1142 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
1143 Friend->setAccess(AS_public);
1144 CurContext->addDecl(Friend);
1148 NewTemplate->setInvalidDecl();
1149 NewClass->setInvalidDecl();
1152 ActOnDocumentableDecl(NewTemplate);
1157 /// \brief Diagnose the presence of a default template argument on a
1158 /// template parameter, which is ill-formed in certain contexts.
1160 /// \returns true if the default template argument should be dropped.
1161 static bool DiagnoseDefaultTemplateArgument(Sema &S,
1162 Sema::TemplateParamListContext TPC,
1163 SourceLocation ParamLoc,
1164 SourceRange DefArgRange) {
1166 case Sema::TPC_ClassTemplate:
1167 case Sema::TPC_VarTemplate:
1168 case Sema::TPC_TypeAliasTemplate:
1171 case Sema::TPC_FunctionTemplate:
1172 case Sema::TPC_FriendFunctionTemplateDefinition:
1173 // C++ [temp.param]p9:
1174 // A default template-argument shall not be specified in a
1175 // function template declaration or a function template
1177 // If a friend function template declaration specifies a default
1178 // template-argument, that declaration shall be a definition and shall be
1179 // the only declaration of the function template in the translation unit.
1180 // (C++98/03 doesn't have this wording; see DR226).
1181 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
1182 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1183 : diag::ext_template_parameter_default_in_function_template)
1187 case Sema::TPC_ClassTemplateMember:
1188 // C++0x [temp.param]p9:
1189 // A default template-argument shall not be specified in the
1190 // template-parameter-lists of the definition of a member of a
1191 // class template that appears outside of the member's class.
1192 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1196 case Sema::TPC_FriendClassTemplate:
1197 case Sema::TPC_FriendFunctionTemplate:
1198 // C++ [temp.param]p9:
1199 // A default template-argument shall not be specified in a
1200 // friend template declaration.
1201 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1205 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1206 // for friend function templates if there is only a single
1207 // declaration (and it is a definition). Strange!
1210 llvm_unreachable("Invalid TemplateParamListContext!");
1213 /// \brief Check for unexpanded parameter packs within the template parameters
1214 /// of a template template parameter, recursively.
1215 static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1216 TemplateTemplateParmDecl *TTP) {
1217 // A template template parameter which is a parameter pack is also a pack
1219 if (TTP->isParameterPack())
1222 TemplateParameterList *Params = TTP->getTemplateParameters();
1223 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1224 NamedDecl *P = Params->getParam(I);
1225 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
1226 if (!NTTP->isParameterPack() &&
1227 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
1228 NTTP->getTypeSourceInfo(),
1229 Sema::UPPC_NonTypeTemplateParameterType))
1235 if (TemplateTemplateParmDecl *InnerTTP
1236 = dyn_cast<TemplateTemplateParmDecl>(P))
1237 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1244 /// \brief Checks the validity of a template parameter list, possibly
1245 /// considering the template parameter list from a previous
1248 /// If an "old" template parameter list is provided, it must be
1249 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
1250 /// template parameter list.
1252 /// \param NewParams Template parameter list for a new template
1253 /// declaration. This template parameter list will be updated with any
1254 /// default arguments that are carried through from the previous
1255 /// template parameter list.
1257 /// \param OldParams If provided, template parameter list from a
1258 /// previous declaration of the same template. Default template
1259 /// arguments will be merged from the old template parameter list to
1260 /// the new template parameter list.
1262 /// \param TPC Describes the context in which we are checking the given
1263 /// template parameter list.
1265 /// \returns true if an error occurred, false otherwise.
1266 bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
1267 TemplateParameterList *OldParams,
1268 TemplateParamListContext TPC) {
1269 bool Invalid = false;
1271 // C++ [temp.param]p10:
1272 // The set of default template-arguments available for use with a
1273 // template declaration or definition is obtained by merging the
1274 // default arguments from the definition (if in scope) and all
1275 // declarations in scope in the same way default function
1276 // arguments are (8.3.6).
1277 bool SawDefaultArgument = false;
1278 SourceLocation PreviousDefaultArgLoc;
1280 // Dummy initialization to avoid warnings.
1281 TemplateParameterList::iterator OldParam = NewParams->end();
1283 OldParam = OldParams->begin();
1285 bool RemoveDefaultArguments = false;
1286 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1287 NewParamEnd = NewParams->end();
1288 NewParam != NewParamEnd; ++NewParam) {
1289 // Variables used to diagnose redundant default arguments
1290 bool RedundantDefaultArg = false;
1291 SourceLocation OldDefaultLoc;
1292 SourceLocation NewDefaultLoc;
1294 // Variable used to diagnose missing default arguments
1295 bool MissingDefaultArg = false;
1297 // Variable used to diagnose non-final parameter packs
1298 bool SawParameterPack = false;
1300 if (TemplateTypeParmDecl *NewTypeParm
1301 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
1302 // Check the presence of a default argument here.
1303 if (NewTypeParm->hasDefaultArgument() &&
1304 DiagnoseDefaultTemplateArgument(*this, TPC,
1305 NewTypeParm->getLocation(),
1306 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1308 NewTypeParm->removeDefaultArgument();
1310 // Merge default arguments for template type parameters.
1311 TemplateTypeParmDecl *OldTypeParm
1312 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
1313 // FIXME: There might be a visible declaration of this template parameter.
1314 if (OldTypeParm && !LookupResult::isVisible(*this, OldTypeParm))
1315 OldTypeParm = nullptr;
1317 if (NewTypeParm->isParameterPack()) {
1318 assert(!NewTypeParm->hasDefaultArgument() &&
1319 "Parameter packs can't have a default argument!");
1320 SawParameterPack = true;
1321 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
1322 NewTypeParm->hasDefaultArgument()) {
1323 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1324 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1325 SawDefaultArgument = true;
1326 RedundantDefaultArg = true;
1327 PreviousDefaultArgLoc = NewDefaultLoc;
1328 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1329 // Merge the default argument from the old declaration to the
1331 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
1333 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1334 } else if (NewTypeParm->hasDefaultArgument()) {
1335 SawDefaultArgument = true;
1336 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1337 } else if (SawDefaultArgument)
1338 MissingDefaultArg = true;
1339 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
1340 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
1341 // Check for unexpanded parameter packs.
1342 if (!NewNonTypeParm->isParameterPack() &&
1343 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
1344 NewNonTypeParm->getTypeSourceInfo(),
1345 UPPC_NonTypeTemplateParameterType)) {
1350 // Check the presence of a default argument here.
1351 if (NewNonTypeParm->hasDefaultArgument() &&
1352 DiagnoseDefaultTemplateArgument(*this, TPC,
1353 NewNonTypeParm->getLocation(),
1354 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1355 NewNonTypeParm->removeDefaultArgument();
1358 // Merge default arguments for non-type template parameters
1359 NonTypeTemplateParmDecl *OldNonTypeParm
1360 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
1361 if (OldNonTypeParm && !LookupResult::isVisible(*this, OldNonTypeParm))
1362 OldNonTypeParm = nullptr;
1363 if (NewNonTypeParm->isParameterPack()) {
1364 assert(!NewNonTypeParm->hasDefaultArgument() &&
1365 "Parameter packs can't have a default argument!");
1366 if (!NewNonTypeParm->isPackExpansion())
1367 SawParameterPack = true;
1368 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
1369 NewNonTypeParm->hasDefaultArgument()) {
1370 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1371 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1372 SawDefaultArgument = true;
1373 RedundantDefaultArg = true;
1374 PreviousDefaultArgLoc = NewDefaultLoc;
1375 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1376 // Merge the default argument from the old declaration to the
1378 // FIXME: We need to create a new kind of "default argument"
1379 // expression that points to a previous non-type template
1381 NewNonTypeParm->setDefaultArgument(
1382 OldNonTypeParm->getDefaultArgument(),
1383 /*Inherited=*/ true);
1384 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1385 } else if (NewNonTypeParm->hasDefaultArgument()) {
1386 SawDefaultArgument = true;
1387 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1388 } else if (SawDefaultArgument)
1389 MissingDefaultArg = true;
1391 TemplateTemplateParmDecl *NewTemplateParm
1392 = cast<TemplateTemplateParmDecl>(*NewParam);
1394 // Check for unexpanded parameter packs, recursively.
1395 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
1400 // Check the presence of a default argument here.
1401 if (NewTemplateParm->hasDefaultArgument() &&
1402 DiagnoseDefaultTemplateArgument(*this, TPC,
1403 NewTemplateParm->getLocation(),
1404 NewTemplateParm->getDefaultArgument().getSourceRange()))
1405 NewTemplateParm->removeDefaultArgument();
1407 // Merge default arguments for template template parameters
1408 TemplateTemplateParmDecl *OldTemplateParm
1409 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
1410 if (OldTemplateParm && !LookupResult::isVisible(*this, OldTemplateParm))
1411 OldTemplateParm = nullptr;
1412 if (NewTemplateParm->isParameterPack()) {
1413 assert(!NewTemplateParm->hasDefaultArgument() &&
1414 "Parameter packs can't have a default argument!");
1415 if (!NewTemplateParm->isPackExpansion())
1416 SawParameterPack = true;
1417 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
1418 NewTemplateParm->hasDefaultArgument()) {
1419 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1420 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
1421 SawDefaultArgument = true;
1422 RedundantDefaultArg = true;
1423 PreviousDefaultArgLoc = NewDefaultLoc;
1424 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1425 // Merge the default argument from the old declaration to the
1427 // FIXME: We need to create a new kind of "default argument" expression
1428 // that points to a previous template template parameter.
1429 NewTemplateParm->setDefaultArgument(
1430 OldTemplateParm->getDefaultArgument(),
1431 /*Inherited=*/ true);
1432 PreviousDefaultArgLoc
1433 = OldTemplateParm->getDefaultArgument().getLocation();
1434 } else if (NewTemplateParm->hasDefaultArgument()) {
1435 SawDefaultArgument = true;
1436 PreviousDefaultArgLoc
1437 = NewTemplateParm->getDefaultArgument().getLocation();
1438 } else if (SawDefaultArgument)
1439 MissingDefaultArg = true;
1442 // C++11 [temp.param]p11:
1443 // If a template parameter of a primary class template or alias template
1444 // is a template parameter pack, it shall be the last template parameter.
1445 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
1446 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
1447 TPC == TPC_TypeAliasTemplate)) {
1448 Diag((*NewParam)->getLocation(),
1449 diag::err_template_param_pack_must_be_last_template_parameter);
1453 if (RedundantDefaultArg) {
1454 // C++ [temp.param]p12:
1455 // A template-parameter shall not be given default arguments
1456 // by two different declarations in the same scope.
1457 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1458 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1460 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
1461 // C++ [temp.param]p11:
1462 // If a template-parameter of a class template has a default
1463 // template-argument, each subsequent template-parameter shall either
1464 // have a default template-argument supplied or be a template parameter
1466 Diag((*NewParam)->getLocation(),
1467 diag::err_template_param_default_arg_missing);
1468 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1470 RemoveDefaultArguments = true;
1473 // If we have an old template parameter list that we're merging
1474 // in, move on to the next parameter.
1479 // We were missing some default arguments at the end of the list, so remove
1480 // all of the default arguments.
1481 if (RemoveDefaultArguments) {
1482 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1483 NewParamEnd = NewParams->end();
1484 NewParam != NewParamEnd; ++NewParam) {
1485 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1486 TTP->removeDefaultArgument();
1487 else if (NonTypeTemplateParmDecl *NTTP
1488 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1489 NTTP->removeDefaultArgument();
1491 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1500 /// A class which looks for a use of a certain level of template
1502 struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1503 typedef RecursiveASTVisitor<DependencyChecker> super;
1507 SourceLocation MatchLoc;
1509 DependencyChecker(unsigned Depth) : Depth(Depth), Match(false) {}
1511 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1512 NamedDecl *ND = Params->getParam(0);
1513 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1514 Depth = PD->getDepth();
1515 } else if (NonTypeTemplateParmDecl *PD =
1516 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1517 Depth = PD->getDepth();
1519 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1523 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
1524 if (ParmDepth >= Depth) {
1532 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1533 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
1536 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1537 return !Matches(T->getDepth());
1540 bool TraverseTemplateName(TemplateName N) {
1541 if (TemplateTemplateParmDecl *PD =
1542 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
1543 if (Matches(PD->getDepth()))
1545 return super::TraverseTemplateName(N);
1548 bool VisitDeclRefExpr(DeclRefExpr *E) {
1549 if (NonTypeTemplateParmDecl *PD =
1550 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
1551 if (Matches(PD->getDepth(), E->getExprLoc()))
1553 return super::VisitDeclRefExpr(E);
1556 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1557 return TraverseType(T->getReplacementType());
1561 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
1562 return TraverseTemplateArgument(T->getArgumentPack());
1565 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1566 return TraverseType(T->getInjectedSpecializationType());
1571 /// Determines whether a given type depends on the given parameter
1574 DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
1575 DependencyChecker Checker(Params);
1576 Checker.TraverseType(T);
1577 return Checker.Match;
1580 // Find the source range corresponding to the named type in the given
1581 // nested-name-specifier, if any.
1582 static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
1584 const CXXScopeSpec &SS) {
1585 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
1586 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1587 if (const Type *CurType = NNS->getAsType()) {
1588 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1589 return NNSLoc.getTypeLoc().getSourceRange();
1593 NNSLoc = NNSLoc.getPrefix();
1596 return SourceRange();
1599 /// \brief Match the given template parameter lists to the given scope
1600 /// specifier, returning the template parameter list that applies to the
1603 /// \param DeclStartLoc the start of the declaration that has a scope
1604 /// specifier or a template parameter list.
1606 /// \param DeclLoc The location of the declaration itself.
1608 /// \param SS the scope specifier that will be matched to the given template
1609 /// parameter lists. This scope specifier precedes a qualified name that is
1612 /// \param TemplateId The template-id following the scope specifier, if there
1613 /// is one. Used to check for a missing 'template<>'.
1615 /// \param ParamLists the template parameter lists, from the outermost to the
1616 /// innermost template parameter lists.
1618 /// \param IsFriend Whether to apply the slightly different rules for
1619 /// matching template parameters to scope specifiers in friend
1622 /// \param IsExplicitSpecialization will be set true if the entity being
1623 /// declared is an explicit specialization, false otherwise.
1625 /// \returns the template parameter list, if any, that corresponds to the
1626 /// name that is preceded by the scope specifier @p SS. This template
1627 /// parameter list may have template parameters (if we're declaring a
1628 /// template) or may have no template parameters (if we're declaring a
1629 /// template specialization), or may be NULL (if what we're declaring isn't
1630 /// itself a template).
1631 TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
1632 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
1633 TemplateIdAnnotation *TemplateId,
1634 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
1635 bool &IsExplicitSpecialization, bool &Invalid) {
1636 IsExplicitSpecialization = false;
1639 // The sequence of nested types to which we will match up the template
1640 // parameter lists. We first build this list by starting with the type named
1641 // by the nested-name-specifier and walking out until we run out of types.
1642 SmallVector<QualType, 4> NestedTypes;
1644 if (SS.getScopeRep()) {
1645 if (CXXRecordDecl *Record
1646 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1647 T = Context.getTypeDeclType(Record);
1649 T = QualType(SS.getScopeRep()->getAsType(), 0);
1652 // If we found an explicit specialization that prevents us from needing
1653 // 'template<>' headers, this will be set to the location of that
1654 // explicit specialization.
1655 SourceLocation ExplicitSpecLoc;
1657 while (!T.isNull()) {
1658 NestedTypes.push_back(T);
1660 // Retrieve the parent of a record type.
1661 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1662 // If this type is an explicit specialization, we're done.
1663 if (ClassTemplateSpecializationDecl *Spec
1664 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1665 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
1666 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1667 ExplicitSpecLoc = Spec->getLocation();
1670 } else if (Record->getTemplateSpecializationKind()
1671 == TSK_ExplicitSpecialization) {
1672 ExplicitSpecLoc = Record->getLocation();
1676 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1677 T = Context.getTypeDeclType(Parent);
1683 if (const TemplateSpecializationType *TST
1684 = T->getAs<TemplateSpecializationType>()) {
1685 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1686 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1687 T = Context.getTypeDeclType(Parent);
1694 // Look one step prior in a dependent template specialization type.
1695 if (const DependentTemplateSpecializationType *DependentTST
1696 = T->getAs<DependentTemplateSpecializationType>()) {
1697 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1698 T = QualType(NNS->getAsType(), 0);
1704 // Look one step prior in a dependent name type.
1705 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1706 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1707 T = QualType(NNS->getAsType(), 0);
1713 // Retrieve the parent of an enumeration type.
1714 if (const EnumType *EnumT = T->getAs<EnumType>()) {
1715 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1717 EnumDecl *Enum = EnumT->getDecl();
1719 // Get to the parent type.
1720 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1721 T = Context.getTypeDeclType(Parent);
1729 // Reverse the nested types list, since we want to traverse from the outermost
1730 // to the innermost while checking template-parameter-lists.
1731 std::reverse(NestedTypes.begin(), NestedTypes.end());
1733 // C++0x [temp.expl.spec]p17:
1734 // A member or a member template may be nested within many
1735 // enclosing class templates. In an explicit specialization for
1736 // such a member, the member declaration shall be preceded by a
1737 // template<> for each enclosing class template that is
1738 // explicitly specialized.
1739 bool SawNonEmptyTemplateParameterList = false;
1741 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
1742 if (SawNonEmptyTemplateParameterList) {
1743 Diag(DeclLoc, diag::err_specialize_member_of_template)
1744 << !Recovery << Range;
1746 IsExplicitSpecialization = false;
1753 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
1754 // Check that we can have an explicit specialization here.
1755 if (CheckExplicitSpecialization(Range, true))
1758 // We don't have a template header, but we should.
1759 SourceLocation ExpectedTemplateLoc;
1760 if (!ParamLists.empty())
1761 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
1763 ExpectedTemplateLoc = DeclStartLoc;
1765 Diag(DeclLoc, diag::err_template_spec_needs_header)
1767 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
1771 unsigned ParamIdx = 0;
1772 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
1774 T = NestedTypes[TypeIdx];
1776 // Whether we expect a 'template<>' header.
1777 bool NeedEmptyTemplateHeader = false;
1779 // Whether we expect a template header with parameters.
1780 bool NeedNonemptyTemplateHeader = false;
1782 // For a dependent type, the set of template parameters that we
1784 TemplateParameterList *ExpectedTemplateParams = nullptr;
1786 // C++0x [temp.expl.spec]p15:
1787 // A member or a member template may be nested within many enclosing
1788 // class templates. In an explicit specialization for such a member, the
1789 // member declaration shall be preceded by a template<> for each
1790 // enclosing class template that is explicitly specialized.
1791 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1792 if (ClassTemplatePartialSpecializationDecl *Partial
1793 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1794 ExpectedTemplateParams = Partial->getTemplateParameters();
1795 NeedNonemptyTemplateHeader = true;
1796 } else if (Record->isDependentType()) {
1797 if (Record->getDescribedClassTemplate()) {
1798 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1799 ->getTemplateParameters();
1800 NeedNonemptyTemplateHeader = true;
1802 } else if (ClassTemplateSpecializationDecl *Spec
1803 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1804 // C++0x [temp.expl.spec]p4:
1805 // Members of an explicitly specialized class template are defined
1806 // in the same manner as members of normal classes, and not using
1807 // the template<> syntax.
1808 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
1809 NeedEmptyTemplateHeader = true;
1812 } else if (Record->getTemplateSpecializationKind()) {
1813 if (Record->getTemplateSpecializationKind()
1814 != TSK_ExplicitSpecialization &&
1815 TypeIdx == NumTypes - 1)
1816 IsExplicitSpecialization = true;
1820 } else if (const TemplateSpecializationType *TST
1821 = T->getAs<TemplateSpecializationType>()) {
1822 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1823 ExpectedTemplateParams = Template->getTemplateParameters();
1824 NeedNonemptyTemplateHeader = true;
1826 } else if (T->getAs<DependentTemplateSpecializationType>()) {
1827 // FIXME: We actually could/should check the template arguments here
1828 // against the corresponding template parameter list.
1829 NeedNonemptyTemplateHeader = false;
1832 // C++ [temp.expl.spec]p16:
1833 // In an explicit specialization declaration for a member of a class
1834 // template or a member template that ap- pears in namespace scope, the
1835 // member template and some of its enclosing class templates may remain
1836 // unspecialized, except that the declaration shall not explicitly
1837 // specialize a class member template if its en- closing class templates
1838 // are not explicitly specialized as well.
1839 if (ParamIdx < ParamLists.size()) {
1840 if (ParamLists[ParamIdx]->size() == 0) {
1841 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1845 SawNonEmptyTemplateParameterList = true;
1848 if (NeedEmptyTemplateHeader) {
1849 // If we're on the last of the types, and we need a 'template<>' header
1850 // here, then it's an explicit specialization.
1851 if (TypeIdx == NumTypes - 1)
1852 IsExplicitSpecialization = true;
1854 if (ParamIdx < ParamLists.size()) {
1855 if (ParamLists[ParamIdx]->size() > 0) {
1856 // The header has template parameters when it shouldn't. Complain.
1857 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1858 diag::err_template_param_list_matches_nontemplate)
1860 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
1861 ParamLists[ParamIdx]->getRAngleLoc())
1862 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1867 // Consume this template header.
1873 if (DiagnoseMissingExplicitSpecialization(
1874 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
1880 if (NeedNonemptyTemplateHeader) {
1881 // In friend declarations we can have template-ids which don't
1882 // depend on the corresponding template parameter lists. But
1883 // assume that empty parameter lists are supposed to match this
1885 if (IsFriend && T->isDependentType()) {
1886 if (ParamIdx < ParamLists.size() &&
1887 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
1888 ExpectedTemplateParams = nullptr;
1893 if (ParamIdx < ParamLists.size()) {
1894 // Check the template parameter list, if we can.
1895 if (ExpectedTemplateParams &&
1896 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
1897 ExpectedTemplateParams,
1898 true, TPL_TemplateMatch))
1902 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
1903 TPC_ClassTemplateMember))
1910 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
1912 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1918 // If there were at least as many template-ids as there were template
1919 // parameter lists, then there are no template parameter lists remaining for
1920 // the declaration itself.
1921 if (ParamIdx >= ParamLists.size()) {
1922 if (TemplateId && !IsFriend) {
1923 // We don't have a template header for the declaration itself, but we
1925 IsExplicitSpecialization = true;
1926 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
1927 TemplateId->RAngleLoc));
1929 // Fabricate an empty template parameter list for the invented header.
1930 return TemplateParameterList::Create(Context, SourceLocation(),
1931 SourceLocation(), nullptr, 0,
1938 // If there were too many template parameter lists, complain about that now.
1939 if (ParamIdx < ParamLists.size() - 1) {
1940 bool HasAnyExplicitSpecHeader = false;
1941 bool AllExplicitSpecHeaders = true;
1942 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
1943 if (ParamLists[I]->size() == 0)
1944 HasAnyExplicitSpecHeader = true;
1946 AllExplicitSpecHeaders = false;
1949 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1950 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
1951 : diag::err_template_spec_extra_headers)
1952 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1953 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
1955 // If there was a specialization somewhere, such that 'template<>' is
1956 // not required, and there were any 'template<>' headers, note where the
1957 // specialization occurred.
1958 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
1959 Diag(ExplicitSpecLoc,
1960 diag::note_explicit_template_spec_does_not_need_header)
1961 << NestedTypes.back();
1963 // We have a template parameter list with no corresponding scope, which
1964 // means that the resulting template declaration can't be instantiated
1965 // properly (we'll end up with dependent nodes when we shouldn't).
1966 if (!AllExplicitSpecHeaders)
1970 // C++ [temp.expl.spec]p16:
1971 // In an explicit specialization declaration for a member of a class
1972 // template or a member template that ap- pears in namespace scope, the
1973 // member template and some of its enclosing class templates may remain
1974 // unspecialized, except that the declaration shall not explicitly
1975 // specialize a class member template if its en- closing class templates
1976 // are not explicitly specialized as well.
1977 if (ParamLists.back()->size() == 0 &&
1978 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1982 // Return the last template parameter list, which corresponds to the
1983 // entity being declared.
1984 return ParamLists.back();
1987 void Sema::NoteAllFoundTemplates(TemplateName Name) {
1988 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
1989 Diag(Template->getLocation(), diag::note_template_declared_here)
1990 << (isa<FunctionTemplateDecl>(Template)
1992 : isa<ClassTemplateDecl>(Template)
1994 : isa<VarTemplateDecl>(Template)
1996 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
1997 << Template->getDeclName();
2001 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
2002 for (OverloadedTemplateStorage::iterator I = OST->begin(),
2005 Diag((*I)->getLocation(), diag::note_template_declared_here)
2006 << 0 << (*I)->getDeclName();
2012 QualType Sema::CheckTemplateIdType(TemplateName Name,
2013 SourceLocation TemplateLoc,
2014 TemplateArgumentListInfo &TemplateArgs) {
2015 DependentTemplateName *DTN
2016 = Name.getUnderlying().getAsDependentTemplateName();
2017 if (DTN && DTN->isIdentifier())
2018 // When building a template-id where the template-name is dependent,
2019 // assume the template is a type template. Either our assumption is
2020 // correct, or the code is ill-formed and will be diagnosed when the
2021 // dependent name is substituted.
2022 return Context.getDependentTemplateSpecializationType(ETK_None,
2023 DTN->getQualifier(),
2024 DTN->getIdentifier(),
2027 TemplateDecl *Template = Name.getAsTemplateDecl();
2028 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2029 isa<VarTemplateDecl>(Template)) {
2030 // We might have a substituted template template parameter pack. If so,
2031 // build a template specialization type for it.
2032 if (Name.getAsSubstTemplateTemplateParmPack())
2033 return Context.getTemplateSpecializationType(Name, TemplateArgs);
2035 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2037 NoteAllFoundTemplates(Name);
2041 // Check that the template argument list is well-formed for this
2043 SmallVector<TemplateArgument, 4> Converted;
2044 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
2050 bool InstantiationDependent = false;
2051 if (TypeAliasTemplateDecl *AliasTemplate =
2052 dyn_cast<TypeAliasTemplateDecl>(Template)) {
2053 // Find the canonical type for this type alias template specialization.
2054 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2055 if (Pattern->isInvalidDecl())
2058 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2059 Converted.data(), Converted.size());
2061 // Only substitute for the innermost template argument list.
2062 MultiLevelTemplateArgumentList TemplateArgLists;
2063 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
2064 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2065 for (unsigned I = 0; I < Depth; ++I)
2066 TemplateArgLists.addOuterTemplateArguments(None);
2068 LocalInstantiationScope Scope(*this);
2069 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
2070 if (Inst.isInvalid())
2073 CanonType = SubstType(Pattern->getUnderlyingType(),
2074 TemplateArgLists, AliasTemplate->getLocation(),
2075 AliasTemplate->getDeclName());
2076 if (CanonType.isNull())
2078 } else if (Name.isDependent() ||
2079 TemplateSpecializationType::anyDependentTemplateArguments(
2080 TemplateArgs, InstantiationDependent)) {
2081 // This class template specialization is a dependent
2082 // type. Therefore, its canonical type is another class template
2083 // specialization type that contains all of the converted
2084 // arguments in canonical form. This ensures that, e.g., A<T> and
2085 // A<T, T> have identical types when A is declared as:
2087 // template<typename T, typename U = T> struct A;
2088 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
2089 CanonType = Context.getTemplateSpecializationType(CanonName,
2093 // FIXME: CanonType is not actually the canonical type, and unfortunately
2094 // it is a TemplateSpecializationType that we will never use again.
2095 // In the future, we need to teach getTemplateSpecializationType to only
2096 // build the canonical type and return that to us.
2097 CanonType = Context.getCanonicalType(CanonType);
2099 // This might work out to be a current instantiation, in which
2100 // case the canonical type needs to be the InjectedClassNameType.
2102 // TODO: in theory this could be a simple hashtable lookup; most
2103 // changes to CurContext don't change the set of current
2105 if (isa<ClassTemplateDecl>(Template)) {
2106 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2107 // If we get out to a namespace, we're done.
2108 if (Ctx->isFileContext()) break;
2110 // If this isn't a record, keep looking.
2111 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2112 if (!Record) continue;
2114 // Look for one of the two cases with InjectedClassNameTypes
2115 // and check whether it's the same template.
2116 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2117 !Record->getDescribedClassTemplate())
2120 // Fetch the injected class name type and check whether its
2121 // injected type is equal to the type we just built.
2122 QualType ICNT = Context.getTypeDeclType(Record);
2123 QualType Injected = cast<InjectedClassNameType>(ICNT)
2124 ->getInjectedSpecializationType();
2126 if (CanonType != Injected->getCanonicalTypeInternal())
2129 // If so, the canonical type of this TST is the injected
2130 // class name type of the record we just found.
2131 assert(ICNT.isCanonical());
2136 } else if (ClassTemplateDecl *ClassTemplate
2137 = dyn_cast<ClassTemplateDecl>(Template)) {
2138 // Find the class template specialization declaration that
2139 // corresponds to these arguments.
2140 void *InsertPos = nullptr;
2141 ClassTemplateSpecializationDecl *Decl
2142 = ClassTemplate->findSpecialization(Converted, InsertPos);
2144 // This is the first time we have referenced this class template
2145 // specialization. Create the canonical declaration and add it to
2146 // the set of specializations.
2147 Decl = ClassTemplateSpecializationDecl::Create(Context,
2148 ClassTemplate->getTemplatedDecl()->getTagKind(),
2149 ClassTemplate->getDeclContext(),
2150 ClassTemplate->getTemplatedDecl()->getLocStart(),
2151 ClassTemplate->getLocation(),
2154 Converted.size(), nullptr);
2155 ClassTemplate->AddSpecialization(Decl, InsertPos);
2156 if (ClassTemplate->isOutOfLine())
2157 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
2160 // Diagnose uses of this specialization.
2161 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2163 CanonType = Context.getTypeDeclType(Decl);
2164 assert(isa<RecordType>(CanonType) &&
2165 "type of non-dependent specialization is not a RecordType");
2168 // Build the fully-sugared type for this class template
2169 // specialization, which refers back to the class template
2170 // specialization we created or found.
2171 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
2175 Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
2176 TemplateTy TemplateD, SourceLocation TemplateLoc,
2177 SourceLocation LAngleLoc,
2178 ASTTemplateArgsPtr TemplateArgsIn,
2179 SourceLocation RAngleLoc,
2180 bool IsCtorOrDtorName) {
2184 TemplateName Template = TemplateD.get();
2186 // Translate the parser's template argument list in our AST format.
2187 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2188 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2190 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2192 = Context.getDependentTemplateSpecializationType(ETK_None,
2193 DTN->getQualifier(),
2194 DTN->getIdentifier(),
2196 // Build type-source information.
2198 DependentTemplateSpecializationTypeLoc SpecTL
2199 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2200 SpecTL.setElaboratedKeywordLoc(SourceLocation());
2201 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
2202 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2203 SpecTL.setTemplateNameLoc(TemplateLoc);
2204 SpecTL.setLAngleLoc(LAngleLoc);
2205 SpecTL.setRAngleLoc(RAngleLoc);
2206 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2207 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2208 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2211 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2213 if (Result.isNull())
2216 // Build type-source information.
2218 TemplateSpecializationTypeLoc SpecTL
2219 = TLB.push<TemplateSpecializationTypeLoc>(Result);
2220 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2221 SpecTL.setTemplateNameLoc(TemplateLoc);
2222 SpecTL.setLAngleLoc(LAngleLoc);
2223 SpecTL.setRAngleLoc(RAngleLoc);
2224 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2225 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
2227 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2228 // constructor or destructor name (in such a case, the scope specifier
2229 // will be attached to the enclosing Decl or Expr node).
2230 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
2231 // Create an elaborated-type-specifier containing the nested-name-specifier.
2232 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2233 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
2234 ElabTL.setElaboratedKeywordLoc(SourceLocation());
2235 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2238 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
2241 TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
2242 TypeSpecifierType TagSpec,
2243 SourceLocation TagLoc,
2245 SourceLocation TemplateKWLoc,
2246 TemplateTy TemplateD,
2247 SourceLocation TemplateLoc,
2248 SourceLocation LAngleLoc,
2249 ASTTemplateArgsPtr TemplateArgsIn,
2250 SourceLocation RAngleLoc) {
2251 TemplateName Template = TemplateD.get();
2253 // Translate the parser's template argument list in our AST format.
2254 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2255 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2257 // Determine the tag kind
2258 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
2259 ElaboratedTypeKeyword Keyword
2260 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
2262 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2263 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
2264 DTN->getQualifier(),
2265 DTN->getIdentifier(),
2268 // Build type-source information.
2270 DependentTemplateSpecializationTypeLoc SpecTL
2271 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2272 SpecTL.setElaboratedKeywordLoc(TagLoc);
2273 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
2274 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2275 SpecTL.setTemplateNameLoc(TemplateLoc);
2276 SpecTL.setLAngleLoc(LAngleLoc);
2277 SpecTL.setRAngleLoc(RAngleLoc);
2278 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2279 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2280 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2283 if (TypeAliasTemplateDecl *TAT =
2284 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2285 // C++0x [dcl.type.elab]p2:
2286 // If the identifier resolves to a typedef-name or the simple-template-id
2287 // resolves to an alias template specialization, the
2288 // elaborated-type-specifier is ill-formed.
2289 Diag(TemplateLoc, diag::err_tag_reference_non_tag) << 4;
2290 Diag(TAT->getLocation(), diag::note_declared_at);
2293 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2294 if (Result.isNull())
2295 return TypeResult(true);
2297 // Check the tag kind
2298 if (const RecordType *RT = Result->getAs<RecordType>()) {
2299 RecordDecl *D = RT->getDecl();
2301 IdentifierInfo *Id = D->getIdentifier();
2302 assert(Id && "templated class must have an identifier");
2304 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
2306 Diag(TagLoc, diag::err_use_with_wrong_tag)
2308 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
2309 Diag(D->getLocation(), diag::note_previous_use);
2313 // Provide source-location information for the template specialization.
2315 TemplateSpecializationTypeLoc SpecTL
2316 = TLB.push<TemplateSpecializationTypeLoc>(Result);
2317 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2318 SpecTL.setTemplateNameLoc(TemplateLoc);
2319 SpecTL.setLAngleLoc(LAngleLoc);
2320 SpecTL.setRAngleLoc(RAngleLoc);
2321 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2322 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
2324 // Construct an elaborated type containing the nested-name-specifier (if any)
2326 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2327 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
2328 ElabTL.setElaboratedKeywordLoc(TagLoc);
2329 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2330 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
2333 static bool CheckTemplatePartialSpecializationArgs(
2334 Sema &S, SourceLocation NameLoc, TemplateParameterList *TemplateParams,
2335 unsigned ExplicitArgs, SmallVectorImpl<TemplateArgument> &TemplateArgs);
2337 static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
2338 NamedDecl *PrevDecl,
2340 bool IsPartialSpecialization);
2342 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
2344 static bool isTemplateArgumentTemplateParameter(
2345 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
2346 switch (Arg.getKind()) {
2347 case TemplateArgument::Null:
2348 case TemplateArgument::NullPtr:
2349 case TemplateArgument::Integral:
2350 case TemplateArgument::Declaration:
2351 case TemplateArgument::Pack:
2352 case TemplateArgument::TemplateExpansion:
2355 case TemplateArgument::Type: {
2356 QualType Type = Arg.getAsType();
2357 const TemplateTypeParmType *TPT =
2358 Arg.getAsType()->getAs<TemplateTypeParmType>();
2359 return TPT && !Type.hasQualifiers() &&
2360 TPT->getDepth() == Depth && TPT->getIndex() == Index;
2363 case TemplateArgument::Expression: {
2364 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
2365 if (!DRE || !DRE->getDecl())
2367 const NonTypeTemplateParmDecl *NTTP =
2368 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2369 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
2372 case TemplateArgument::Template:
2373 const TemplateTemplateParmDecl *TTP =
2374 dyn_cast_or_null<TemplateTemplateParmDecl>(
2375 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
2376 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
2378 llvm_unreachable("unexpected kind of template argument");
2381 static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
2382 ArrayRef<TemplateArgument> Args) {
2383 if (Params->size() != Args.size())
2386 unsigned Depth = Params->getDepth();
2388 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2389 TemplateArgument Arg = Args[I];
2391 // If the parameter is a pack expansion, the argument must be a pack
2392 // whose only element is a pack expansion.
2393 if (Params->getParam(I)->isParameterPack()) {
2394 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
2395 !Arg.pack_begin()->isPackExpansion())
2397 Arg = Arg.pack_begin()->getPackExpansionPattern();
2400 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
2407 /// Convert the parser's template argument list representation into our form.
2408 static TemplateArgumentListInfo
2409 makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
2410 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
2411 TemplateId.RAngleLoc);
2412 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
2413 TemplateId.NumArgs);
2414 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
2415 return TemplateArgs;
2418 DeclResult Sema::ActOnVarTemplateSpecialization(
2419 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
2420 TemplateParameterList *TemplateParams, StorageClass SC,
2421 bool IsPartialSpecialization) {
2422 // D must be variable template id.
2423 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
2424 "Variable template specialization is declared with a template it.");
2426 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
2427 TemplateArgumentListInfo TemplateArgs =
2428 makeTemplateArgumentListInfo(*this, *TemplateId);
2429 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
2430 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
2431 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
2433 TemplateName Name = TemplateId->Template.get();
2435 // The template-id must name a variable template.
2436 VarTemplateDecl *VarTemplate =
2437 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
2439 NamedDecl *FnTemplate;
2440 if (auto *OTS = Name.getAsOverloadedTemplate())
2441 FnTemplate = *OTS->begin();
2443 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
2445 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
2446 << FnTemplate->getDeclName();
2447 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
2448 << IsPartialSpecialization;
2451 // Check for unexpanded parameter packs in any of the template arguments.
2452 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2453 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
2454 UPPC_PartialSpecialization))
2457 // Check that the template argument list is well-formed for this
2459 SmallVector<TemplateArgument, 4> Converted;
2460 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
2464 // Check that the type of this variable template specialization
2465 // matches the expected type.
2466 TypeSourceInfo *ExpectedDI;
2468 // Do substitution on the type of the declaration
2469 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
2470 Converted.data(), Converted.size());
2471 InstantiatingTemplate Inst(*this, TemplateKWLoc, VarTemplate);
2472 if (Inst.isInvalid())
2474 VarDecl *Templated = VarTemplate->getTemplatedDecl();
2476 SubstType(Templated->getTypeSourceInfo(),
2477 MultiLevelTemplateArgumentList(TemplateArgList),
2478 Templated->getTypeSpecStartLoc(), Templated->getDeclName());
2483 // Find the variable template (partial) specialization declaration that
2484 // corresponds to these arguments.
2485 if (IsPartialSpecialization) {
2486 if (CheckTemplatePartialSpecializationArgs(
2487 *this, TemplateNameLoc, VarTemplate->getTemplateParameters(),
2488 TemplateArgs.size(), Converted))
2491 bool InstantiationDependent;
2492 if (!Name.isDependent() &&
2493 !TemplateSpecializationType::anyDependentTemplateArguments(
2494 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
2495 InstantiationDependent)) {
2496 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
2497 << VarTemplate->getDeclName();
2498 IsPartialSpecialization = false;
2501 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
2503 // C++ [temp.class.spec]p9b3:
2505 // -- The argument list of the specialization shall not be identical
2506 // to the implicit argument list of the primary template.
2507 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2508 << /*variable template*/ 1
2509 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
2510 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
2511 // FIXME: Recover from this by treating the declaration as a redeclaration
2512 // of the primary template.
2517 void *InsertPos = nullptr;
2518 VarTemplateSpecializationDecl *PrevDecl = nullptr;
2520 if (IsPartialSpecialization)
2521 // FIXME: Template parameter list matters too
2522 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
2524 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
2526 VarTemplateSpecializationDecl *Specialization = nullptr;
2528 // Check whether we can declare a variable template specialization in
2529 // the current scope.
2530 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
2532 IsPartialSpecialization))
2535 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2536 // Since the only prior variable template specialization with these
2537 // arguments was referenced but not declared, reuse that
2538 // declaration node as our own, updating its source location and
2539 // the list of outer template parameters to reflect our new declaration.
2540 Specialization = PrevDecl;
2541 Specialization->setLocation(TemplateNameLoc);
2543 } else if (IsPartialSpecialization) {
2544 // Create a new class template partial specialization declaration node.
2545 VarTemplatePartialSpecializationDecl *PrevPartial =
2546 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
2547 VarTemplatePartialSpecializationDecl *Partial =
2548 VarTemplatePartialSpecializationDecl::Create(
2549 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
2550 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
2551 Converted.data(), Converted.size(), TemplateArgs);
2554 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
2555 Specialization = Partial;
2557 // If we are providing an explicit specialization of a member variable
2558 // template specialization, make a note of that.
2559 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
2560 PrevPartial->setMemberSpecialization();
2562 // Check that all of the template parameters of the variable template
2563 // partial specialization are deducible from the template
2564 // arguments. If not, this variable template partial specialization
2565 // will never be used.
2566 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
2567 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2568 TemplateParams->getDepth(), DeducibleParams);
2570 if (!DeducibleParams.all()) {
2571 unsigned NumNonDeducible =
2572 DeducibleParams.size() - DeducibleParams.count();
2573 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2574 << /*variable template*/ 1 << (NumNonDeducible > 1)
2575 << SourceRange(TemplateNameLoc, RAngleLoc);
2576 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2577 if (!DeducibleParams[I]) {
2578 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2579 if (Param->getDeclName())
2580 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2581 << Param->getDeclName();
2583 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2589 // Create a new class template specialization declaration node for
2590 // this explicit specialization or friend declaration.
2591 Specialization = VarTemplateSpecializationDecl::Create(
2592 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
2593 VarTemplate, DI->getType(), DI, SC, Converted.data(), Converted.size());
2594 Specialization->setTemplateArgsInfo(TemplateArgs);
2597 VarTemplate->AddSpecialization(Specialization, InsertPos);
2600 // C++ [temp.expl.spec]p6:
2601 // If a template, a member template or the member of a class template is
2602 // explicitly specialized then that specialization shall be declared
2603 // before the first use of that specialization that would cause an implicit
2604 // instantiation to take place, in every translation unit in which such a
2605 // use occurs; no diagnostic is required.
2606 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
2608 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
2609 // Is there any previous explicit specialization declaration?
2610 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
2617 SourceRange Range(TemplateNameLoc, RAngleLoc);
2618 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
2621 Diag(PrevDecl->getPointOfInstantiation(),
2622 diag::note_instantiation_required_here)
2623 << (PrevDecl->getTemplateSpecializationKind() !=
2624 TSK_ImplicitInstantiation);
2629 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
2630 Specialization->setLexicalDeclContext(CurContext);
2632 // Add the specialization into its lexical context, so that it can
2633 // be seen when iterating through the list of declarations in that
2634 // context. However, specializations are not found by name lookup.
2635 CurContext->addDecl(Specialization);
2637 // Note that this is an explicit specialization.
2638 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2641 // Check that this isn't a redefinition of this specialization,
2642 // merging with previous declarations.
2643 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
2645 PrevSpec.addDecl(PrevDecl);
2646 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
2647 } else if (Specialization->isStaticDataMember() &&
2648 Specialization->isOutOfLine()) {
2649 Specialization->setAccess(VarTemplate->getAccess());
2652 // Link instantiations of static data members back to the template from
2653 // which they were instantiated.
2654 if (Specialization->isStaticDataMember())
2655 Specialization->setInstantiationOfStaticDataMember(
2656 VarTemplate->getTemplatedDecl(),
2657 Specialization->getSpecializationKind());
2659 return Specialization;
2663 /// \brief A partial specialization whose template arguments have matched
2664 /// a given template-id.
2665 struct PartialSpecMatchResult {
2666 VarTemplatePartialSpecializationDecl *Partial;
2667 TemplateArgumentList *Args;
2672 Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
2673 SourceLocation TemplateNameLoc,
2674 const TemplateArgumentListInfo &TemplateArgs) {
2675 assert(Template && "A variable template id without template?");
2677 // Check that the template argument list is well-formed for this template.
2678 SmallVector<TemplateArgument, 4> Converted;
2679 if (CheckTemplateArgumentList(
2680 Template, TemplateNameLoc,
2681 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
2685 // Find the variable template specialization declaration that
2686 // corresponds to these arguments.
2687 void *InsertPos = nullptr;
2688 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
2689 Converted, InsertPos))
2690 // If we already have a variable template specialization, return it.
2693 // This is the first time we have referenced this variable template
2694 // specialization. Create the canonical declaration and add it to
2695 // the set of specializations, based on the closest partial specialization
2696 // that it represents. That is,
2697 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
2698 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
2699 Converted.data(), Converted.size());
2700 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
2701 bool AmbiguousPartialSpec = false;
2702 typedef PartialSpecMatchResult MatchResult;
2703 SmallVector<MatchResult, 4> Matched;
2704 SourceLocation PointOfInstantiation = TemplateNameLoc;
2705 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
2707 // 1. Attempt to find the closest partial specialization that this
2708 // specializes, if any.
2709 // If any of the template arguments is dependent, then this is probably
2710 // a placeholder for an incomplete declarative context; which must be
2711 // complete by instantiation time. Thus, do not search through the partial
2712 // specializations yet.
2713 // TODO: Unify with InstantiateClassTemplateSpecialization()?
2714 // Perhaps better after unification of DeduceTemplateArguments() and
2715 // getMoreSpecializedPartialSpecialization().
2716 bool InstantiationDependent = false;
2717 if (!TemplateSpecializationType::anyDependentTemplateArguments(
2718 TemplateArgs, InstantiationDependent)) {
2720 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2721 Template->getPartialSpecializations(PartialSpecs);
2723 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2724 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2725 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2727 if (TemplateDeductionResult Result =
2728 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
2729 // Store the failed-deduction information for use in diagnostics, later.
2730 // TODO: Actually use the failed-deduction info?
2731 FailedCandidates.addCandidate()
2732 .set(Partial, MakeDeductionFailureInfo(Context, Result, Info));
2735 Matched.push_back(PartialSpecMatchResult());
2736 Matched.back().Partial = Partial;
2737 Matched.back().Args = Info.take();
2741 if (Matched.size() >= 1) {
2742 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
2743 if (Matched.size() == 1) {
2744 // -- If exactly one matching specialization is found, the
2745 // instantiation is generated from that specialization.
2746 // We don't need to do anything for this.
2748 // -- If more than one matching specialization is found, the
2749 // partial order rules (14.5.4.2) are used to determine
2750 // whether one of the specializations is more specialized
2751 // than the others. If none of the specializations is more
2752 // specialized than all of the other matching
2753 // specializations, then the use of the variable template is
2754 // ambiguous and the program is ill-formed.
2755 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
2756 PEnd = Matched.end();
2758 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2759 PointOfInstantiation) ==
2764 // Determine if the best partial specialization is more specialized than
2766 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2767 PEnd = Matched.end();
2769 if (P != Best && getMoreSpecializedPartialSpecialization(
2770 P->Partial, Best->Partial,
2771 PointOfInstantiation) != Best->Partial) {
2772 AmbiguousPartialSpec = true;
2778 // Instantiate using the best variable template partial specialization.
2779 InstantiationPattern = Best->Partial;
2780 InstantiationArgs = Best->Args;
2782 // -- If no match is found, the instantiation is generated
2783 // from the primary template.
2784 // InstantiationPattern = Template->getTemplatedDecl();
2788 // 2. Create the canonical declaration.
2789 // Note that we do not instantiate the variable just yet, since
2790 // instantiation is handled in DoMarkVarDeclReferenced().
2791 // FIXME: LateAttrs et al.?
2792 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
2793 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
2794 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
2798 if (AmbiguousPartialSpec) {
2799 // Partial ordering did not produce a clear winner. Complain.
2800 Decl->setInvalidDecl();
2801 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2804 // Print the matching partial specializations.
2805 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2806 PEnd = Matched.end();
2808 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2809 << getTemplateArgumentBindingsText(
2810 P->Partial->getTemplateParameters(), *P->Args);
2814 if (VarTemplatePartialSpecializationDecl *D =
2815 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
2816 Decl->setInstantiationOf(D, InstantiationArgs);
2818 assert(Decl && "No variable template specialization?");
2823 Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
2824 const DeclarationNameInfo &NameInfo,
2825 VarTemplateDecl *Template, SourceLocation TemplateLoc,
2826 const TemplateArgumentListInfo *TemplateArgs) {
2828 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
2830 if (Decl.isInvalid())
2833 VarDecl *Var = cast<VarDecl>(Decl.get());
2834 if (!Var->getTemplateSpecializationKind())
2835 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
2838 // Build an ordinary singleton decl ref.
2839 return BuildDeclarationNameExpr(SS, NameInfo, Var,
2840 /*FoundD=*/nullptr, TemplateArgs);
2843 ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
2844 SourceLocation TemplateKWLoc,
2847 const TemplateArgumentListInfo *TemplateArgs) {
2848 // FIXME: Can we do any checking at this point? I guess we could check the
2849 // template arguments that we have against the template name, if the template
2850 // name refers to a single template. That's not a terribly common case,
2852 // foo<int> could identify a single function unambiguously
2853 // This approach does NOT work, since f<int>(1);
2854 // gets resolved prior to resorting to overload resolution
2855 // i.e., template<class T> void f(double);
2856 // vs template<class T, class U> void f(U);
2858 // These should be filtered out by our callers.
2859 assert(!R.empty() && "empty lookup results when building templateid");
2860 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
2862 // In C++1y, check variable template ids.
2863 bool InstantiationDependent;
2864 if (R.getAsSingle<VarTemplateDecl>() &&
2865 !TemplateSpecializationType::anyDependentTemplateArguments(
2866 *TemplateArgs, InstantiationDependent)) {
2867 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
2868 R.getAsSingle<VarTemplateDecl>(),
2869 TemplateKWLoc, TemplateArgs);
2872 // We don't want lookup warnings at this point.
2873 R.suppressDiagnostics();
2875 UnresolvedLookupExpr *ULE
2876 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2877 SS.getWithLocInContext(Context),
2879 R.getLookupNameInfo(),
2880 RequiresADL, TemplateArgs,
2881 R.begin(), R.end());
2886 // We actually only call this from template instantiation.
2888 Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
2889 SourceLocation TemplateKWLoc,
2890 const DeclarationNameInfo &NameInfo,
2891 const TemplateArgumentListInfo *TemplateArgs) {
2893 assert(TemplateArgs || TemplateKWLoc.isValid());
2895 if (!(DC = computeDeclContext(SS, false)) ||
2896 DC->isDependentContext() ||
2897 RequireCompleteDeclContext(SS, DC))
2898 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
2900 bool MemberOfUnknownSpecialization;
2901 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2902 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
2903 MemberOfUnknownSpecialization);
2905 if (R.isAmbiguous())
2909 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
2910 << NameInfo.getName() << SS.getRange();
2914 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
2915 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
2917 << NameInfo.getName().getAsString() << SS.getRange();
2918 Diag(Temp->getLocation(), diag::note_referenced_class_template);
2922 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
2925 /// \brief Form a dependent template name.
2927 /// This action forms a dependent template name given the template
2928 /// name and its (presumably dependent) scope specifier. For
2929 /// example, given "MetaFun::template apply", the scope specifier \p
2930 /// SS will be "MetaFun::", \p TemplateKWLoc contains the location
2931 /// of the "template" keyword, and "apply" is the \p Name.
2932 TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
2934 SourceLocation TemplateKWLoc,
2935 UnqualifiedId &Name,
2936 ParsedType ObjectType,
2937 bool EnteringContext,
2938 TemplateTy &Result) {
2939 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
2941 getLangOpts().CPlusPlus11 ?
2942 diag::warn_cxx98_compat_template_outside_of_template :
2943 diag::ext_template_outside_of_template)
2944 << FixItHint::CreateRemoval(TemplateKWLoc);
2946 DeclContext *LookupCtx = nullptr;
2948 LookupCtx = computeDeclContext(SS, EnteringContext);
2949 if (!LookupCtx && ObjectType)
2950 LookupCtx = computeDeclContext(ObjectType.get());
2952 // C++0x [temp.names]p5:
2953 // If a name prefixed by the keyword template is not the name of
2954 // a template, the program is ill-formed. [Note: the keyword
2955 // template may not be applied to non-template members of class
2956 // templates. -end note ] [ Note: as is the case with the
2957 // typename prefix, the template prefix is allowed in cases
2958 // where it is not strictly necessary; i.e., when the
2959 // nested-name-specifier or the expression on the left of the ->
2960 // or . is not dependent on a template-parameter, or the use
2961 // does not appear in the scope of a template. -end note]
2963 // Note: C++03 was more strict here, because it banned the use of
2964 // the "template" keyword prior to a template-name that was not a
2965 // dependent name. C++ DR468 relaxed this requirement (the
2966 // "template" keyword is now permitted). We follow the C++0x
2967 // rules, even in C++03 mode with a warning, retroactively applying the DR.
2968 bool MemberOfUnknownSpecialization;
2969 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
2970 ObjectType, EnteringContext, Result,
2971 MemberOfUnknownSpecialization);
2972 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
2973 isa<CXXRecordDecl>(LookupCtx) &&
2974 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
2975 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
2976 // This is a dependent template. Handle it below.
2977 } else if (TNK == TNK_Non_template) {
2978 Diag(Name.getLocStart(),
2979 diag::err_template_kw_refers_to_non_template)
2980 << GetNameFromUnqualifiedId(Name).getName()
2981 << Name.getSourceRange()
2983 return TNK_Non_template;
2985 // We found something; return it.
2990 NestedNameSpecifier *Qualifier = SS.getScopeRep();
2992 switch (Name.getKind()) {
2993 case UnqualifiedId::IK_Identifier:
2994 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
2996 return TNK_Dependent_template_name;
2998 case UnqualifiedId::IK_OperatorFunctionId:
2999 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
3000 Name.OperatorFunctionId.Operator));
3001 return TNK_Function_template;
3003 case UnqualifiedId::IK_LiteralOperatorId:
3004 llvm_unreachable("literal operator id cannot have a dependent scope");
3010 Diag(Name.getLocStart(),
3011 diag::err_template_kw_refers_to_non_template)
3012 << GetNameFromUnqualifiedId(Name).getName()
3013 << Name.getSourceRange()
3015 return TNK_Non_template;
3018 bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
3019 TemplateArgumentLoc &AL,
3020 SmallVectorImpl<TemplateArgument> &Converted) {
3021 const TemplateArgument &Arg = AL.getArgument();
3023 TypeSourceInfo *TSI = nullptr;
3025 // Check template type parameter.
3026 switch(Arg.getKind()) {
3027 case TemplateArgument::Type:
3028 // C++ [temp.arg.type]p1:
3029 // A template-argument for a template-parameter which is a
3030 // type shall be a type-id.
3031 ArgType = Arg.getAsType();
3032 TSI = AL.getTypeSourceInfo();
3034 case TemplateArgument::Template: {
3035 // We have a template type parameter but the template argument
3036 // is a template without any arguments.
3037 SourceRange SR = AL.getSourceRange();
3038 TemplateName Name = Arg.getAsTemplate();
3039 Diag(SR.getBegin(), diag::err_template_missing_args)
3041 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3042 Diag(Decl->getLocation(), diag::note_template_decl_here);
3046 case TemplateArgument::Expression: {
3047 // We have a template type parameter but the template argument is an
3048 // expression; see if maybe it is missing the "typename" keyword.
3050 DeclarationNameInfo NameInfo;
3052 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3053 SS.Adopt(ArgExpr->getQualifierLoc());
3054 NameInfo = ArgExpr->getNameInfo();
3055 } else if (DependentScopeDeclRefExpr *ArgExpr =
3056 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3057 SS.Adopt(ArgExpr->getQualifierLoc());
3058 NameInfo = ArgExpr->getNameInfo();
3059 } else if (CXXDependentScopeMemberExpr *ArgExpr =
3060 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
3061 if (ArgExpr->isImplicitAccess()) {
3062 SS.Adopt(ArgExpr->getQualifierLoc());
3063 NameInfo = ArgExpr->getMemberNameInfo();
3067 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
3068 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3069 LookupParsedName(Result, CurScope, &SS);
3071 if (Result.getAsSingle<TypeDecl>() ||
3072 Result.getResultKind() ==
3073 LookupResult::NotFoundInCurrentInstantiation) {
3074 // Suggest that the user add 'typename' before the NNS.
3075 SourceLocation Loc = AL.getSourceRange().getBegin();
3076 Diag(Loc, getLangOpts().MSVCCompat
3077 ? diag::ext_ms_template_type_arg_missing_typename
3078 : diag::err_template_arg_must_be_type_suggest)
3079 << FixItHint::CreateInsertion(Loc, "typename ");
3080 Diag(Param->getLocation(), diag::note_template_param_here);
3082 // Recover by synthesizing a type using the location information that we
3085 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
3087 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
3088 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
3089 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3090 TL.setNameLoc(NameInfo.getLoc());
3091 TSI = TLB.getTypeSourceInfo(Context, ArgType);
3093 // Overwrite our input TemplateArgumentLoc so that we can recover
3095 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
3096 TemplateArgumentLocInfo(TSI));
3104 // We have a template type parameter but the template argument
3106 SourceRange SR = AL.getSourceRange();
3107 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
3108 Diag(Param->getLocation(), diag::note_template_param_here);
3114 if (CheckTemplateArgument(Param, TSI))
3117 // Add the converted template type argument.
3118 ArgType = Context.getCanonicalType(ArgType);
3121 // If an explicitly-specified template argument type is a lifetime type
3122 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
3123 if (getLangOpts().ObjCAutoRefCount &&
3124 ArgType->isObjCLifetimeType() &&
3125 !ArgType.getObjCLifetime()) {
3127 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
3128 ArgType = Context.getQualifiedType(ArgType, Qs);
3131 Converted.push_back(TemplateArgument(ArgType));
3135 /// \brief Substitute template arguments into the default template argument for
3136 /// the given template type parameter.
3138 /// \param SemaRef the semantic analysis object for which we are performing
3139 /// the substitution.
3141 /// \param Template the template that we are synthesizing template arguments
3144 /// \param TemplateLoc the location of the template name that started the
3145 /// template-id we are checking.
3147 /// \param RAngleLoc the location of the right angle bracket ('>') that
3148 /// terminates the template-id.
3150 /// \param Param the template template parameter whose default we are
3151 /// substituting into.
3153 /// \param Converted the list of template arguments provided for template
3154 /// parameters that precede \p Param in the template parameter list.
3155 /// \returns the substituted template argument, or NULL if an error occurred.
3156 static TypeSourceInfo *
3157 SubstDefaultTemplateArgument(Sema &SemaRef,
3158 TemplateDecl *Template,
3159 SourceLocation TemplateLoc,
3160 SourceLocation RAngleLoc,
3161 TemplateTypeParmDecl *Param,
3162 SmallVectorImpl<TemplateArgument> &Converted) {
3163 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
3165 // If the argument type is dependent, instantiate it now based
3166 // on the previously-computed template arguments.
3167 if (ArgType->getType()->isDependentType()) {
3168 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
3169 Template, Converted,
3170 SourceRange(TemplateLoc, RAngleLoc));
3171 if (Inst.isInvalid())
3174 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3175 Converted.data(), Converted.size());
3177 // Only substitute for the innermost template argument list.
3178 MultiLevelTemplateArgumentList TemplateArgLists;
3179 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3180 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3181 TemplateArgLists.addOuterTemplateArguments(None);
3183 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
3185 SemaRef.SubstType(ArgType, TemplateArgLists,
3186 Param->getDefaultArgumentLoc(), Param->getDeclName());
3192 /// \brief Substitute template arguments into the default template argument for
3193 /// the given non-type template parameter.
3195 /// \param SemaRef the semantic analysis object for which we are performing
3196 /// the substitution.
3198 /// \param Template the template that we are synthesizing template arguments
3201 /// \param TemplateLoc the location of the template name that started the
3202 /// template-id we are checking.
3204 /// \param RAngleLoc the location of the right angle bracket ('>') that
3205 /// terminates the template-id.
3207 /// \param Param the non-type template parameter whose default we are
3208 /// substituting into.
3210 /// \param Converted the list of template arguments provided for template
3211 /// parameters that precede \p Param in the template parameter list.
3213 /// \returns the substituted template argument, or NULL if an error occurred.
3215 SubstDefaultTemplateArgument(Sema &SemaRef,
3216 TemplateDecl *Template,
3217 SourceLocation TemplateLoc,
3218 SourceLocation RAngleLoc,
3219 NonTypeTemplateParmDecl *Param,
3220 SmallVectorImpl<TemplateArgument> &Converted) {
3221 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
3222 Template, Converted,
3223 SourceRange(TemplateLoc, RAngleLoc));
3224 if (Inst.isInvalid())
3227 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3228 Converted.data(), Converted.size());
3230 // Only substitute for the innermost template argument list.
3231 MultiLevelTemplateArgumentList TemplateArgLists;
3232 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3233 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3234 TemplateArgLists.addOuterTemplateArguments(None);
3236 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
3237 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
3238 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
3241 /// \brief Substitute template arguments into the default template argument for
3242 /// the given template template parameter.
3244 /// \param SemaRef the semantic analysis object for which we are performing
3245 /// the substitution.
3247 /// \param Template the template that we are synthesizing template arguments
3250 /// \param TemplateLoc the location of the template name that started the
3251 /// template-id we are checking.
3253 /// \param RAngleLoc the location of the right angle bracket ('>') that
3254 /// terminates the template-id.
3256 /// \param Param the template template parameter whose default we are
3257 /// substituting into.
3259 /// \param Converted the list of template arguments provided for template
3260 /// parameters that precede \p Param in the template parameter list.
3262 /// \param QualifierLoc Will be set to the nested-name-specifier (with
3263 /// source-location information) that precedes the template name.
3265 /// \returns the substituted template argument, or NULL if an error occurred.
3267 SubstDefaultTemplateArgument(Sema &SemaRef,
3268 TemplateDecl *Template,
3269 SourceLocation TemplateLoc,
3270 SourceLocation RAngleLoc,
3271 TemplateTemplateParmDecl *Param,
3272 SmallVectorImpl<TemplateArgument> &Converted,
3273 NestedNameSpecifierLoc &QualifierLoc) {
3274 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Template, Converted,
3275 SourceRange(TemplateLoc, RAngleLoc));
3276 if (Inst.isInvalid())
3277 return TemplateName();
3279 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3280 Converted.data(), Converted.size());
3282 // Only substitute for the innermost template argument list.
3283 MultiLevelTemplateArgumentList TemplateArgLists;
3284 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3285 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3286 TemplateArgLists.addOuterTemplateArguments(None);
3288 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
3289 // Substitute into the nested-name-specifier first,
3290 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
3293 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
3295 return TemplateName();
3298 return SemaRef.SubstTemplateName(
3300 Param->getDefaultArgument().getArgument().getAsTemplate(),
3301 Param->getDefaultArgument().getTemplateNameLoc(),
3305 /// \brief If the given template parameter has a default template
3306 /// argument, substitute into that default template argument and
3307 /// return the corresponding template argument.
3309 Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
3310 SourceLocation TemplateLoc,
3311 SourceLocation RAngleLoc,
3313 SmallVectorImpl<TemplateArgument>
3315 bool &HasDefaultArg) {
3316 HasDefaultArg = false;
3318 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
3319 if (!TypeParm->hasDefaultArgument())
3320 return TemplateArgumentLoc();
3322 HasDefaultArg = true;
3323 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
3329 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3331 return TemplateArgumentLoc();
3334 if (NonTypeTemplateParmDecl *NonTypeParm
3335 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3336 if (!NonTypeParm->hasDefaultArgument())
3337 return TemplateArgumentLoc();
3339 HasDefaultArg = true;
3340 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
3345 if (Arg.isInvalid())
3346 return TemplateArgumentLoc();
3348 Expr *ArgE = Arg.getAs<Expr>();
3349 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
3352 TemplateTemplateParmDecl *TempTempParm
3353 = cast<TemplateTemplateParmDecl>(Param);
3354 if (!TempTempParm->hasDefaultArgument())
3355 return TemplateArgumentLoc();
3357 HasDefaultArg = true;
3358 NestedNameSpecifierLoc QualifierLoc;
3359 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
3366 return TemplateArgumentLoc();
3368 return TemplateArgumentLoc(TemplateArgument(TName),
3369 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
3370 TempTempParm->getDefaultArgument().getTemplateNameLoc());
3373 /// \brief Check that the given template argument corresponds to the given
3374 /// template parameter.
3376 /// \param Param The template parameter against which the argument will be
3379 /// \param Arg The template argument, which may be updated due to conversions.
3381 /// \param Template The template in which the template argument resides.
3383 /// \param TemplateLoc The location of the template name for the template
3384 /// whose argument list we're matching.
3386 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
3387 /// the template argument list.
3389 /// \param ArgumentPackIndex The index into the argument pack where this
3390 /// argument will be placed. Only valid if the parameter is a parameter pack.
3392 /// \param Converted The checked, converted argument will be added to the
3393 /// end of this small vector.
3395 /// \param CTAK Describes how we arrived at this particular template argument:
3396 /// explicitly written, deduced, etc.
3398 /// \returns true on error, false otherwise.
3399 bool Sema::CheckTemplateArgument(NamedDecl *Param,
3400 TemplateArgumentLoc &Arg,
3401 NamedDecl *Template,
3402 SourceLocation TemplateLoc,
3403 SourceLocation RAngleLoc,
3404 unsigned ArgumentPackIndex,
3405 SmallVectorImpl<TemplateArgument> &Converted,
3406 CheckTemplateArgumentKind CTAK) {
3407 // Check template type parameters.
3408 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3409 return CheckTemplateTypeArgument(TTP, Arg, Converted);
3411 // Check non-type template parameters.
3412 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3413 // Do substitution on the type of the non-type template parameter
3414 // with the template arguments we've seen thus far. But if the
3415 // template has a dependent context then we cannot substitute yet.
3416 QualType NTTPType = NTTP->getType();
3417 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
3418 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
3420 if (NTTPType->isDependentType() &&
3421 !isa<TemplateTemplateParmDecl>(Template) &&
3422 !Template->getDeclContext()->isDependentContext()) {
3423 // Do substitution on the type of the non-type template parameter.
3424 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
3426 SourceRange(TemplateLoc, RAngleLoc));
3427 if (Inst.isInvalid())
3430 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3431 Converted.data(), Converted.size());
3432 NTTPType = SubstType(NTTPType,
3433 MultiLevelTemplateArgumentList(TemplateArgs),
3434 NTTP->getLocation(),
3435 NTTP->getDeclName());
3436 // If that worked, check the non-type template parameter type
3438 if (!NTTPType.isNull())
3439 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
3440 NTTP->getLocation());
3441 if (NTTPType.isNull())
3445 switch (Arg.getArgument().getKind()) {
3446 case TemplateArgument::Null:
3447 llvm_unreachable("Should never see a NULL template argument here");
3449 case TemplateArgument::Expression: {
3450 TemplateArgument Result;
3452 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
3454 if (Res.isInvalid())
3457 // If the resulting expression is new, then use it in place of the
3458 // old expression in the template argument.
3459 if (Res.get() != Arg.getArgument().getAsExpr()) {
3460 TemplateArgument TA(Res.get());
3461 Arg = TemplateArgumentLoc(TA, Res.get());
3464 Converted.push_back(Result);
3468 case TemplateArgument::Declaration:
3469 case TemplateArgument::Integral:
3470 case TemplateArgument::NullPtr:
3471 // We've already checked this template argument, so just copy
3472 // it to the list of converted arguments.
3473 Converted.push_back(Arg.getArgument());
3476 case TemplateArgument::Template:
3477 case TemplateArgument::TemplateExpansion:
3478 // We were given a template template argument. It may not be ill-formed;
3480 if (DependentTemplateName *DTN
3481 = Arg.getArgument().getAsTemplateOrTemplatePattern()
3482 .getAsDependentTemplateName()) {
3483 // We have a template argument such as \c T::template X, which we
3484 // parsed as a template template argument. However, since we now
3485 // know that we need a non-type template argument, convert this
3486 // template name into an expression.
3488 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
3489 Arg.getTemplateNameLoc());
3492 SS.Adopt(Arg.getTemplateQualifierLoc());
3493 // FIXME: the template-template arg was a DependentTemplateName,
3494 // so it was provided with a template keyword. However, its source
3495 // location is not stored in the template argument structure.
3496 SourceLocation TemplateKWLoc;
3497 ExprResult E = DependentScopeDeclRefExpr::Create(
3498 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
3501 // If we parsed the template argument as a pack expansion, create a
3502 // pack expansion expression.
3503 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
3504 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
3509 TemplateArgument Result;
3510 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
3514 Converted.push_back(Result);
3518 // We have a template argument that actually does refer to a class
3519 // template, alias template, or template template parameter, and
3520 // therefore cannot be a non-type template argument.
3521 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
3522 << Arg.getSourceRange();
3524 Diag(Param->getLocation(), diag::note_template_param_here);
3527 case TemplateArgument::Type: {
3528 // We have a non-type template parameter but the template
3529 // argument is a type.
3531 // C++ [temp.arg]p2:
3532 // In a template-argument, an ambiguity between a type-id and
3533 // an expression is resolved to a type-id, regardless of the
3534 // form of the corresponding template-parameter.
3536 // We warn specifically about this case, since it can be rather
3537 // confusing for users.
3538 QualType T = Arg.getArgument().getAsType();
3539 SourceRange SR = Arg.getSourceRange();
3540 if (T->isFunctionType())
3541 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
3543 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
3544 Diag(Param->getLocation(), diag::note_template_param_here);
3548 case TemplateArgument::Pack:
3549 llvm_unreachable("Caller must expand template argument packs");
3556 // Check template template parameters.
3557 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
3559 // Substitute into the template parameter list of the template
3560 // template parameter, since previously-supplied template arguments
3561 // may appear within the template template parameter.
3563 // Set up a template instantiation context.
3564 LocalInstantiationScope Scope(*this);
3565 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
3566 TempParm, Converted,
3567 SourceRange(TemplateLoc, RAngleLoc));
3568 if (Inst.isInvalid())
3571 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3572 Converted.data(), Converted.size());
3573 TempParm = cast_or_null<TemplateTemplateParmDecl>(
3574 SubstDecl(TempParm, CurContext,
3575 MultiLevelTemplateArgumentList(TemplateArgs)));
3580 switch (Arg.getArgument().getKind()) {
3581 case TemplateArgument::Null:
3582 llvm_unreachable("Should never see a NULL template argument here");
3584 case TemplateArgument::Template:
3585 case TemplateArgument::TemplateExpansion:
3586 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
3589 Converted.push_back(Arg.getArgument());
3592 case TemplateArgument::Expression:
3593 case TemplateArgument::Type:
3594 // We have a template template parameter but the template
3595 // argument does not refer to a template.
3596 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
3597 << getLangOpts().CPlusPlus11;
3600 case TemplateArgument::Declaration:
3601 llvm_unreachable("Declaration argument with template template parameter");
3602 case TemplateArgument::Integral:
3603 llvm_unreachable("Integral argument with template template parameter");
3604 case TemplateArgument::NullPtr:
3605 llvm_unreachable("Null pointer argument with template template parameter");
3607 case TemplateArgument::Pack:
3608 llvm_unreachable("Caller must expand template argument packs");
3614 /// \brief Diagnose an arity mismatch in the
3615 static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
3616 SourceLocation TemplateLoc,
3617 TemplateArgumentListInfo &TemplateArgs) {
3618 TemplateParameterList *Params = Template->getTemplateParameters();
3619 unsigned NumParams = Params->size();
3620 unsigned NumArgs = TemplateArgs.size();
3623 if (NumArgs > NumParams)
3624 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
3625 TemplateArgs.getRAngleLoc());
3626 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3627 << (NumArgs > NumParams)
3628 << (isa<ClassTemplateDecl>(Template)? 0 :
3629 isa<FunctionTemplateDecl>(Template)? 1 :
3630 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3631 << Template << Range;
3632 S.Diag(Template->getLocation(), diag::note_template_decl_here)
3633 << Params->getSourceRange();
3637 /// \brief Check whether the template parameter is a pack expansion, and if so,
3638 /// determine the number of parameters produced by that expansion. For instance:
3641 /// template<typename ...Ts> struct A {
3642 /// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
3646 /// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
3647 /// is not a pack expansion, so returns an empty Optional.
3648 static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
3649 if (NonTypeTemplateParmDecl *NTTP
3650 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3651 if (NTTP->isExpandedParameterPack())
3652 return NTTP->getNumExpansionTypes();
3655 if (TemplateTemplateParmDecl *TTP
3656 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3657 if (TTP->isExpandedParameterPack())
3658 return TTP->getNumExpansionTemplateParameters();
3664 /// \brief Check that the given template argument list is well-formed
3665 /// for specializing the given template.
3666 bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
3667 SourceLocation TemplateLoc,
3668 TemplateArgumentListInfo &TemplateArgs,
3669 bool PartialTemplateArgs,
3670 SmallVectorImpl<TemplateArgument> &Converted) {
3671 // Make a copy of the template arguments for processing. Only make the
3672 // changes at the end when successful in matching the arguments to the
3674 TemplateArgumentListInfo NewArgs = TemplateArgs;
3676 TemplateParameterList *Params = Template->getTemplateParameters();
3678 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
3680 // C++ [temp.arg]p1:
3681 // [...] The type and form of each template-argument specified in
3682 // a template-id shall match the type and form specified for the
3683 // corresponding parameter declared by the template in its
3684 // template-parameter-list.
3685 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
3686 SmallVector<TemplateArgument, 2> ArgumentPack;
3687 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
3688 LocalInstantiationScope InstScope(*this, true);
3689 for (TemplateParameterList::iterator Param = Params->begin(),
3690 ParamEnd = Params->end();
3691 Param != ParamEnd; /* increment in loop */) {
3692 // If we have an expanded parameter pack, make sure we don't have too
3694 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
3695 if (*Expansions == ArgumentPack.size()) {
3696 // We're done with this parameter pack. Pack up its arguments and add
3697 // them to the list.
3698 Converted.push_back(
3699 TemplateArgument::CreatePackCopy(Context,
3700 ArgumentPack.data(),
3701 ArgumentPack.size()));
3702 ArgumentPack.clear();
3704 // This argument is assigned to the next parameter.
3707 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
3708 // Not enough arguments for this parameter pack.
3709 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3711 << (isa<ClassTemplateDecl>(Template)? 0 :
3712 isa<FunctionTemplateDecl>(Template)? 1 :
3713 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3715 Diag(Template->getLocation(), diag::note_template_decl_here)
3716 << Params->getSourceRange();
3721 if (ArgIdx < NumArgs) {
3722 // Check the template argument we were given.
3723 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
3724 TemplateLoc, RAngleLoc,
3725 ArgumentPack.size(), Converted))
3728 bool PackExpansionIntoNonPack =
3729 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
3730 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
3731 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
3732 // Core issue 1430: we have a pack expansion as an argument to an
3733 // alias template, and it's not part of a parameter pack. This
3734 // can't be canonicalized, so reject it now.
3735 Diag(NewArgs[ArgIdx].getLocation(),
3736 diag::err_alias_template_expansion_into_fixed_list)
3737 << NewArgs[ArgIdx].getSourceRange();
3738 Diag((*Param)->getLocation(), diag::note_template_param_here);
3742 // We're now done with this argument.
3745 if ((*Param)->isTemplateParameterPack()) {
3746 // The template parameter was a template parameter pack, so take the
3747 // deduced argument and place it on the argument pack. Note that we
3748 // stay on the same template parameter so that we can deduce more
3750 ArgumentPack.push_back(Converted.pop_back_val());
3752 // Move to the next template parameter.
3756 // If we just saw a pack expansion into a non-pack, then directly convert
3757 // the remaining arguments, because we don't know what parameters they'll
3759 if (PackExpansionIntoNonPack) {
3760 if (!ArgumentPack.empty()) {
3761 // If we were part way through filling in an expanded parameter pack,
3762 // fall back to just producing individual arguments.
3763 Converted.insert(Converted.end(),
3764 ArgumentPack.begin(), ArgumentPack.end());
3765 ArgumentPack.clear();
3768 while (ArgIdx < NumArgs) {
3769 Converted.push_back(NewArgs[ArgIdx].getArgument());
3779 // If we're checking a partial template argument list, we're done.
3780 if (PartialTemplateArgs) {
3781 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
3782 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
3783 ArgumentPack.data(),
3784 ArgumentPack.size()));
3789 // If we have a template parameter pack with no more corresponding
3790 // arguments, just break out now and we'll fill in the argument pack below.
3791 if ((*Param)->isTemplateParameterPack()) {
3792 assert(!getExpandedPackSize(*Param) &&
3793 "Should have dealt with this already");
3795 // A non-expanded parameter pack before the end of the parameter list
3796 // only occurs for an ill-formed template parameter list, unless we've
3797 // got a partial argument list for a function template, so just bail out.
3798 if (Param + 1 != ParamEnd)
3801 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
3802 ArgumentPack.data(),
3803 ArgumentPack.size()));
3804 ArgumentPack.clear();
3810 // Check whether we have a default argument.
3811 TemplateArgumentLoc Arg;
3813 // Retrieve the default template argument from the template
3814 // parameter. For each kind of template parameter, we substitute the
3815 // template arguments provided thus far and any "outer" template arguments
3816 // (when the template parameter was part of a nested template) into
3817 // the default argument.
3818 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
3819 if (!TTP->hasDefaultArgument())
3820 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
3822 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
3831 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
3833 } else if (NonTypeTemplateParmDecl *NTTP
3834 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
3835 if (!NTTP->hasDefaultArgument())
3836 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
3838 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
3846 Expr *Ex = E.getAs<Expr>();
3847 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
3849 TemplateTemplateParmDecl *TempParm
3850 = cast<TemplateTemplateParmDecl>(*Param);
3852 if (!TempParm->hasDefaultArgument())
3853 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
3855 NestedNameSpecifierLoc QualifierLoc;
3856 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
3865 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
3866 TempParm->getDefaultArgument().getTemplateNameLoc());
3869 // Introduce an instantiation record that describes where we are using
3870 // the default template argument.
3871 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
3872 SourceRange(TemplateLoc, RAngleLoc));
3873 if (Inst.isInvalid())
3876 // Check the default template argument.
3877 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
3878 RAngleLoc, 0, Converted))
3881 // Core issue 150 (assumed resolution): if this is a template template
3882 // parameter, keep track of the default template arguments from the
3883 // template definition.
3884 if (isTemplateTemplateParameter)
3885 NewArgs.addArgument(Arg);
3887 // Move to the next template parameter and argument.
3892 // If we're performing a partial argument substitution, allow any trailing
3893 // pack expansions; they might be empty. This can happen even if
3894 // PartialTemplateArgs is false (the list of arguments is complete but
3895 // still dependent).
3896 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
3897 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
3898 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
3899 Converted.push_back(NewArgs[ArgIdx++].getArgument());
3902 // If we have any leftover arguments, then there were too many arguments.
3903 // Complain and fail.
3904 if (ArgIdx < NumArgs)
3905 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
3907 // No problems found with the new argument list, propagate changes back
3909 TemplateArgs = NewArgs;
3915 class UnnamedLocalNoLinkageFinder
3916 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
3921 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
3924 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
3926 bool Visit(QualType T) {
3927 return inherited::Visit(T.getTypePtr());
3930 #define TYPE(Class, Parent) \
3931 bool Visit##Class##Type(const Class##Type *);
3932 #define ABSTRACT_TYPE(Class, Parent) \
3933 bool Visit##Class##Type(const Class##Type *) { return false; }
3934 #define NON_CANONICAL_TYPE(Class, Parent) \
3935 bool Visit##Class##Type(const Class##Type *) { return false; }
3936 #include "clang/AST/TypeNodes.def"
3938 bool VisitTagDecl(const TagDecl *Tag);
3939 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
3943 bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
3947 bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
3948 return Visit(T->getElementType());
3951 bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
3952 return Visit(T->getPointeeType());
3955 bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
3956 const BlockPointerType* T) {
3957 return Visit(T->getPointeeType());
3960 bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
3961 const LValueReferenceType* T) {
3962 return Visit(T->getPointeeType());
3965 bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
3966 const RValueReferenceType* T) {
3967 return Visit(T->getPointeeType());
3970 bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
3971 const MemberPointerType* T) {
3972 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
3975 bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
3976 const ConstantArrayType* T) {
3977 return Visit(T->getElementType());
3980 bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
3981 const IncompleteArrayType* T) {
3982 return Visit(T->getElementType());
3985 bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
3986 const VariableArrayType* T) {
3987 return Visit(T->getElementType());
3990 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
3991 const DependentSizedArrayType* T) {
3992 return Visit(T->getElementType());
3995 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
3996 const DependentSizedExtVectorType* T) {
3997 return Visit(T->getElementType());
4000 bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
4001 return Visit(T->getElementType());
4004 bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
4005 return Visit(T->getElementType());
4008 bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
4009 const FunctionProtoType* T) {
4010 for (const auto &A : T->param_types()) {
4015 return Visit(T->getReturnType());
4018 bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
4019 const FunctionNoProtoType* T) {
4020 return Visit(T->getReturnType());
4023 bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
4024 const UnresolvedUsingType*) {
4028 bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
4032 bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
4033 return Visit(T->getUnderlyingType());
4036 bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
4040 bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
4041 const UnaryTransformType*) {
4045 bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
4046 return Visit(T->getDeducedType());
4049 bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
4050 return VisitTagDecl(T->getDecl());
4053 bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
4054 return VisitTagDecl(T->getDecl());
4057 bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
4058 const TemplateTypeParmType*) {
4062 bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
4063 const SubstTemplateTypeParmPackType *) {
4067 bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
4068 const TemplateSpecializationType*) {
4072 bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
4073 const InjectedClassNameType* T) {
4074 return VisitTagDecl(T->getDecl());
4077 bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
4078 const DependentNameType* T) {
4079 return VisitNestedNameSpecifier(T->getQualifier());
4082 bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
4083 const DependentTemplateSpecializationType* T) {
4084 return VisitNestedNameSpecifier(T->getQualifier());
4087 bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
4088 const PackExpansionType* T) {
4089 return Visit(T->getPattern());
4092 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
4096 bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
4097 const ObjCInterfaceType *) {
4101 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
4102 const ObjCObjectPointerType *) {
4106 bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
4107 return Visit(T->getValueType());
4110 bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
4111 if (Tag->getDeclContext()->isFunctionOrMethod()) {
4112 S.Diag(SR.getBegin(),
4113 S.getLangOpts().CPlusPlus11 ?
4114 diag::warn_cxx98_compat_template_arg_local_type :
4115 diag::ext_template_arg_local_type)
4116 << S.Context.getTypeDeclType(Tag) << SR;
4120 if (!Tag->hasNameForLinkage()) {
4121 S.Diag(SR.getBegin(),
4122 S.getLangOpts().CPlusPlus11 ?
4123 diag::warn_cxx98_compat_template_arg_unnamed_type :
4124 diag::ext_template_arg_unnamed_type) << SR;
4125 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
4132 bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
4133 NestedNameSpecifier *NNS) {
4134 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
4137 switch (NNS->getKind()) {
4138 case NestedNameSpecifier::Identifier:
4139 case NestedNameSpecifier::Namespace:
4140 case NestedNameSpecifier::NamespaceAlias:
4141 case NestedNameSpecifier::Global:
4142 case NestedNameSpecifier::Super:
4145 case NestedNameSpecifier::TypeSpec:
4146 case NestedNameSpecifier::TypeSpecWithTemplate:
4147 return Visit(QualType(NNS->getAsType(), 0));
4149 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
4153 /// \brief Check a template argument against its corresponding
4154 /// template type parameter.
4156 /// This routine implements the semantics of C++ [temp.arg.type]. It
4157 /// returns true if an error occurred, and false otherwise.
4158 bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
4159 TypeSourceInfo *ArgInfo) {
4160 assert(ArgInfo && "invalid TypeSourceInfo");
4161 QualType Arg = ArgInfo->getType();
4162 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
4164 if (Arg->isVariablyModifiedType()) {
4165 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
4166 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
4167 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
4170 // C++03 [temp.arg.type]p2:
4171 // A local type, a type with no linkage, an unnamed type or a type
4172 // compounded from any of these types shall not be used as a
4173 // template-argument for a template type-parameter.
4175 // C++11 allows these, and even in C++03 we allow them as an extension with
4178 if (LangOpts.CPlusPlus11)
4180 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_unnamed_type,
4182 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_local_type,
4185 NeedsCheck = Arg->hasUnnamedOrLocalType();
4188 UnnamedLocalNoLinkageFinder Finder(*this, SR);
4189 (void)Finder.Visit(Context.getCanonicalType(Arg));
4195 enum NullPointerValueKind {
4201 /// \brief Determine whether the given template argument is a null pointer
4202 /// value of the appropriate type.
4203 static NullPointerValueKind
4204 isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
4205 QualType ParamType, Expr *Arg) {
4206 if (Arg->isValueDependent() || Arg->isTypeDependent())
4207 return NPV_NotNullPointer;
4209 if (!S.getLangOpts().CPlusPlus11)
4210 return NPV_NotNullPointer;
4212 // Determine whether we have a constant expression.
4213 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
4214 if (ArgRV.isInvalid())
4218 Expr::EvalResult EvalResult;
4219 SmallVector<PartialDiagnosticAt, 8> Notes;
4220 EvalResult.Diag = &Notes;
4221 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
4222 EvalResult.HasSideEffects) {
4223 SourceLocation DiagLoc = Arg->getExprLoc();
4225 // If our only note is the usual "invalid subexpression" note, just point
4226 // the caret at its location rather than producing an essentially
4228 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
4229 diag::note_invalid_subexpr_in_const_expr) {
4230 DiagLoc = Notes[0].first;
4234 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
4235 << Arg->getType() << Arg->getSourceRange();
4236 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
4237 S.Diag(Notes[I].first, Notes[I].second);
4239 S.Diag(Param->getLocation(), diag::note_template_param_here);
4243 // C++11 [temp.arg.nontype]p1:
4244 // - an address constant expression of type std::nullptr_t
4245 if (Arg->getType()->isNullPtrType())
4246 return NPV_NullPointer;
4248 // - a constant expression that evaluates to a null pointer value (4.10); or
4249 // - a constant expression that evaluates to a null member pointer value
4251 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
4252 (EvalResult.Val.isMemberPointer() &&
4253 !EvalResult.Val.getMemberPointerDecl())) {
4254 // If our expression has an appropriate type, we've succeeded.
4255 bool ObjCLifetimeConversion;
4256 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
4257 S.IsQualificationConversion(Arg->getType(), ParamType, false,
4258 ObjCLifetimeConversion))
4259 return NPV_NullPointer;
4261 // The types didn't match, but we know we got a null pointer; complain,
4262 // then recover as if the types were correct.
4263 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
4264 << Arg->getType() << ParamType << Arg->getSourceRange();
4265 S.Diag(Param->getLocation(), diag::note_template_param_here);
4266 return NPV_NullPointer;
4269 // If we don't have a null pointer value, but we do have a NULL pointer
4270 // constant, suggest a cast to the appropriate type.
4271 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
4272 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
4273 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
4274 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
4275 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
4277 S.Diag(Param->getLocation(), diag::note_template_param_here);
4278 return NPV_NullPointer;
4281 // FIXME: If we ever want to support general, address-constant expressions
4282 // as non-type template arguments, we should return the ExprResult here to
4283 // be interpreted by the caller.
4284 return NPV_NotNullPointer;
4287 /// \brief Checks whether the given template argument is compatible with its
4288 /// template parameter.
4289 static bool CheckTemplateArgumentIsCompatibleWithParameter(
4290 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
4291 Expr *Arg, QualType ArgType) {
4292 bool ObjCLifetimeConversion;
4293 if (ParamType->isPointerType() &&
4294 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
4295 S.IsQualificationConversion(ArgType, ParamType, false,
4296 ObjCLifetimeConversion)) {
4297 // For pointer-to-object types, qualification conversions are
4300 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
4301 if (!ParamRef->getPointeeType()->isFunctionType()) {
4302 // C++ [temp.arg.nontype]p5b3:
4303 // For a non-type template-parameter of type reference to
4304 // object, no conversions apply. The type referred to by the
4305 // reference may be more cv-qualified than the (otherwise
4306 // identical) type of the template- argument. The
4307 // template-parameter is bound directly to the
4308 // template-argument, which shall be an lvalue.
4310 // FIXME: Other qualifiers?
4311 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
4312 unsigned ArgQuals = ArgType.getCVRQualifiers();
4314 if ((ParamQuals | ArgQuals) != ParamQuals) {
4315 S.Diag(Arg->getLocStart(),
4316 diag::err_template_arg_ref_bind_ignores_quals)
4317 << ParamType << Arg->getType() << Arg->getSourceRange();
4318 S.Diag(Param->getLocation(), diag::note_template_param_here);
4324 // At this point, the template argument refers to an object or
4325 // function with external linkage. We now need to check whether the
4326 // argument and parameter types are compatible.
4327 if (!S.Context.hasSameUnqualifiedType(ArgType,
4328 ParamType.getNonReferenceType())) {
4329 // We can't perform this conversion or binding.
4330 if (ParamType->isReferenceType())
4331 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
4332 << ParamType << ArgIn->getType() << Arg->getSourceRange();
4334 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4335 << ArgIn->getType() << ParamType << Arg->getSourceRange();
4336 S.Diag(Param->getLocation(), diag::note_template_param_here);
4344 /// \brief Checks whether the given template argument is the address
4345 /// of an object or function according to C++ [temp.arg.nontype]p1.
4347 CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
4348 NonTypeTemplateParmDecl *Param,
4351 TemplateArgument &Converted) {
4352 bool Invalid = false;
4354 QualType ArgType = Arg->getType();
4356 bool AddressTaken = false;
4357 SourceLocation AddrOpLoc;
4358 if (S.getLangOpts().MicrosoftExt) {
4359 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
4360 // dereference and address-of operators.
4361 Arg = Arg->IgnoreParenCasts();
4363 bool ExtWarnMSTemplateArg = false;
4364 UnaryOperatorKind FirstOpKind;
4365 SourceLocation FirstOpLoc;
4366 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4367 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
4368 if (UnOpKind == UO_Deref)
4369 ExtWarnMSTemplateArg = true;
4370 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
4371 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
4372 if (!AddrOpLoc.isValid()) {
4373 FirstOpKind = UnOpKind;
4374 FirstOpLoc = UnOp->getOperatorLoc();
4379 if (FirstOpLoc.isValid()) {
4380 if (ExtWarnMSTemplateArg)
4381 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
4382 << ArgIn->getSourceRange();
4384 if (FirstOpKind == UO_AddrOf)
4385 AddressTaken = true;
4386 else if (Arg->getType()->isPointerType()) {
4387 // We cannot let pointers get dereferenced here, that is obviously not a
4388 // constant expression.
4389 assert(FirstOpKind == UO_Deref);
4390 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4391 << Arg->getSourceRange();
4395 // See through any implicit casts we added to fix the type.
4396 Arg = Arg->IgnoreImpCasts();
4398 // C++ [temp.arg.nontype]p1:
4400 // A template-argument for a non-type, non-template
4401 // template-parameter shall be one of: [...]
4403 // -- the address of an object or function with external
4404 // linkage, including function templates and function
4405 // template-ids but excluding non-static class members,
4406 // expressed as & id-expression where the & is optional if
4407 // the name refers to a function or array, or if the
4408 // corresponding template-parameter is a reference; or
4410 // In C++98/03 mode, give an extension warning on any extra parentheses.
4411 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4412 bool ExtraParens = false;
4413 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4414 if (!Invalid && !ExtraParens) {
4415 S.Diag(Arg->getLocStart(),
4416 S.getLangOpts().CPlusPlus11
4417 ? diag::warn_cxx98_compat_template_arg_extra_parens
4418 : diag::ext_template_arg_extra_parens)
4419 << Arg->getSourceRange();
4423 Arg = Parens->getSubExpr();
4426 while (SubstNonTypeTemplateParmExpr *subst =
4427 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4428 Arg = subst->getReplacement()->IgnoreImpCasts();
4430 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4431 if (UnOp->getOpcode() == UO_AddrOf) {
4432 Arg = UnOp->getSubExpr();
4433 AddressTaken = true;
4434 AddrOpLoc = UnOp->getOperatorLoc();
4438 while (SubstNonTypeTemplateParmExpr *subst =
4439 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4440 Arg = subst->getReplacement()->IgnoreImpCasts();
4443 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
4444 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
4446 // If our parameter has pointer type, check for a null template value.
4447 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
4448 NullPointerValueKind NPV;
4449 // dllimport'd entities aren't constant but are available inside of template
4451 if (Entity && Entity->hasAttr<DLLImportAttr>())
4452 NPV = NPV_NotNullPointer;
4454 NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
4456 case NPV_NullPointer:
4457 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
4458 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4459 /*isNullPtr=*/true);
4465 case NPV_NotNullPointer:
4470 // Stop checking the precise nature of the argument if it is value dependent,
4471 // it should be checked when instantiated.
4472 if (Arg->isValueDependent()) {
4473 Converted = TemplateArgument(ArgIn);
4477 if (isa<CXXUuidofExpr>(Arg)) {
4478 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
4479 ArgIn, Arg, ArgType))
4482 Converted = TemplateArgument(ArgIn);
4487 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4488 << Arg->getSourceRange();
4489 S.Diag(Param->getLocation(), diag::note_template_param_here);
4493 // Cannot refer to non-static data members
4494 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
4495 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
4496 << Entity << Arg->getSourceRange();
4497 S.Diag(Param->getLocation(), diag::note_template_param_here);
4501 // Cannot refer to non-static member functions
4502 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
4503 if (!Method->isStatic()) {
4504 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
4505 << Method << Arg->getSourceRange();
4506 S.Diag(Param->getLocation(), diag::note_template_param_here);
4511 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
4512 VarDecl *Var = dyn_cast<VarDecl>(Entity);
4514 // A non-type template argument must refer to an object or function.
4515 if (!Func && !Var) {
4516 // We found something, but we don't know specifically what it is.
4517 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
4518 << Arg->getSourceRange();
4519 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4523 // Address / reference template args must have external linkage in C++98.
4524 if (Entity->getFormalLinkage() == InternalLinkage) {
4525 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
4526 diag::warn_cxx98_compat_template_arg_object_internal :
4527 diag::ext_template_arg_object_internal)
4528 << !Func << Entity << Arg->getSourceRange();
4529 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4531 } else if (!Entity->hasLinkage()) {
4532 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
4533 << !Func << Entity << Arg->getSourceRange();
4534 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4540 // If the template parameter has pointer type, the function decays.
4541 if (ParamType->isPointerType() && !AddressTaken)
4542 ArgType = S.Context.getPointerType(Func->getType());
4543 else if (AddressTaken && ParamType->isReferenceType()) {
4544 // If we originally had an address-of operator, but the
4545 // parameter has reference type, complain and (if things look
4546 // like they will work) drop the address-of operator.
4547 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
4548 ParamType.getNonReferenceType())) {
4549 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4551 S.Diag(Param->getLocation(), diag::note_template_param_here);
4555 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4557 << FixItHint::CreateRemoval(AddrOpLoc);
4558 S.Diag(Param->getLocation(), diag::note_template_param_here);
4560 ArgType = Func->getType();
4563 // A value of reference type is not an object.
4564 if (Var->getType()->isReferenceType()) {
4565 S.Diag(Arg->getLocStart(),
4566 diag::err_template_arg_reference_var)
4567 << Var->getType() << Arg->getSourceRange();
4568 S.Diag(Param->getLocation(), diag::note_template_param_here);
4572 // A template argument must have static storage duration.
4573 if (Var->getTLSKind()) {
4574 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
4575 << Arg->getSourceRange();
4576 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
4580 // If the template parameter has pointer type, we must have taken
4581 // the address of this object.
4582 if (ParamType->isReferenceType()) {
4584 // If we originally had an address-of operator, but the
4585 // parameter has reference type, complain and (if things look
4586 // like they will work) drop the address-of operator.
4587 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
4588 ParamType.getNonReferenceType())) {
4589 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4591 S.Diag(Param->getLocation(), diag::note_template_param_here);
4595 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4597 << FixItHint::CreateRemoval(AddrOpLoc);
4598 S.Diag(Param->getLocation(), diag::note_template_param_here);
4600 ArgType = Var->getType();
4602 } else if (!AddressTaken && ParamType->isPointerType()) {
4603 if (Var->getType()->isArrayType()) {
4604 // Array-to-pointer decay.
4605 ArgType = S.Context.getArrayDecayedType(Var->getType());
4607 // If the template parameter has pointer type but the address of
4608 // this object was not taken, complain and (possibly) recover by
4609 // taking the address of the entity.
4610 ArgType = S.Context.getPointerType(Var->getType());
4611 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
4612 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4614 S.Diag(Param->getLocation(), diag::note_template_param_here);
4618 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4620 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
4622 S.Diag(Param->getLocation(), diag::note_template_param_here);
4627 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
4631 // Create the template argument.
4633 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
4634 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
4638 /// \brief Checks whether the given template argument is a pointer to
4639 /// member constant according to C++ [temp.arg.nontype]p1.
4640 static bool CheckTemplateArgumentPointerToMember(Sema &S,
4641 NonTypeTemplateParmDecl *Param,
4644 TemplateArgument &Converted) {
4645 bool Invalid = false;
4647 // Check for a null pointer value.
4648 Expr *Arg = ResultArg;
4649 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
4652 case NPV_NullPointer:
4653 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
4654 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4656 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft())
4657 S.RequireCompleteType(Arg->getExprLoc(), ParamType, 0);
4659 case NPV_NotNullPointer:
4663 bool ObjCLifetimeConversion;
4664 if (S.IsQualificationConversion(Arg->getType(),
4665 ParamType.getNonReferenceType(),
4666 false, ObjCLifetimeConversion)) {
4667 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
4668 Arg->getValueKind()).get();
4670 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
4671 ParamType.getNonReferenceType())) {
4672 // We can't perform this conversion.
4673 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4674 << Arg->getType() << ParamType << Arg->getSourceRange();
4675 S.Diag(Param->getLocation(), diag::note_template_param_here);
4679 // See through any implicit casts we added to fix the type.
4680 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
4681 Arg = Cast->getSubExpr();
4683 // C++ [temp.arg.nontype]p1:
4685 // A template-argument for a non-type, non-template
4686 // template-parameter shall be one of: [...]
4688 // -- a pointer to member expressed as described in 5.3.1.
4689 DeclRefExpr *DRE = nullptr;
4691 // In C++98/03 mode, give an extension warning on any extra parentheses.
4692 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4693 bool ExtraParens = false;
4694 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4695 if (!Invalid && !ExtraParens) {
4696 S.Diag(Arg->getLocStart(),
4697 S.getLangOpts().CPlusPlus11 ?
4698 diag::warn_cxx98_compat_template_arg_extra_parens :
4699 diag::ext_template_arg_extra_parens)
4700 << Arg->getSourceRange();
4704 Arg = Parens->getSubExpr();
4707 while (SubstNonTypeTemplateParmExpr *subst =
4708 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4709 Arg = subst->getReplacement()->IgnoreImpCasts();
4711 // A pointer-to-member constant written &Class::member.
4712 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4713 if (UnOp->getOpcode() == UO_AddrOf) {
4714 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
4715 if (DRE && !DRE->getQualifier())
4719 // A constant of pointer-to-member type.
4720 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
4721 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
4722 if (VD->getType()->isMemberPointerType()) {
4723 if (isa<NonTypeTemplateParmDecl>(VD)) {
4724 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
4725 Converted = TemplateArgument(Arg);
4727 VD = cast<ValueDecl>(VD->getCanonicalDecl());
4728 Converted = TemplateArgument(VD, ParamType);
4739 return S.Diag(Arg->getLocStart(),
4740 diag::err_template_arg_not_pointer_to_member_form)
4741 << Arg->getSourceRange();
4743 if (isa<FieldDecl>(DRE->getDecl()) ||
4744 isa<IndirectFieldDecl>(DRE->getDecl()) ||
4745 isa<CXXMethodDecl>(DRE->getDecl())) {
4746 assert((isa<FieldDecl>(DRE->getDecl()) ||
4747 isa<IndirectFieldDecl>(DRE->getDecl()) ||
4748 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
4749 "Only non-static member pointers can make it here");
4751 // Okay: this is the address of a non-static member, and therefore
4752 // a member pointer constant.
4753 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
4754 Converted = TemplateArgument(Arg);
4756 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
4757 Converted = TemplateArgument(D, ParamType);
4762 // We found something else, but we don't know specifically what it is.
4763 S.Diag(Arg->getLocStart(),
4764 diag::err_template_arg_not_pointer_to_member_form)
4765 << Arg->getSourceRange();
4766 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4770 /// \brief Check a template argument against its corresponding
4771 /// non-type template parameter.
4773 /// This routine implements the semantics of C++ [temp.arg.nontype].
4774 /// If an error occurred, it returns ExprError(); otherwise, it
4775 /// returns the converted template argument. \p ParamType is the
4776 /// type of the non-type template parameter after it has been instantiated.
4777 ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
4778 QualType ParamType, Expr *Arg,
4779 TemplateArgument &Converted,
4780 CheckTemplateArgumentKind CTAK) {
4781 SourceLocation StartLoc = Arg->getLocStart();
4783 // If either the parameter has a dependent type or the argument is
4784 // type-dependent, there's nothing we can check now.
4785 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
4786 // FIXME: Produce a cloned, canonical expression?
4787 Converted = TemplateArgument(Arg);
4791 // We should have already dropped all cv-qualifiers by now.
4792 assert(!ParamType.hasQualifiers() &&
4793 "non-type template parameter type cannot be qualified");
4795 if (CTAK == CTAK_Deduced &&
4796 !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) {
4797 // C++ [temp.deduct.type]p17:
4798 // If, in the declaration of a function template with a non-type
4799 // template-parameter, the non-type template-parameter is used
4800 // in an expression in the function parameter-list and, if the
4801 // corresponding template-argument is deduced, the
4802 // template-argument type shall match the type of the
4803 // template-parameter exactly, except that a template-argument
4804 // deduced from an array bound may be of any integral type.
4805 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
4806 << Arg->getType().getUnqualifiedType()
4807 << ParamType.getUnqualifiedType();
4808 Diag(Param->getLocation(), diag::note_template_param_here);
4812 if (getLangOpts().CPlusPlus1z) {
4813 // FIXME: We can do some limited checking for a value-dependent but not
4814 // type-dependent argument.
4815 if (Arg->isValueDependent()) {
4816 Converted = TemplateArgument(Arg);
4820 // C++1z [temp.arg.nontype]p1:
4821 // A template-argument for a non-type template parameter shall be
4822 // a converted constant expression of the type of the template-parameter.
4824 ExprResult ArgResult = CheckConvertedConstantExpression(
4825 Arg, ParamType, Value, CCEK_TemplateArg);
4826 if (ArgResult.isInvalid())
4829 QualType CanonParamType = Context.getCanonicalType(ParamType);
4831 // Convert the APValue to a TemplateArgument.
4832 switch (Value.getKind()) {
4833 case APValue::Uninitialized:
4834 assert(ParamType->isNullPtrType());
4835 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
4838 assert(ParamType->isIntegralOrEnumerationType());
4839 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
4841 case APValue::MemberPointer: {
4842 assert(ParamType->isMemberPointerType());
4844 // FIXME: We need TemplateArgument representation and mangling for these.
4845 if (!Value.getMemberPointerPath().empty()) {
4846 Diag(Arg->getLocStart(),
4847 diag::err_template_arg_member_ptr_base_derived_not_supported)
4848 << Value.getMemberPointerDecl() << ParamType
4849 << Arg->getSourceRange();
4853 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
4854 Converted = VD ? TemplateArgument(VD, CanonParamType)
4855 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
4858 case APValue::LValue: {
4859 // For a non-type template-parameter of pointer or reference type,
4860 // the value of the constant expression shall not refer to
4861 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
4862 ParamType->isNullPtrType());
4863 // -- a temporary object
4864 // -- a string literal
4865 // -- the result of a typeid expression, or
4866 // -- a predefind __func__ variable
4867 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
4868 if (isa<CXXUuidofExpr>(E)) {
4869 Converted = TemplateArgument(const_cast<Expr*>(E));
4872 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4873 << Arg->getSourceRange();
4876 auto *VD = const_cast<ValueDecl *>(
4877 Value.getLValueBase().dyn_cast<const ValueDecl *>());
4879 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
4880 VD && VD->getType()->isArrayType() &&
4881 Value.getLValuePath()[0].ArrayIndex == 0 &&
4882 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
4883 // Per defect report (no number yet):
4884 // ... other than a pointer to the first element of a complete array
4886 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
4887 Value.isLValueOnePastTheEnd()) {
4888 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
4889 << Value.getAsString(Context, ParamType);
4892 assert((VD || !ParamType->isReferenceType()) &&
4893 "null reference should not be a constant expression");
4894 assert((!VD || !ParamType->isNullPtrType()) &&
4895 "non-null value of type nullptr_t?");
4896 Converted = VD ? TemplateArgument(VD, CanonParamType)
4897 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
4900 case APValue::AddrLabelDiff:
4901 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
4902 case APValue::Float:
4903 case APValue::ComplexInt:
4904 case APValue::ComplexFloat:
4905 case APValue::Vector:
4906 case APValue::Array:
4907 case APValue::Struct:
4908 case APValue::Union:
4909 llvm_unreachable("invalid kind for template argument");
4912 return ArgResult.get();
4915 // C++ [temp.arg.nontype]p5:
4916 // The following conversions are performed on each expression used
4917 // as a non-type template-argument. If a non-type
4918 // template-argument cannot be converted to the type of the
4919 // corresponding template-parameter then the program is
4921 if (ParamType->isIntegralOrEnumerationType()) {
4923 // -- for a non-type template-parameter of integral or
4924 // enumeration type, conversions permitted in a converted
4925 // constant expression are applied.
4928 // -- for a non-type template-parameter of integral or
4929 // enumeration type, integral promotions (4.5) and integral
4930 // conversions (4.7) are applied.
4932 if (getLangOpts().CPlusPlus11) {
4933 // We can't check arbitrary value-dependent arguments.
4934 // FIXME: If there's no viable conversion to the template parameter type,
4935 // we should be able to diagnose that prior to instantiation.
4936 if (Arg->isValueDependent()) {
4937 Converted = TemplateArgument(Arg);
4941 // C++ [temp.arg.nontype]p1:
4942 // A template-argument for a non-type, non-template template-parameter
4945 // -- for a non-type template-parameter of integral or enumeration
4946 // type, a converted constant expression of the type of the
4947 // template-parameter; or
4949 ExprResult ArgResult =
4950 CheckConvertedConstantExpression(Arg, ParamType, Value,
4952 if (ArgResult.isInvalid())
4955 // Widen the argument value to sizeof(parameter type). This is almost
4956 // always a no-op, except when the parameter type is bool. In
4957 // that case, this may extend the argument from 1 bit to 8 bits.
4958 QualType IntegerType = ParamType;
4959 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
4960 IntegerType = Enum->getDecl()->getIntegerType();
4961 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
4963 Converted = TemplateArgument(Context, Value,
4964 Context.getCanonicalType(ParamType));
4968 ExprResult ArgResult = DefaultLvalueConversion(Arg);
4969 if (ArgResult.isInvalid())
4971 Arg = ArgResult.get();
4973 QualType ArgType = Arg->getType();
4975 // C++ [temp.arg.nontype]p1:
4976 // A template-argument for a non-type, non-template
4977 // template-parameter shall be one of:
4979 // -- an integral constant-expression of integral or enumeration
4981 // -- the name of a non-type template-parameter; or
4982 SourceLocation NonConstantLoc;
4984 if (!ArgType->isIntegralOrEnumerationType()) {
4985 Diag(Arg->getLocStart(),
4986 diag::err_template_arg_not_integral_or_enumeral)
4987 << ArgType << Arg->getSourceRange();
4988 Diag(Param->getLocation(), diag::note_template_param_here);
4990 } else if (!Arg->isValueDependent()) {
4991 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
4995 TmplArgICEDiagnoser(QualType T) : T(T) { }
4997 void diagnoseNotICE(Sema &S, SourceLocation Loc,
4998 SourceRange SR) override {
4999 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
5001 } Diagnoser(ArgType);
5003 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
5009 // From here on out, all we care about is the unqualified form
5010 // of the argument type.
5011 ArgType = ArgType.getUnqualifiedType();
5013 // Try to convert the argument to the parameter's type.
5014 if (Context.hasSameType(ParamType, ArgType)) {
5015 // Okay: no conversion necessary
5016 } else if (ParamType->isBooleanType()) {
5017 // This is an integral-to-boolean conversion.
5018 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
5019 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
5020 !ParamType->isEnumeralType()) {
5021 // This is an integral promotion or conversion.
5022 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
5024 // We can't perform this conversion.
5025 Diag(Arg->getLocStart(),
5026 diag::err_template_arg_not_convertible)
5027 << Arg->getType() << ParamType << Arg->getSourceRange();
5028 Diag(Param->getLocation(), diag::note_template_param_here);
5032 // Add the value of this argument to the list of converted
5033 // arguments. We use the bitwidth and signedness of the template
5035 if (Arg->isValueDependent()) {
5036 // The argument is value-dependent. Create a new
5037 // TemplateArgument with the converted expression.
5038 Converted = TemplateArgument(Arg);
5042 QualType IntegerType = Context.getCanonicalType(ParamType);
5043 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
5044 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
5046 if (ParamType->isBooleanType()) {
5047 // Value must be zero or one.
5049 unsigned AllowedBits = Context.getTypeSize(IntegerType);
5050 if (Value.getBitWidth() != AllowedBits)
5051 Value = Value.extOrTrunc(AllowedBits);
5052 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
5054 llvm::APSInt OldValue = Value;
5056 // Coerce the template argument's value to the value it will have
5057 // based on the template parameter's type.
5058 unsigned AllowedBits = Context.getTypeSize(IntegerType);
5059 if (Value.getBitWidth() != AllowedBits)
5060 Value = Value.extOrTrunc(AllowedBits);
5061 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
5063 // Complain if an unsigned parameter received a negative value.
5064 if (IntegerType->isUnsignedIntegerOrEnumerationType()
5065 && (OldValue.isSigned() && OldValue.isNegative())) {
5066 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
5067 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5068 << Arg->getSourceRange();
5069 Diag(Param->getLocation(), diag::note_template_param_here);
5072 // Complain if we overflowed the template parameter's type.
5073 unsigned RequiredBits;
5074 if (IntegerType->isUnsignedIntegerOrEnumerationType())
5075 RequiredBits = OldValue.getActiveBits();
5076 else if (OldValue.isUnsigned())
5077 RequiredBits = OldValue.getActiveBits() + 1;
5079 RequiredBits = OldValue.getMinSignedBits();
5080 if (RequiredBits > AllowedBits) {
5081 Diag(Arg->getLocStart(),
5082 diag::warn_template_arg_too_large)
5083 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5084 << Arg->getSourceRange();
5085 Diag(Param->getLocation(), diag::note_template_param_here);
5089 Converted = TemplateArgument(Context, Value,
5090 ParamType->isEnumeralType()
5091 ? Context.getCanonicalType(ParamType)
5096 QualType ArgType = Arg->getType();
5097 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
5099 // Handle pointer-to-function, reference-to-function, and
5100 // pointer-to-member-function all in (roughly) the same way.
5101 if (// -- For a non-type template-parameter of type pointer to
5102 // function, only the function-to-pointer conversion (4.3) is
5103 // applied. If the template-argument represents a set of
5104 // overloaded functions (or a pointer to such), the matching
5105 // function is selected from the set (13.4).
5106 (ParamType->isPointerType() &&
5107 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
5108 // -- For a non-type template-parameter of type reference to
5109 // function, no conversions apply. If the template-argument
5110 // represents a set of overloaded functions, the matching
5111 // function is selected from the set (13.4).
5112 (ParamType->isReferenceType() &&
5113 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
5114 // -- For a non-type template-parameter of type pointer to
5115 // member function, no conversions apply. If the
5116 // template-argument represents a set of overloaded member
5117 // functions, the matching member function is selected from
5119 (ParamType->isMemberPointerType() &&
5120 ParamType->getAs<MemberPointerType>()->getPointeeType()
5121 ->isFunctionType())) {
5123 if (Arg->getType() == Context.OverloadTy) {
5124 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
5127 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
5130 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5131 ArgType = Arg->getType();
5136 if (!ParamType->isMemberPointerType()) {
5137 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5144 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5150 if (ParamType->isPointerType()) {
5151 // -- for a non-type template-parameter of type pointer to
5152 // object, qualification conversions (4.4) and the
5153 // array-to-pointer conversion (4.2) are applied.
5154 // C++0x also allows a value of std::nullptr_t.
5155 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
5156 "Only object pointers allowed here");
5158 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5165 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
5166 // -- For a non-type template-parameter of type reference to
5167 // object, no conversions apply. The type referred to by the
5168 // reference may be more cv-qualified than the (otherwise
5169 // identical) type of the template-argument. The
5170 // template-parameter is bound directly to the
5171 // template-argument, which must be an lvalue.
5172 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
5173 "Only object references allowed here");
5175 if (Arg->getType() == Context.OverloadTy) {
5176 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
5177 ParamRefType->getPointeeType(),
5180 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
5183 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5184 ArgType = Arg->getType();
5189 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5196 // Deal with parameters of type std::nullptr_t.
5197 if (ParamType->isNullPtrType()) {
5198 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5199 Converted = TemplateArgument(Arg);
5203 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
5204 case NPV_NotNullPointer:
5205 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
5206 << Arg->getType() << ParamType;
5207 Diag(Param->getLocation(), diag::note_template_param_here);
5213 case NPV_NullPointer:
5214 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
5215 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
5221 // -- For a non-type template-parameter of type pointer to data
5222 // member, qualification conversions (4.4) are applied.
5223 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
5225 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5231 /// \brief Check a template argument against its corresponding
5232 /// template template parameter.
5234 /// This routine implements the semantics of C++ [temp.arg.template].
5235 /// It returns true if an error occurred, and false otherwise.
5236 bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
5237 TemplateArgumentLoc &Arg,
5238 unsigned ArgumentPackIndex) {
5239 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
5240 TemplateDecl *Template = Name.getAsTemplateDecl();
5242 // Any dependent template name is fine.
5243 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
5247 // C++0x [temp.arg.template]p1:
5248 // A template-argument for a template template-parameter shall be
5249 // the name of a class template or an alias template, expressed as an
5250 // id-expression. When the template-argument names a class template, only
5251 // primary class templates are considered when matching the
5252 // template template argument with the corresponding parameter;
5253 // partial specializations are not considered even if their
5254 // parameter lists match that of the template template parameter.
5256 // Note that we also allow template template parameters here, which
5257 // will happen when we are dealing with, e.g., class template
5258 // partial specializations.
5259 if (!isa<ClassTemplateDecl>(Template) &&
5260 !isa<TemplateTemplateParmDecl>(Template) &&
5261 !isa<TypeAliasTemplateDecl>(Template)) {
5262 assert(isa<FunctionTemplateDecl>(Template) &&
5263 "Only function templates are possible here");
5264 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
5265 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
5269 TemplateParameterList *Params = Param->getTemplateParameters();
5270 if (Param->isExpandedParameterPack())
5271 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
5273 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
5276 TPL_TemplateTemplateArgumentMatch,
5280 /// \brief Given a non-type template argument that refers to a
5281 /// declaration and the type of its corresponding non-type template
5282 /// parameter, produce an expression that properly refers to that
5285 Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5287 SourceLocation Loc) {
5288 // C++ [temp.param]p8:
5290 // A non-type template-parameter of type "array of T" or
5291 // "function returning T" is adjusted to be of type "pointer to
5292 // T" or "pointer to function returning T", respectively.
5293 if (ParamType->isArrayType())
5294 ParamType = Context.getArrayDecayedType(ParamType);
5295 else if (ParamType->isFunctionType())
5296 ParamType = Context.getPointerType(ParamType);
5298 // For a NULL non-type template argument, return nullptr casted to the
5299 // parameter's type.
5300 if (Arg.getKind() == TemplateArgument::NullPtr) {
5301 return ImpCastExprToType(
5302 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
5304 ParamType->getAs<MemberPointerType>()
5305 ? CK_NullToMemberPointer
5306 : CK_NullToPointer);
5308 assert(Arg.getKind() == TemplateArgument::Declaration &&
5309 "Only declaration template arguments permitted here");
5311 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
5313 if (VD->getDeclContext()->isRecord() &&
5314 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
5315 isa<IndirectFieldDecl>(VD))) {
5316 // If the value is a class member, we might have a pointer-to-member.
5317 // Determine whether the non-type template template parameter is of
5318 // pointer-to-member type. If so, we need to build an appropriate
5319 // expression for a pointer-to-member, since a "normal" DeclRefExpr
5320 // would refer to the member itself.
5321 if (ParamType->isMemberPointerType()) {
5323 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
5324 NestedNameSpecifier *Qualifier
5325 = NestedNameSpecifier::Create(Context, nullptr, false,
5326 ClassType.getTypePtr());
5328 SS.MakeTrivial(Context, Qualifier, Loc);
5330 // The actual value-ness of this is unimportant, but for
5331 // internal consistency's sake, references to instance methods
5333 ExprValueKind VK = VK_LValue;
5334 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
5337 ExprResult RefExpr = BuildDeclRefExpr(VD,
5338 VD->getType().getNonReferenceType(),
5342 if (RefExpr.isInvalid())
5345 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
5347 // We might need to perform a trailing qualification conversion, since
5348 // the element type on the parameter could be more qualified than the
5349 // element type in the expression we constructed.
5350 bool ObjCLifetimeConversion;
5351 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
5352 ParamType.getUnqualifiedType(), false,
5353 ObjCLifetimeConversion))
5354 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
5356 assert(!RefExpr.isInvalid() &&
5357 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
5358 ParamType.getUnqualifiedType()));
5363 QualType T = VD->getType().getNonReferenceType();
5365 if (ParamType->isPointerType()) {
5366 // When the non-type template parameter is a pointer, take the
5367 // address of the declaration.
5368 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
5369 if (RefExpr.isInvalid())
5372 if (T->isFunctionType() || T->isArrayType()) {
5373 // Decay functions and arrays.
5374 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
5375 if (RefExpr.isInvalid())
5381 // Take the address of everything else
5382 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
5385 ExprValueKind VK = VK_RValue;
5387 // If the non-type template parameter has reference type, qualify the
5388 // resulting declaration reference with the extra qualifiers on the
5389 // type that the reference refers to.
5390 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
5392 T = Context.getQualifiedType(T,
5393 TargetRef->getPointeeType().getQualifiers());
5394 } else if (isa<FunctionDecl>(VD)) {
5395 // References to functions are always lvalues.
5399 return BuildDeclRefExpr(VD, T, VK, Loc);
5402 /// \brief Construct a new expression that refers to the given
5403 /// integral template argument with the given source-location
5406 /// This routine takes care of the mapping from an integral template
5407 /// argument (which may have any integral type) to the appropriate
5410 Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5411 SourceLocation Loc) {
5412 assert(Arg.getKind() == TemplateArgument::Integral &&
5413 "Operation is only valid for integral template arguments");
5414 QualType OrigT = Arg.getIntegralType();
5416 // If this is an enum type that we're instantiating, we need to use an integer
5417 // type the same size as the enumerator. We don't want to build an
5418 // IntegerLiteral with enum type. The integer type of an enum type can be of
5419 // any integral type with C++11 enum classes, make sure we create the right
5420 // type of literal for it.
5422 if (const EnumType *ET = OrigT->getAs<EnumType>())
5423 T = ET->getDecl()->getIntegerType();
5426 if (T->isAnyCharacterType()) {
5427 CharacterLiteral::CharacterKind Kind;
5428 if (T->isWideCharType())
5429 Kind = CharacterLiteral::Wide;
5430 else if (T->isChar16Type())
5431 Kind = CharacterLiteral::UTF16;
5432 else if (T->isChar32Type())
5433 Kind = CharacterLiteral::UTF32;
5435 Kind = CharacterLiteral::Ascii;
5437 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
5439 } else if (T->isBooleanType()) {
5440 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
5442 } else if (T->isNullPtrType()) {
5443 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
5445 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
5448 if (OrigT->isEnumeralType()) {
5449 // FIXME: This is a hack. We need a better way to handle substituted
5450 // non-type template parameters.
5451 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
5453 Context.getTrivialTypeSourceInfo(OrigT, Loc),
5460 /// \brief Match two template parameters within template parameter lists.
5461 static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
5463 Sema::TemplateParameterListEqualKind Kind,
5464 SourceLocation TemplateArgLoc) {
5465 // Check the actual kind (type, non-type, template).
5466 if (Old->getKind() != New->getKind()) {
5468 unsigned NextDiag = diag::err_template_param_different_kind;
5469 if (TemplateArgLoc.isValid()) {
5470 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5471 NextDiag = diag::note_template_param_different_kind;
5473 S.Diag(New->getLocation(), NextDiag)
5474 << (Kind != Sema::TPL_TemplateMatch);
5475 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
5476 << (Kind != Sema::TPL_TemplateMatch);
5482 // Check that both are parameter packs are neither are parameter packs.
5483 // However, if we are matching a template template argument to a
5484 // template template parameter, the template template parameter can have
5485 // a parameter pack where the template template argument does not.
5486 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
5487 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5488 Old->isTemplateParameterPack())) {
5490 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
5491 if (TemplateArgLoc.isValid()) {
5492 S.Diag(TemplateArgLoc,
5493 diag::err_template_arg_template_params_mismatch);
5494 NextDiag = diag::note_template_parameter_pack_non_pack;
5497 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
5498 : isa<NonTypeTemplateParmDecl>(New)? 1
5500 S.Diag(New->getLocation(), NextDiag)
5501 << ParamKind << New->isParameterPack();
5502 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
5503 << ParamKind << Old->isParameterPack();
5509 // For non-type template parameters, check the type of the parameter.
5510 if (NonTypeTemplateParmDecl *OldNTTP
5511 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
5512 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
5514 // If we are matching a template template argument to a template
5515 // template parameter and one of the non-type template parameter types
5516 // is dependent, then we must wait until template instantiation time
5517 // to actually compare the arguments.
5518 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5519 (OldNTTP->getType()->isDependentType() ||
5520 NewNTTP->getType()->isDependentType()))
5523 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
5525 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
5526 if (TemplateArgLoc.isValid()) {
5527 S.Diag(TemplateArgLoc,
5528 diag::err_template_arg_template_params_mismatch);
5529 NextDiag = diag::note_template_nontype_parm_different_type;
5531 S.Diag(NewNTTP->getLocation(), NextDiag)
5532 << NewNTTP->getType()
5533 << (Kind != Sema::TPL_TemplateMatch);
5534 S.Diag(OldNTTP->getLocation(),
5535 diag::note_template_nontype_parm_prev_declaration)
5536 << OldNTTP->getType();
5545 // For template template parameters, check the template parameter types.
5546 // The template parameter lists of template template
5547 // parameters must agree.
5548 if (TemplateTemplateParmDecl *OldTTP
5549 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
5550 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
5551 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
5552 OldTTP->getTemplateParameters(),
5554 (Kind == Sema::TPL_TemplateMatch
5555 ? Sema::TPL_TemplateTemplateParmMatch
5563 /// \brief Diagnose a known arity mismatch when comparing template argument
5566 void DiagnoseTemplateParameterListArityMismatch(Sema &S,
5567 TemplateParameterList *New,
5568 TemplateParameterList *Old,
5569 Sema::TemplateParameterListEqualKind Kind,
5570 SourceLocation TemplateArgLoc) {
5571 unsigned NextDiag = diag::err_template_param_list_different_arity;
5572 if (TemplateArgLoc.isValid()) {
5573 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5574 NextDiag = diag::note_template_param_list_different_arity;
5576 S.Diag(New->getTemplateLoc(), NextDiag)
5577 << (New->size() > Old->size())
5578 << (Kind != Sema::TPL_TemplateMatch)
5579 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
5580 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
5581 << (Kind != Sema::TPL_TemplateMatch)
5582 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
5585 /// \brief Determine whether the given template parameter lists are
5588 /// \param New The new template parameter list, typically written in the
5589 /// source code as part of a new template declaration.
5591 /// \param Old The old template parameter list, typically found via
5592 /// name lookup of the template declared with this template parameter
5595 /// \param Complain If true, this routine will produce a diagnostic if
5596 /// the template parameter lists are not equivalent.
5598 /// \param Kind describes how we are to match the template parameter lists.
5600 /// \param TemplateArgLoc If this source location is valid, then we
5601 /// are actually checking the template parameter list of a template
5602 /// argument (New) against the template parameter list of its
5603 /// corresponding template template parameter (Old). We produce
5604 /// slightly different diagnostics in this scenario.
5606 /// \returns True if the template parameter lists are equal, false
5609 Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
5610 TemplateParameterList *Old,
5612 TemplateParameterListEqualKind Kind,
5613 SourceLocation TemplateArgLoc) {
5614 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
5616 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5622 // C++0x [temp.arg.template]p3:
5623 // A template-argument matches a template template-parameter (call it P)
5624 // when each of the template parameters in the template-parameter-list of
5625 // the template-argument's corresponding class template or alias template
5626 // (call it A) matches the corresponding template parameter in the
5627 // template-parameter-list of P. [...]
5628 TemplateParameterList::iterator NewParm = New->begin();
5629 TemplateParameterList::iterator NewParmEnd = New->end();
5630 for (TemplateParameterList::iterator OldParm = Old->begin(),
5631 OldParmEnd = Old->end();
5632 OldParm != OldParmEnd; ++OldParm) {
5633 if (Kind != TPL_TemplateTemplateArgumentMatch ||
5634 !(*OldParm)->isTemplateParameterPack()) {
5635 if (NewParm == NewParmEnd) {
5637 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5643 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5644 Kind, TemplateArgLoc))
5651 // C++0x [temp.arg.template]p3:
5652 // [...] When P's template- parameter-list contains a template parameter
5653 // pack (14.5.3), the template parameter pack will match zero or more
5654 // template parameters or template parameter packs in the
5655 // template-parameter-list of A with the same type and form as the
5656 // template parameter pack in P (ignoring whether those template
5657 // parameters are template parameter packs).
5658 for (; NewParm != NewParmEnd; ++NewParm) {
5659 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5660 Kind, TemplateArgLoc))
5665 // Make sure we exhausted all of the arguments.
5666 if (NewParm != NewParmEnd) {
5668 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5677 /// \brief Check whether a template can be declared within this scope.
5679 /// If the template declaration is valid in this scope, returns
5680 /// false. Otherwise, issues a diagnostic and returns true.
5682 Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
5686 // Find the nearest enclosing declaration scope.
5687 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5688 (S->getFlags() & Scope::TemplateParamScope) != 0)
5692 // A template [...] shall not have C linkage.
5693 DeclContext *Ctx = S->getEntity();
5694 if (Ctx && Ctx->isExternCContext())
5695 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
5696 << TemplateParams->getSourceRange();
5698 while (Ctx && isa<LinkageSpecDecl>(Ctx))
5699 Ctx = Ctx->getParent();
5702 // A template-declaration can appear only as a namespace scope or
5703 // class scope declaration.
5705 if (Ctx->isFileContext())
5707 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
5708 // C++ [temp.mem]p2:
5709 // A local class shall not have member templates.
5710 if (RD->isLocalClass())
5711 return Diag(TemplateParams->getTemplateLoc(),
5712 diag::err_template_inside_local_class)
5713 << TemplateParams->getSourceRange();
5719 return Diag(TemplateParams->getTemplateLoc(),
5720 diag::err_template_outside_namespace_or_class_scope)
5721 << TemplateParams->getSourceRange();
5724 /// \brief Determine what kind of template specialization the given declaration
5726 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
5728 return TSK_Undeclared;
5730 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
5731 return Record->getTemplateSpecializationKind();
5732 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
5733 return Function->getTemplateSpecializationKind();
5734 if (VarDecl *Var = dyn_cast<VarDecl>(D))
5735 return Var->getTemplateSpecializationKind();
5737 return TSK_Undeclared;
5740 /// \brief Check whether a specialization is well-formed in the current
5743 /// This routine determines whether a template specialization can be declared
5744 /// in the current context (C++ [temp.expl.spec]p2).
5746 /// \param S the semantic analysis object for which this check is being
5749 /// \param Specialized the entity being specialized or instantiated, which
5750 /// may be a kind of template (class template, function template, etc.) or
5751 /// a member of a class template (member function, static data member,
5754 /// \param PrevDecl the previous declaration of this entity, if any.
5756 /// \param Loc the location of the explicit specialization or instantiation of
5759 /// \param IsPartialSpecialization whether this is a partial specialization of
5760 /// a class template.
5762 /// \returns true if there was an error that we cannot recover from, false
5764 static bool CheckTemplateSpecializationScope(Sema &S,
5765 NamedDecl *Specialized,
5766 NamedDecl *PrevDecl,
5768 bool IsPartialSpecialization) {
5769 // Keep these "kind" numbers in sync with the %select statements in the
5770 // various diagnostics emitted by this routine.
5772 if (isa<ClassTemplateDecl>(Specialized))
5773 EntityKind = IsPartialSpecialization? 1 : 0;
5774 else if (isa<VarTemplateDecl>(Specialized))
5775 EntityKind = IsPartialSpecialization ? 3 : 2;
5776 else if (isa<FunctionTemplateDecl>(Specialized))
5778 else if (isa<CXXMethodDecl>(Specialized))
5780 else if (isa<VarDecl>(Specialized))
5782 else if (isa<RecordDecl>(Specialized))
5784 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
5787 S.Diag(Loc, diag::err_template_spec_unknown_kind)
5788 << S.getLangOpts().CPlusPlus11;
5789 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5793 // C++ [temp.expl.spec]p2:
5794 // An explicit specialization shall be declared in the namespace
5795 // of which the template is a member, or, for member templates, in
5796 // the namespace of which the enclosing class or enclosing class
5797 // template is a member. An explicit specialization of a member
5798 // function, member class or static data member of a class
5799 // template shall be declared in the namespace of which the class
5800 // template is a member. Such a declaration may also be a
5801 // definition. If the declaration is not a definition, the
5802 // specialization may be defined later in the name- space in which
5803 // the explicit specialization was declared, or in a namespace
5804 // that encloses the one in which the explicit specialization was
5806 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
5807 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
5812 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
5813 if (S.getLangOpts().MicrosoftExt) {
5814 // Do not warn for class scope explicit specialization during
5815 // instantiation, warning was already emitted during pattern
5816 // semantic analysis.
5817 if (!S.ActiveTemplateInstantiations.size())
5818 S.Diag(Loc, diag::ext_function_specialization_in_class)
5821 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5827 if (S.CurContext->isRecord() &&
5828 !S.CurContext->Equals(Specialized->getDeclContext())) {
5829 // Make sure that we're specializing in the right record context.
5830 // Otherwise, things can go horribly wrong.
5831 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5836 // C++ [temp.class.spec]p6:
5837 // A class template partial specialization may be declared or redeclared
5838 // in any namespace scope in which its definition may be defined (14.5.1
5840 DeclContext *SpecializedContext
5841 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
5842 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
5844 // Make sure that this redeclaration (or definition) occurs in an enclosing
5846 // Note that HandleDeclarator() performs this check for explicit
5847 // specializations of function templates, static data members, and member
5848 // functions, so we skip the check here for those kinds of entities.
5849 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
5850 // Should we refactor that check, so that it occurs later?
5851 if (!DC->Encloses(SpecializedContext) &&
5852 !(isa<FunctionTemplateDecl>(Specialized) ||
5853 isa<FunctionDecl>(Specialized) ||
5854 isa<VarTemplateDecl>(Specialized) ||
5855 isa<VarDecl>(Specialized))) {
5856 if (isa<TranslationUnitDecl>(SpecializedContext))
5857 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
5858 << EntityKind << Specialized;
5859 else if (isa<NamespaceDecl>(SpecializedContext)) {
5860 int Diag = diag::err_template_spec_redecl_out_of_scope;
5861 if (S.getLangOpts().MicrosoftExt)
5862 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
5863 S.Diag(Loc, Diag) << EntityKind << Specialized
5864 << cast<NamedDecl>(SpecializedContext);
5866 llvm_unreachable("unexpected namespace context for specialization");
5868 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5869 } else if ((!PrevDecl ||
5870 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
5871 getTemplateSpecializationKind(PrevDecl) ==
5872 TSK_ImplicitInstantiation)) {
5873 // C++ [temp.exp.spec]p2:
5874 // An explicit specialization shall be declared in the namespace of which
5875 // the template is a member, or, for member templates, in the namespace
5876 // of which the enclosing class or enclosing class template is a member.
5877 // An explicit specialization of a member function, member class or
5878 // static data member of a class template shall be declared in the
5879 // namespace of which the class template is a member.
5881 // C++11 [temp.expl.spec]p2:
5882 // An explicit specialization shall be declared in a namespace enclosing
5883 // the specialized template.
5884 // C++11 [temp.explicit]p3:
5885 // An explicit instantiation shall appear in an enclosing namespace of its
5887 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
5888 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
5889 if (isa<TranslationUnitDecl>(SpecializedContext)) {
5890 assert(!IsCPlusPlus11Extension &&
5891 "DC encloses TU but isn't in enclosing namespace set");
5892 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
5893 << EntityKind << Specialized;
5894 } else if (isa<NamespaceDecl>(SpecializedContext)) {
5896 if (!IsCPlusPlus11Extension)
5897 Diag = diag::err_template_spec_decl_out_of_scope;
5898 else if (!S.getLangOpts().CPlusPlus11)
5899 Diag = diag::ext_template_spec_decl_out_of_scope;
5901 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
5903 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
5906 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5913 static SourceRange findTemplateParameter(unsigned Depth, Expr *E) {
5914 if (!E->isInstantiationDependent())
5915 return SourceLocation();
5916 DependencyChecker Checker(Depth);
5917 Checker.TraverseStmt(E);
5918 if (Checker.Match && Checker.MatchLoc.isInvalid())
5919 return E->getSourceRange();
5920 return Checker.MatchLoc;
5923 static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
5924 if (!TL.getType()->isDependentType())
5925 return SourceLocation();
5926 DependencyChecker Checker(Depth);
5927 Checker.TraverseTypeLoc(TL);
5928 if (Checker.Match && Checker.MatchLoc.isInvalid())
5929 return TL.getSourceRange();
5930 return Checker.MatchLoc;
5933 /// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
5934 /// that checks non-type template partial specialization arguments.
5935 static bool CheckNonTypeTemplatePartialSpecializationArgs(
5936 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
5937 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
5938 for (unsigned I = 0; I != NumArgs; ++I) {
5939 if (Args[I].getKind() == TemplateArgument::Pack) {
5940 if (CheckNonTypeTemplatePartialSpecializationArgs(
5941 S, TemplateNameLoc, Param, Args[I].pack_begin(),
5942 Args[I].pack_size(), IsDefaultArgument))
5948 if (Args[I].getKind() != TemplateArgument::Expression)
5951 Expr *ArgExpr = Args[I].getAsExpr();
5953 // We can have a pack expansion of any of the bullets below.
5954 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
5955 ArgExpr = Expansion->getPattern();
5957 // Strip off any implicit casts we added as part of type checking.
5958 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
5959 ArgExpr = ICE->getSubExpr();
5961 // C++ [temp.class.spec]p8:
5962 // A non-type argument is non-specialized if it is the name of a
5963 // non-type parameter. All other non-type arguments are
5966 // Below, we check the two conditions that only apply to
5967 // specialized non-type arguments, so skip any non-specialized
5969 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
5970 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
5973 // C++ [temp.class.spec]p9:
5974 // Within the argument list of a class template partial
5975 // specialization, the following restrictions apply:
5976 // -- A partially specialized non-type argument expression
5977 // shall not involve a template parameter of the partial
5978 // specialization except when the argument expression is a
5979 // simple identifier.
5980 SourceRange ParamUseRange =
5981 findTemplateParameter(Param->getDepth(), ArgExpr);
5982 if (ParamUseRange.isValid()) {
5983 if (IsDefaultArgument) {
5984 S.Diag(TemplateNameLoc,
5985 diag::err_dependent_non_type_arg_in_partial_spec);
5986 S.Diag(ParamUseRange.getBegin(),
5987 diag::note_dependent_non_type_default_arg_in_partial_spec)
5990 S.Diag(ParamUseRange.getBegin(),
5991 diag::err_dependent_non_type_arg_in_partial_spec)
5997 // -- The type of a template parameter corresponding to a
5998 // specialized non-type argument shall not be dependent on a
5999 // parameter of the specialization.
6001 // FIXME: We need to delay this check until instantiation in some cases:
6003 // template<template<typename> class X> struct A {
6004 // template<typename T, X<T> N> struct B;
6005 // template<typename T> struct B<T, 0>;
6007 // template<typename> using X = int;
6008 // A<X>::B<int, 0> b;
6009 ParamUseRange = findTemplateParameter(
6010 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
6011 if (ParamUseRange.isValid()) {
6012 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
6013 diag::err_dependent_typed_non_type_arg_in_partial_spec)
6014 << Param->getType() << ParamUseRange;
6015 S.Diag(Param->getLocation(), diag::note_template_param_here)
6016 << (IsDefaultArgument ? ParamUseRange : SourceRange());
6024 /// \brief Check the non-type template arguments of a class template
6025 /// partial specialization according to C++ [temp.class.spec]p9.
6027 /// \param TemplateNameLoc the location of the template name.
6028 /// \param TemplateParams the template parameters of the primary class
6030 /// \param NumExplicit the number of explicitly-specified template arguments.
6031 /// \param TemplateArgs the template arguments of the class template
6032 /// partial specialization.
6034 /// \returns \c true if there was an error, \c false otherwise.
6035 static bool CheckTemplatePartialSpecializationArgs(
6036 Sema &S, SourceLocation TemplateNameLoc,
6037 TemplateParameterList *TemplateParams, unsigned NumExplicit,
6038 SmallVectorImpl<TemplateArgument> &TemplateArgs) {
6039 const TemplateArgument *ArgList = TemplateArgs.data();
6041 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6042 NonTypeTemplateParmDecl *Param
6043 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
6047 if (CheckNonTypeTemplatePartialSpecializationArgs(
6048 S, TemplateNameLoc, Param, &ArgList[I], 1, I >= NumExplicit))
6056 Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
6058 SourceLocation KWLoc,
6059 SourceLocation ModulePrivateLoc,
6060 TemplateIdAnnotation &TemplateId,
6061 AttributeList *Attr,
6062 MultiTemplateParamsArg
6063 TemplateParameterLists,
6064 SkipBodyInfo *SkipBody) {
6065 assert(TUK != TUK_Reference && "References are not specializations");
6067 CXXScopeSpec &SS = TemplateId.SS;
6069 // NOTE: KWLoc is the location of the tag keyword. This will instead
6070 // store the location of the outermost template keyword in the declaration.
6071 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
6072 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
6073 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
6074 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
6075 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
6077 // Find the class template we're specializing
6078 TemplateName Name = TemplateId.Template.get();
6079 ClassTemplateDecl *ClassTemplate
6080 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
6082 if (!ClassTemplate) {
6083 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
6084 << (Name.getAsTemplateDecl() &&
6085 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
6089 bool isExplicitSpecialization = false;
6090 bool isPartialSpecialization = false;
6092 // Check the validity of the template headers that introduce this
6094 // FIXME: We probably shouldn't complain about these headers for
6095 // friend declarations.
6096 bool Invalid = false;
6097 TemplateParameterList *TemplateParams =
6098 MatchTemplateParametersToScopeSpecifier(
6099 KWLoc, TemplateNameLoc, SS, &TemplateId,
6100 TemplateParameterLists, TUK == TUK_Friend, isExplicitSpecialization,
6105 if (TemplateParams && TemplateParams->size() > 0) {
6106 isPartialSpecialization = true;
6108 if (TUK == TUK_Friend) {
6109 Diag(KWLoc, diag::err_partial_specialization_friend)
6110 << SourceRange(LAngleLoc, RAngleLoc);
6114 // C++ [temp.class.spec]p10:
6115 // The template parameter list of a specialization shall not
6116 // contain default template argument values.
6117 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6118 Decl *Param = TemplateParams->getParam(I);
6119 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6120 if (TTP->hasDefaultArgument()) {
6121 Diag(TTP->getDefaultArgumentLoc(),
6122 diag::err_default_arg_in_partial_spec);
6123 TTP->removeDefaultArgument();
6125 } else if (NonTypeTemplateParmDecl *NTTP
6126 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6127 if (Expr *DefArg = NTTP->getDefaultArgument()) {
6128 Diag(NTTP->getDefaultArgumentLoc(),
6129 diag::err_default_arg_in_partial_spec)
6130 << DefArg->getSourceRange();
6131 NTTP->removeDefaultArgument();
6134 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
6135 if (TTP->hasDefaultArgument()) {
6136 Diag(TTP->getDefaultArgument().getLocation(),
6137 diag::err_default_arg_in_partial_spec)
6138 << TTP->getDefaultArgument().getSourceRange();
6139 TTP->removeDefaultArgument();
6143 } else if (TemplateParams) {
6144 if (TUK == TUK_Friend)
6145 Diag(KWLoc, diag::err_template_spec_friend)
6146 << FixItHint::CreateRemoval(
6147 SourceRange(TemplateParams->getTemplateLoc(),
6148 TemplateParams->getRAngleLoc()))
6149 << SourceRange(LAngleLoc, RAngleLoc);
6151 isExplicitSpecialization = true;
6153 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
6156 // Check that the specialization uses the same tag kind as the
6157 // original template.
6158 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6159 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
6160 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
6161 Kind, TUK == TUK_Definition, KWLoc,
6162 *ClassTemplate->getIdentifier())) {
6163 Diag(KWLoc, diag::err_use_with_wrong_tag)
6165 << FixItHint::CreateReplacement(KWLoc,
6166 ClassTemplate->getTemplatedDecl()->getKindName());
6167 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
6168 diag::note_previous_use);
6169 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
6172 // Translate the parser's template argument list in our AST format.
6173 TemplateArgumentListInfo TemplateArgs =
6174 makeTemplateArgumentListInfo(*this, TemplateId);
6176 // Check for unexpanded parameter packs in any of the template arguments.
6177 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
6178 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
6179 UPPC_PartialSpecialization))
6182 // Check that the template argument list is well-formed for this
6184 SmallVector<TemplateArgument, 4> Converted;
6185 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
6186 TemplateArgs, false, Converted))
6189 // Find the class template (partial) specialization declaration that
6190 // corresponds to these arguments.
6191 if (isPartialSpecialization) {
6192 if (CheckTemplatePartialSpecializationArgs(
6193 *this, TemplateNameLoc, ClassTemplate->getTemplateParameters(),
6194 TemplateArgs.size(), Converted))
6197 bool InstantiationDependent;
6198 if (!Name.isDependent() &&
6199 !TemplateSpecializationType::anyDependentTemplateArguments(
6200 TemplateArgs.getArgumentArray(),
6201 TemplateArgs.size(),
6202 InstantiationDependent)) {
6203 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
6204 << ClassTemplate->getDeclName();
6205 isPartialSpecialization = false;
6209 void *InsertPos = nullptr;
6210 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
6212 if (isPartialSpecialization)
6213 // FIXME: Template parameter list matters, too
6214 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
6216 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
6218 ClassTemplateSpecializationDecl *Specialization = nullptr;
6220 // Check whether we can declare a class template specialization in
6221 // the current scope.
6222 if (TUK != TUK_Friend &&
6223 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
6225 isPartialSpecialization))
6228 // The canonical type
6230 if (isPartialSpecialization) {
6231 // Build the canonical type that describes the converted template
6232 // arguments of the class template partial specialization.
6233 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6234 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
6238 if (Context.hasSameType(CanonType,
6239 ClassTemplate->getInjectedClassNameSpecialization())) {
6240 // C++ [temp.class.spec]p9b3:
6242 // -- The argument list of the specialization shall not be identical
6243 // to the implicit argument list of the primary template.
6244 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
6245 << /*class template*/0 << (TUK == TUK_Definition)
6246 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
6247 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
6248 ClassTemplate->getIdentifier(),
6252 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
6253 /*FriendLoc*/SourceLocation(),
6254 TemplateParameterLists.size() - 1,
6255 TemplateParameterLists.data());
6258 // Create a new class template partial specialization declaration node.
6259 ClassTemplatePartialSpecializationDecl *PrevPartial
6260 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
6261 ClassTemplatePartialSpecializationDecl *Partial
6262 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
6263 ClassTemplate->getDeclContext(),
6264 KWLoc, TemplateNameLoc,
6272 SetNestedNameSpecifier(Partial, SS);
6273 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
6274 Partial->setTemplateParameterListsInfo(Context,
6275 TemplateParameterLists.size() - 1,
6276 TemplateParameterLists.data());
6280 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
6281 Specialization = Partial;
6283 // If we are providing an explicit specialization of a member class
6284 // template specialization, make a note of that.
6285 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
6286 PrevPartial->setMemberSpecialization();
6288 // Check that all of the template parameters of the class template
6289 // partial specialization are deducible from the template
6290 // arguments. If not, this class template partial specialization
6291 // will never be used.
6292 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
6293 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
6294 TemplateParams->getDepth(),
6297 if (!DeducibleParams.all()) {
6298 unsigned NumNonDeducible = DeducibleParams.size()-DeducibleParams.count();
6299 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
6300 << /*class template*/0 << (NumNonDeducible > 1)
6301 << SourceRange(TemplateNameLoc, RAngleLoc);
6302 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
6303 if (!DeducibleParams[I]) {
6304 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
6305 if (Param->getDeclName())
6306 Diag(Param->getLocation(),
6307 diag::note_partial_spec_unused_parameter)
6308 << Param->getDeclName();
6310 Diag(Param->getLocation(),
6311 diag::note_partial_spec_unused_parameter)
6317 // Create a new class template specialization declaration node for
6318 // this explicit specialization or friend declaration.
6320 = ClassTemplateSpecializationDecl::Create(Context, Kind,
6321 ClassTemplate->getDeclContext(),
6322 KWLoc, TemplateNameLoc,
6327 SetNestedNameSpecifier(Specialization, SS);
6328 if (TemplateParameterLists.size() > 0) {
6329 Specialization->setTemplateParameterListsInfo(Context,
6330 TemplateParameterLists.size(),
6331 TemplateParameterLists.data());
6335 ClassTemplate->AddSpecialization(Specialization, InsertPos);
6337 CanonType = Context.getTypeDeclType(Specialization);
6340 // C++ [temp.expl.spec]p6:
6341 // If a template, a member template or the member of a class template is
6342 // explicitly specialized then that specialization shall be declared
6343 // before the first use of that specialization that would cause an implicit
6344 // instantiation to take place, in every translation unit in which such a
6345 // use occurs; no diagnostic is required.
6346 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
6348 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
6349 // Is there any previous explicit specialization declaration?
6350 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6357 SourceRange Range(TemplateNameLoc, RAngleLoc);
6358 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
6359 << Context.getTypeDeclType(Specialization) << Range;
6361 Diag(PrevDecl->getPointOfInstantiation(),
6362 diag::note_instantiation_required_here)
6363 << (PrevDecl->getTemplateSpecializationKind()
6364 != TSK_ImplicitInstantiation);
6369 // If this is not a friend, note that this is an explicit specialization.
6370 if (TUK != TUK_Friend)
6371 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
6373 // Check that this isn't a redefinition of this specialization.
6374 if (TUK == TUK_Definition) {
6375 RecordDecl *Def = Specialization->getDefinition();
6376 NamedDecl *Hidden = nullptr;
6377 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
6378 SkipBody->ShouldSkip = true;
6379 makeMergedDefinitionVisible(Hidden, KWLoc);
6380 // From here on out, treat this as just a redeclaration.
6381 TUK = TUK_Declaration;
6383 SourceRange Range(TemplateNameLoc, RAngleLoc);
6384 Diag(TemplateNameLoc, diag::err_redefinition)
6385 << Context.getTypeDeclType(Specialization) << Range;
6386 Diag(Def->getLocation(), diag::note_previous_definition);
6387 Specialization->setInvalidDecl();
6393 ProcessDeclAttributeList(S, Specialization, Attr);
6395 // Add alignment attributes if necessary; these attributes are checked when
6396 // the ASTContext lays out the structure.
6397 if (TUK == TUK_Definition) {
6398 AddAlignmentAttributesForRecord(Specialization);
6399 AddMsStructLayoutForRecord(Specialization);
6402 if (ModulePrivateLoc.isValid())
6403 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
6404 << (isPartialSpecialization? 1 : 0)
6405 << FixItHint::CreateRemoval(ModulePrivateLoc);
6407 // Build the fully-sugared type for this class template
6408 // specialization as the user wrote in the specialization
6409 // itself. This means that we'll pretty-print the type retrieved
6410 // from the specialization's declaration the way that the user
6411 // actually wrote the specialization, rather than formatting the
6412 // name based on the "canonical" representation used to store the
6413 // template arguments in the specialization.
6414 TypeSourceInfo *WrittenTy
6415 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
6416 TemplateArgs, CanonType);
6417 if (TUK != TUK_Friend) {
6418 Specialization->setTypeAsWritten(WrittenTy);
6419 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
6422 // C++ [temp.expl.spec]p9:
6423 // A template explicit specialization is in the scope of the
6424 // namespace in which the template was defined.
6426 // We actually implement this paragraph where we set the semantic
6427 // context (in the creation of the ClassTemplateSpecializationDecl),
6428 // but we also maintain the lexical context where the actual
6429 // definition occurs.
6430 Specialization->setLexicalDeclContext(CurContext);
6432 // We may be starting the definition of this specialization.
6433 if (TUK == TUK_Definition)
6434 Specialization->startDefinition();
6436 if (TUK == TUK_Friend) {
6437 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
6441 Friend->setAccess(AS_public);
6442 CurContext->addDecl(Friend);
6444 // Add the specialization into its lexical context, so that it can
6445 // be seen when iterating through the list of declarations in that
6446 // context. However, specializations are not found by name lookup.
6447 CurContext->addDecl(Specialization);
6449 return Specialization;
6452 Decl *Sema::ActOnTemplateDeclarator(Scope *S,
6453 MultiTemplateParamsArg TemplateParameterLists,
6455 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
6456 ActOnDocumentableDecl(NewDecl);
6460 Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
6461 MultiTemplateParamsArg TemplateParameterLists,
6463 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
6464 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6466 if (FTI.hasPrototype) {
6467 // FIXME: Diagnose arguments without names in C.
6470 Scope *ParentScope = FnBodyScope->getParent();
6472 D.setFunctionDefinitionKind(FDK_Definition);
6473 Decl *DP = HandleDeclarator(ParentScope, D,
6474 TemplateParameterLists);
6475 return ActOnStartOfFunctionDef(FnBodyScope, DP);
6478 /// \brief Strips various properties off an implicit instantiation
6479 /// that has just been explicitly specialized.
6480 static void StripImplicitInstantiation(NamedDecl *D) {
6481 D->dropAttr<DLLImportAttr>();
6482 D->dropAttr<DLLExportAttr>();
6484 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
6485 FD->setInlineSpecified(false);
6488 /// \brief Compute the diagnostic location for an explicit instantiation
6489 // declaration or definition.
6490 static SourceLocation DiagLocForExplicitInstantiation(
6491 NamedDecl* D, SourceLocation PointOfInstantiation) {
6492 // Explicit instantiations following a specialization have no effect and
6493 // hence no PointOfInstantiation. In that case, walk decl backwards
6494 // until a valid name loc is found.
6495 SourceLocation PrevDiagLoc = PointOfInstantiation;
6496 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
6497 Prev = Prev->getPreviousDecl()) {
6498 PrevDiagLoc = Prev->getLocation();
6500 assert(PrevDiagLoc.isValid() &&
6501 "Explicit instantiation without point of instantiation?");
6505 /// \brief Diagnose cases where we have an explicit template specialization
6506 /// before/after an explicit template instantiation, producing diagnostics
6507 /// for those cases where they are required and determining whether the
6508 /// new specialization/instantiation will have any effect.
6510 /// \param NewLoc the location of the new explicit specialization or
6513 /// \param NewTSK the kind of the new explicit specialization or instantiation.
6515 /// \param PrevDecl the previous declaration of the entity.
6517 /// \param PrevTSK the kind of the old explicit specialization or instantiatin.
6519 /// \param PrevPointOfInstantiation if valid, indicates where the previus
6520 /// declaration was instantiated (either implicitly or explicitly).
6522 /// \param HasNoEffect will be set to true to indicate that the new
6523 /// specialization or instantiation has no effect and should be ignored.
6525 /// \returns true if there was an error that should prevent the introduction of
6526 /// the new declaration into the AST, false otherwise.
6528 Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6529 TemplateSpecializationKind NewTSK,
6530 NamedDecl *PrevDecl,
6531 TemplateSpecializationKind PrevTSK,
6532 SourceLocation PrevPointOfInstantiation,
6533 bool &HasNoEffect) {
6534 HasNoEffect = false;
6537 case TSK_Undeclared:
6538 case TSK_ImplicitInstantiation:
6540 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
6541 "previous declaration must be implicit!");
6544 case TSK_ExplicitSpecialization:
6546 case TSK_Undeclared:
6547 case TSK_ExplicitSpecialization:
6548 // Okay, we're just specializing something that is either already
6549 // explicitly specialized or has merely been mentioned without any
6553 case TSK_ImplicitInstantiation:
6554 if (PrevPointOfInstantiation.isInvalid()) {
6555 // The declaration itself has not actually been instantiated, so it is
6556 // still okay to specialize it.
6557 StripImplicitInstantiation(PrevDecl);
6562 case TSK_ExplicitInstantiationDeclaration:
6563 case TSK_ExplicitInstantiationDefinition:
6564 assert((PrevTSK == TSK_ImplicitInstantiation ||
6565 PrevPointOfInstantiation.isValid()) &&
6566 "Explicit instantiation without point of instantiation?");
6568 // C++ [temp.expl.spec]p6:
6569 // If a template, a member template or the member of a class template
6570 // is explicitly specialized then that specialization shall be declared
6571 // before the first use of that specialization that would cause an
6572 // implicit instantiation to take place, in every translation unit in
6573 // which such a use occurs; no diagnostic is required.
6574 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
6575 // Is there any previous explicit specialization declaration?
6576 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
6580 Diag(NewLoc, diag::err_specialization_after_instantiation)
6582 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
6583 << (PrevTSK != TSK_ImplicitInstantiation);
6588 case TSK_ExplicitInstantiationDeclaration:
6590 case TSK_ExplicitInstantiationDeclaration:
6591 // This explicit instantiation declaration is redundant (that's okay).
6595 case TSK_Undeclared:
6596 case TSK_ImplicitInstantiation:
6597 // We're explicitly instantiating something that may have already been
6598 // implicitly instantiated; that's fine.
6601 case TSK_ExplicitSpecialization:
6602 // C++0x [temp.explicit]p4:
6603 // For a given set of template parameters, if an explicit instantiation
6604 // of a template appears after a declaration of an explicit
6605 // specialization for that template, the explicit instantiation has no
6610 case TSK_ExplicitInstantiationDefinition:
6611 // C++0x [temp.explicit]p10:
6612 // If an entity is the subject of both an explicit instantiation
6613 // declaration and an explicit instantiation definition in the same
6614 // translation unit, the definition shall follow the declaration.
6616 diag::err_explicit_instantiation_declaration_after_definition);
6618 // Explicit instantiations following a specialization have no effect and
6619 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
6620 // until a valid name loc is found.
6621 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6622 diag::note_explicit_instantiation_definition_here);
6627 case TSK_ExplicitInstantiationDefinition:
6629 case TSK_Undeclared:
6630 case TSK_ImplicitInstantiation:
6631 // We're explicitly instantiating something that may have already been
6632 // implicitly instantiated; that's fine.
6635 case TSK_ExplicitSpecialization:
6636 // C++ DR 259, C++0x [temp.explicit]p4:
6637 // For a given set of template parameters, if an explicit
6638 // instantiation of a template appears after a declaration of
6639 // an explicit specialization for that template, the explicit
6640 // instantiation has no effect.
6642 // In C++98/03 mode, we only give an extension warning here, because it
6643 // is not harmful to try to explicitly instantiate something that
6644 // has been explicitly specialized.
6645 Diag(NewLoc, getLangOpts().CPlusPlus11 ?
6646 diag::warn_cxx98_compat_explicit_instantiation_after_specialization :
6647 diag::ext_explicit_instantiation_after_specialization)
6649 Diag(PrevDecl->getLocation(),
6650 diag::note_previous_template_specialization);
6654 case TSK_ExplicitInstantiationDeclaration:
6655 // We're explicity instantiating a definition for something for which we
6656 // were previously asked to suppress instantiations. That's fine.
6658 // C++0x [temp.explicit]p4:
6659 // For a given set of template parameters, if an explicit instantiation
6660 // of a template appears after a declaration of an explicit
6661 // specialization for that template, the explicit instantiation has no
6663 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
6664 // Is there any previous explicit specialization declaration?
6665 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6673 case TSK_ExplicitInstantiationDefinition:
6674 // C++0x [temp.spec]p5:
6675 // For a given template and a given set of template-arguments,
6676 // - an explicit instantiation definition shall appear at most once
6679 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
6680 Diag(NewLoc, (getLangOpts().MSVCCompat)
6681 ? diag::ext_explicit_instantiation_duplicate
6682 : diag::err_explicit_instantiation_duplicate)
6684 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6685 diag::note_previous_explicit_instantiation);
6691 llvm_unreachable("Missing specialization/instantiation case?");
6694 /// \brief Perform semantic analysis for the given dependent function
6695 /// template specialization.
6697 /// The only possible way to get a dependent function template specialization
6698 /// is with a friend declaration, like so:
6701 /// template \<class T> void foo(T);
6702 /// template \<class T> class A {
6703 /// friend void foo<>(T);
6707 /// There really isn't any useful analysis we can do here, so we
6708 /// just store the information.
6710 Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6711 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6712 LookupResult &Previous) {
6713 // Remove anything from Previous that isn't a function template in
6714 // the correct context.
6715 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
6716 LookupResult::Filter F = Previous.makeFilter();
6717 while (F.hasNext()) {
6718 NamedDecl *D = F.next()->getUnderlyingDecl();
6719 if (!isa<FunctionTemplateDecl>(D) ||
6720 !FDLookupContext->InEnclosingNamespaceSetOf(
6721 D->getDeclContext()->getRedeclContext()))
6726 // Should this be diagnosed here?
6727 if (Previous.empty()) return true;
6729 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
6730 ExplicitTemplateArgs);
6734 /// \brief Perform semantic analysis for the given function template
6737 /// This routine performs all of the semantic analysis required for an
6738 /// explicit function template specialization. On successful completion,
6739 /// the function declaration \p FD will become a function template
6742 /// \param FD the function declaration, which will be updated to become a
6743 /// function template specialization.
6745 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
6746 /// if any. Note that this may be valid info even when 0 arguments are
6747 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
6748 /// as it anyway contains info on the angle brackets locations.
6750 /// \param Previous the set of declarations that may be specialized by
6751 /// this function specialization.
6752 bool Sema::CheckFunctionTemplateSpecialization(
6753 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
6754 LookupResult &Previous) {
6755 // The set of function template specializations that could match this
6756 // explicit function template specialization.
6757 UnresolvedSet<8> Candidates;
6758 TemplateSpecCandidateSet FailedCandidates(FD->getLocation());
6760 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
6761 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6763 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
6764 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
6765 // Only consider templates found within the same semantic lookup scope as
6767 if (!FDLookupContext->InEnclosingNamespaceSetOf(
6768 Ovl->getDeclContext()->getRedeclContext()))
6771 // When matching a constexpr member function template specialization
6772 // against the primary template, we don't yet know whether the
6773 // specialization has an implicit 'const' (because we don't know whether
6774 // it will be a static member function until we know which template it
6775 // specializes), so adjust it now assuming it specializes this template.
6776 QualType FT = FD->getType();
6777 if (FD->isConstexpr()) {
6778 CXXMethodDecl *OldMD =
6779 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
6780 if (OldMD && OldMD->isConst()) {
6781 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
6782 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6783 EPI.TypeQuals |= Qualifiers::Const;
6784 FT = Context.getFunctionType(FPT->getReturnType(),
6785 FPT->getParamTypes(), EPI);
6789 // C++ [temp.expl.spec]p11:
6790 // A trailing template-argument can be left unspecified in the
6791 // template-id naming an explicit function template specialization
6792 // provided it can be deduced from the function argument type.
6793 // Perform template argument deduction to determine whether we may be
6794 // specializing this template.
6795 // FIXME: It is somewhat wasteful to build
6796 TemplateDeductionInfo Info(FailedCandidates.getLocation());
6797 FunctionDecl *Specialization = nullptr;
6798 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
6799 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
6800 ExplicitTemplateArgs, FT, Specialization, Info)) {
6801 // Template argument deduction failed; record why it failed, so
6802 // that we can provide nifty diagnostics.
6803 FailedCandidates.addCandidate()
6804 .set(FunTmpl->getTemplatedDecl(),
6805 MakeDeductionFailureInfo(Context, TDK, Info));
6810 // Record this candidate.
6811 Candidates.addDecl(Specialization, I.getAccess());
6815 // Find the most specialized function template.
6816 UnresolvedSetIterator Result = getMostSpecialized(
6817 Candidates.begin(), Candidates.end(), FailedCandidates,
6819 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
6820 PDiag(diag::err_function_template_spec_ambiguous)
6821 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
6822 PDiag(diag::note_function_template_spec_matched));
6824 if (Result == Candidates.end())
6827 // Ignore access information; it doesn't figure into redeclaration checking.
6828 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
6830 FunctionTemplateSpecializationInfo *SpecInfo
6831 = Specialization->getTemplateSpecializationInfo();
6832 assert(SpecInfo && "Function template specialization info missing?");
6834 // Note: do not overwrite location info if previous template
6835 // specialization kind was explicit.
6836 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
6837 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
6838 Specialization->setLocation(FD->getLocation());
6839 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
6840 // function can differ from the template declaration with respect to
6841 // the constexpr specifier.
6842 Specialization->setConstexpr(FD->isConstexpr());
6845 // FIXME: Check if the prior specialization has a point of instantiation.
6846 // If so, we have run afoul of .
6848 // If this is a friend declaration, then we're not really declaring
6849 // an explicit specialization.
6850 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
6852 // Check the scope of this explicit specialization.
6854 CheckTemplateSpecializationScope(*this,
6855 Specialization->getPrimaryTemplate(),
6856 Specialization, FD->getLocation(),
6860 // C++ [temp.expl.spec]p6:
6861 // If a template, a member template or the member of a class template is
6862 // explicitly specialized then that specialization shall be declared
6863 // before the first use of that specialization that would cause an implicit
6864 // instantiation to take place, in every translation unit in which such a
6865 // use occurs; no diagnostic is required.
6866 bool HasNoEffect = false;
6868 CheckSpecializationInstantiationRedecl(FD->getLocation(),
6869 TSK_ExplicitSpecialization,
6871 SpecInfo->getTemplateSpecializationKind(),
6872 SpecInfo->getPointOfInstantiation(),
6876 // Mark the prior declaration as an explicit specialization, so that later
6877 // clients know that this is an explicit specialization.
6879 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
6880 MarkUnusedFileScopedDecl(Specialization);
6883 // Turn the given function declaration into a function template
6884 // specialization, with the template arguments from the previous
6886 // Take copies of (semantic and syntactic) template argument lists.
6887 const TemplateArgumentList* TemplArgs = new (Context)
6888 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
6889 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
6890 TemplArgs, /*InsertPos=*/nullptr,
6891 SpecInfo->getTemplateSpecializationKind(),
6892 ExplicitTemplateArgs);
6894 // The "previous declaration" for this function template specialization is
6895 // the prior function template specialization.
6897 Previous.addDecl(Specialization);
6901 /// \brief Perform semantic analysis for the given non-template member
6904 /// This routine performs all of the semantic analysis required for an
6905 /// explicit member function specialization. On successful completion,
6906 /// the function declaration \p FD will become a member function
6909 /// \param Member the member declaration, which will be updated to become a
6912 /// \param Previous the set of declarations, one of which may be specialized
6913 /// by this function specialization; the set will be modified to contain the
6914 /// redeclared member.
6916 Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
6917 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
6919 // Try to find the member we are instantiating.
6920 NamedDecl *Instantiation = nullptr;
6921 NamedDecl *InstantiatedFrom = nullptr;
6922 MemberSpecializationInfo *MSInfo = nullptr;
6924 if (Previous.empty()) {
6925 // Nowhere to look anyway.
6926 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
6927 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6929 NamedDecl *D = (*I)->getUnderlyingDecl();
6930 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
6931 QualType Adjusted = Function->getType();
6932 if (!hasExplicitCallingConv(Adjusted))
6933 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
6934 if (Context.hasSameType(Adjusted, Method->getType())) {
6935 Instantiation = Method;
6936 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
6937 MSInfo = Method->getMemberSpecializationInfo();
6942 } else if (isa<VarDecl>(Member)) {
6944 if (Previous.isSingleResult() &&
6945 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
6946 if (PrevVar->isStaticDataMember()) {
6947 Instantiation = PrevVar;
6948 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
6949 MSInfo = PrevVar->getMemberSpecializationInfo();
6951 } else if (isa<RecordDecl>(Member)) {
6952 CXXRecordDecl *PrevRecord;
6953 if (Previous.isSingleResult() &&
6954 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
6955 Instantiation = PrevRecord;
6956 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
6957 MSInfo = PrevRecord->getMemberSpecializationInfo();
6959 } else if (isa<EnumDecl>(Member)) {
6961 if (Previous.isSingleResult() &&
6962 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
6963 Instantiation = PrevEnum;
6964 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
6965 MSInfo = PrevEnum->getMemberSpecializationInfo();
6969 if (!Instantiation) {
6970 // There is no previous declaration that matches. Since member
6971 // specializations are always out-of-line, the caller will complain about
6972 // this mismatch later.
6976 // If this is a friend, just bail out here before we start turning
6977 // things into explicit specializations.
6978 if (Member->getFriendObjectKind() != Decl::FOK_None) {
6979 // Preserve instantiation information.
6980 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
6981 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
6982 cast<CXXMethodDecl>(InstantiatedFrom),
6983 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
6984 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
6985 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
6986 cast<CXXRecordDecl>(InstantiatedFrom),
6987 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
6991 Previous.addDecl(Instantiation);
6995 // Make sure that this is a specialization of a member.
6996 if (!InstantiatedFrom) {
6997 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
6999 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
7003 // C++ [temp.expl.spec]p6:
7004 // If a template, a member template or the member of a class template is
7005 // explicitly specialized then that specialization shall be declared
7006 // before the first use of that specialization that would cause an implicit
7007 // instantiation to take place, in every translation unit in which such a
7008 // use occurs; no diagnostic is required.
7009 assert(MSInfo && "Member specialization info missing?");
7011 bool HasNoEffect = false;
7012 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
7013 TSK_ExplicitSpecialization,
7015 MSInfo->getTemplateSpecializationKind(),
7016 MSInfo->getPointOfInstantiation(),
7020 // Check the scope of this explicit specialization.
7021 if (CheckTemplateSpecializationScope(*this,
7023 Instantiation, Member->getLocation(),
7027 // Note that this is an explicit instantiation of a member.
7028 // the original declaration to note that it is an explicit specialization
7029 // (if it was previously an implicit instantiation). This latter step
7030 // makes bookkeeping easier.
7031 if (isa<FunctionDecl>(Member)) {
7032 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
7033 if (InstantiationFunction->getTemplateSpecializationKind() ==
7034 TSK_ImplicitInstantiation) {
7035 InstantiationFunction->setTemplateSpecializationKind(
7036 TSK_ExplicitSpecialization);
7037 InstantiationFunction->setLocation(Member->getLocation());
7040 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
7041 cast<CXXMethodDecl>(InstantiatedFrom),
7042 TSK_ExplicitSpecialization);
7043 MarkUnusedFileScopedDecl(InstantiationFunction);
7044 } else if (isa<VarDecl>(Member)) {
7045 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
7046 if (InstantiationVar->getTemplateSpecializationKind() ==
7047 TSK_ImplicitInstantiation) {
7048 InstantiationVar->setTemplateSpecializationKind(
7049 TSK_ExplicitSpecialization);
7050 InstantiationVar->setLocation(Member->getLocation());
7053 cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
7054 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
7055 MarkUnusedFileScopedDecl(InstantiationVar);
7056 } else if (isa<CXXRecordDecl>(Member)) {
7057 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
7058 if (InstantiationClass->getTemplateSpecializationKind() ==
7059 TSK_ImplicitInstantiation) {
7060 InstantiationClass->setTemplateSpecializationKind(
7061 TSK_ExplicitSpecialization);
7062 InstantiationClass->setLocation(Member->getLocation());
7065 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
7066 cast<CXXRecordDecl>(InstantiatedFrom),
7067 TSK_ExplicitSpecialization);
7069 assert(isa<EnumDecl>(Member) && "Only member enums remain");
7070 EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
7071 if (InstantiationEnum->getTemplateSpecializationKind() ==
7072 TSK_ImplicitInstantiation) {
7073 InstantiationEnum->setTemplateSpecializationKind(
7074 TSK_ExplicitSpecialization);
7075 InstantiationEnum->setLocation(Member->getLocation());
7078 cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
7079 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
7082 // Save the caller the trouble of having to figure out which declaration
7083 // this specialization matches.
7085 Previous.addDecl(Instantiation);
7089 /// \brief Check the scope of an explicit instantiation.
7091 /// \returns true if a serious error occurs, false otherwise.
7092 static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
7093 SourceLocation InstLoc,
7094 bool WasQualifiedName) {
7095 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
7096 DeclContext *CurContext = S.CurContext->getRedeclContext();
7098 if (CurContext->isRecord()) {
7099 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
7104 // C++11 [temp.explicit]p3:
7105 // An explicit instantiation shall appear in an enclosing namespace of its
7106 // template. If the name declared in the explicit instantiation is an
7107 // unqualified name, the explicit instantiation shall appear in the
7108 // namespace where its template is declared or, if that namespace is inline
7109 // (7.3.1), any namespace from its enclosing namespace set.
7111 // This is DR275, which we do not retroactively apply to C++98/03.
7112 if (WasQualifiedName) {
7113 if (CurContext->Encloses(OrigContext))
7116 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
7120 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
7121 if (WasQualifiedName)
7123 S.getLangOpts().CPlusPlus11?
7124 diag::err_explicit_instantiation_out_of_scope :
7125 diag::warn_explicit_instantiation_out_of_scope_0x)
7129 S.getLangOpts().CPlusPlus11?
7130 diag::err_explicit_instantiation_unqualified_wrong_namespace :
7131 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
7135 S.getLangOpts().CPlusPlus11?
7136 diag::err_explicit_instantiation_must_be_global :
7137 diag::warn_explicit_instantiation_must_be_global_0x)
7139 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
7143 /// \brief Determine whether the given scope specifier has a template-id in it.
7144 static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
7148 // C++11 [temp.explicit]p3:
7149 // If the explicit instantiation is for a member function, a member class
7150 // or a static data member of a class template specialization, the name of
7151 // the class template specialization in the qualified-id for the member
7152 // name shall be a simple-template-id.
7154 // C++98 has the same restriction, just worded differently.
7155 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
7156 NNS = NNS->getPrefix())
7157 if (const Type *T = NNS->getAsType())
7158 if (isa<TemplateSpecializationType>(T))
7164 // Explicit instantiation of a class template specialization
7166 Sema::ActOnExplicitInstantiation(Scope *S,
7167 SourceLocation ExternLoc,
7168 SourceLocation TemplateLoc,
7170 SourceLocation KWLoc,
7171 const CXXScopeSpec &SS,
7172 TemplateTy TemplateD,
7173 SourceLocation TemplateNameLoc,
7174 SourceLocation LAngleLoc,
7175 ASTTemplateArgsPtr TemplateArgsIn,
7176 SourceLocation RAngleLoc,
7177 AttributeList *Attr) {
7178 // Find the class template we're specializing
7179 TemplateName Name = TemplateD.get();
7180 TemplateDecl *TD = Name.getAsTemplateDecl();
7181 // Check that the specialization uses the same tag kind as the
7182 // original template.
7183 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7184 assert(Kind != TTK_Enum &&
7185 "Invalid enum tag in class template explicit instantiation!");
7187 if (isa<TypeAliasTemplateDecl>(TD)) {
7188 Diag(KWLoc, diag::err_tag_reference_non_tag) << Kind;
7189 Diag(TD->getTemplatedDecl()->getLocation(),
7190 diag::note_previous_use);
7194 ClassTemplateDecl *ClassTemplate = cast<ClassTemplateDecl>(TD);
7196 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
7197 Kind, /*isDefinition*/false, KWLoc,
7198 *ClassTemplate->getIdentifier())) {
7199 Diag(KWLoc, diag::err_use_with_wrong_tag)
7201 << FixItHint::CreateReplacement(KWLoc,
7202 ClassTemplate->getTemplatedDecl()->getKindName());
7203 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
7204 diag::note_previous_use);
7205 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7208 // C++0x [temp.explicit]p2:
7209 // There are two forms of explicit instantiation: an explicit instantiation
7210 // definition and an explicit instantiation declaration. An explicit
7211 // instantiation declaration begins with the extern keyword. [...]
7212 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
7213 ? TSK_ExplicitInstantiationDefinition
7214 : TSK_ExplicitInstantiationDeclaration;
7216 if (TSK == TSK_ExplicitInstantiationDeclaration) {
7217 // Check for dllexport class template instantiation declarations.
7218 for (AttributeList *A = Attr; A; A = A->getNext()) {
7219 if (A->getKind() == AttributeList::AT_DLLExport) {
7221 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7222 Diag(A->getLoc(), diag::note_attribute);
7227 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
7229 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7230 Diag(A->getLocation(), diag::note_attribute);
7234 // Translate the parser's template argument list in our AST format.
7235 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
7236 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
7238 // Check that the template argument list is well-formed for this
7240 SmallVector<TemplateArgument, 4> Converted;
7241 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7242 TemplateArgs, false, Converted))
7245 // Find the class template specialization declaration that
7246 // corresponds to these arguments.
7247 void *InsertPos = nullptr;
7248 ClassTemplateSpecializationDecl *PrevDecl
7249 = ClassTemplate->findSpecialization(Converted, InsertPos);
7251 TemplateSpecializationKind PrevDecl_TSK
7252 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
7254 // C++0x [temp.explicit]p2:
7255 // [...] An explicit instantiation shall appear in an enclosing
7256 // namespace of its template. [...]
7258 // This is C++ DR 275.
7259 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
7263 ClassTemplateSpecializationDecl *Specialization = nullptr;
7265 bool HasNoEffect = false;
7267 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
7268 PrevDecl, PrevDecl_TSK,
7269 PrevDecl->getPointOfInstantiation(),
7273 // Even though HasNoEffect == true means that this explicit instantiation
7274 // has no effect on semantics, we go on to put its syntax in the AST.
7276 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
7277 PrevDecl_TSK == TSK_Undeclared) {
7278 // Since the only prior class template specialization with these
7279 // arguments was referenced but not declared, reuse that
7280 // declaration node as our own, updating the source location
7281 // for the template name to reflect our new declaration.
7282 // (Other source locations will be updated later.)
7283 Specialization = PrevDecl;
7284 Specialization->setLocation(TemplateNameLoc);
7289 if (!Specialization) {
7290 // Create a new class template specialization declaration node for
7291 // this explicit specialization.
7293 = ClassTemplateSpecializationDecl::Create(Context, Kind,
7294 ClassTemplate->getDeclContext(),
7295 KWLoc, TemplateNameLoc,
7300 SetNestedNameSpecifier(Specialization, SS);
7302 if (!HasNoEffect && !PrevDecl) {
7303 // Insert the new specialization.
7304 ClassTemplate->AddSpecialization(Specialization, InsertPos);
7308 // Build the fully-sugared type for this explicit instantiation as
7309 // the user wrote in the explicit instantiation itself. This means
7310 // that we'll pretty-print the type retrieved from the
7311 // specialization's declaration the way that the user actually wrote
7312 // the explicit instantiation, rather than formatting the name based
7313 // on the "canonical" representation used to store the template
7314 // arguments in the specialization.
7315 TypeSourceInfo *WrittenTy
7316 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7318 Context.getTypeDeclType(Specialization));
7319 Specialization->setTypeAsWritten(WrittenTy);
7321 // Set source locations for keywords.
7322 Specialization->setExternLoc(ExternLoc);
7323 Specialization->setTemplateKeywordLoc(TemplateLoc);
7324 Specialization->setRBraceLoc(SourceLocation());
7327 ProcessDeclAttributeList(S, Specialization, Attr);
7329 // Add the explicit instantiation into its lexical context. However,
7330 // since explicit instantiations are never found by name lookup, we
7331 // just put it into the declaration context directly.
7332 Specialization->setLexicalDeclContext(CurContext);
7333 CurContext->addDecl(Specialization);
7335 // Syntax is now OK, so return if it has no other effect on semantics.
7337 // Set the template specialization kind.
7338 Specialization->setTemplateSpecializationKind(TSK);
7339 return Specialization;
7342 // C++ [temp.explicit]p3:
7343 // A definition of a class template or class member template
7344 // shall be in scope at the point of the explicit instantiation of
7345 // the class template or class member template.
7347 // This check comes when we actually try to perform the
7349 ClassTemplateSpecializationDecl *Def
7350 = cast_or_null<ClassTemplateSpecializationDecl>(
7351 Specialization->getDefinition());
7353 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
7354 else if (TSK == TSK_ExplicitInstantiationDefinition) {
7355 MarkVTableUsed(TemplateNameLoc, Specialization, true);
7356 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
7359 // Instantiate the members of this class template specialization.
7360 Def = cast_or_null<ClassTemplateSpecializationDecl>(
7361 Specialization->getDefinition());
7363 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
7365 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
7366 // TSK_ExplicitInstantiationDefinition
7367 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
7368 TSK == TSK_ExplicitInstantiationDefinition) {
7369 // FIXME: Need to notify the ASTMutationListener that we did this.
7370 Def->setTemplateSpecializationKind(TSK);
7372 if (!getDLLAttr(Def) && getDLLAttr(Specialization)) {
7373 auto *A = cast<InheritableAttr>(
7374 getDLLAttr(Specialization)->clone(getASTContext()));
7375 A->setInherited(true);
7377 checkClassLevelDLLAttribute(Def);
7381 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
7384 // Set the template specialization kind.
7385 Specialization->setTemplateSpecializationKind(TSK);
7386 return Specialization;
7389 // Explicit instantiation of a member class of a class template.
7391 Sema::ActOnExplicitInstantiation(Scope *S,
7392 SourceLocation ExternLoc,
7393 SourceLocation TemplateLoc,
7395 SourceLocation KWLoc,
7397 IdentifierInfo *Name,
7398 SourceLocation NameLoc,
7399 AttributeList *Attr) {
7402 bool IsDependent = false;
7403 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
7404 KWLoc, SS, Name, NameLoc, Attr, AS_none,
7405 /*ModulePrivateLoc=*/SourceLocation(),
7406 MultiTemplateParamsArg(), Owned, IsDependent,
7407 SourceLocation(), false, TypeResult(),
7408 /*IsTypeSpecifier*/false);
7409 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
7414 TagDecl *Tag = cast<TagDecl>(TagD);
7415 assert(!Tag->isEnum() && "shouldn't see enumerations here");
7417 if (Tag->isInvalidDecl())
7420 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
7421 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
7423 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
7424 << Context.getTypeDeclType(Record);
7425 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
7429 // C++0x [temp.explicit]p2:
7430 // If the explicit instantiation is for a class or member class, the
7431 // elaborated-type-specifier in the declaration shall include a
7432 // simple-template-id.
7434 // C++98 has the same restriction, just worded differently.
7435 if (!ScopeSpecifierHasTemplateId(SS))
7436 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
7437 << Record << SS.getRange();
7439 // C++0x [temp.explicit]p2:
7440 // There are two forms of explicit instantiation: an explicit instantiation
7441 // definition and an explicit instantiation declaration. An explicit
7442 // instantiation declaration begins with the extern keyword. [...]
7443 TemplateSpecializationKind TSK
7444 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7445 : TSK_ExplicitInstantiationDeclaration;
7447 // C++0x [temp.explicit]p2:
7448 // [...] An explicit instantiation shall appear in an enclosing
7449 // namespace of its template. [...]
7451 // This is C++ DR 275.
7452 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
7454 // Verify that it is okay to explicitly instantiate here.
7455 CXXRecordDecl *PrevDecl
7456 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
7457 if (!PrevDecl && Record->getDefinition())
7460 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
7461 bool HasNoEffect = false;
7462 assert(MSInfo && "No member specialization information?");
7463 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
7465 MSInfo->getTemplateSpecializationKind(),
7466 MSInfo->getPointOfInstantiation(),
7473 CXXRecordDecl *RecordDef
7474 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
7476 // C++ [temp.explicit]p3:
7477 // A definition of a member class of a class template shall be in scope
7478 // at the point of an explicit instantiation of the member class.
7480 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
7482 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
7483 << 0 << Record->getDeclName() << Record->getDeclContext();
7484 Diag(Pattern->getLocation(), diag::note_forward_declaration)
7488 if (InstantiateClass(NameLoc, Record, Def,
7489 getTemplateInstantiationArgs(Record),
7493 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
7499 // Instantiate all of the members of the class.
7500 InstantiateClassMembers(NameLoc, RecordDef,
7501 getTemplateInstantiationArgs(Record), TSK);
7503 if (TSK == TSK_ExplicitInstantiationDefinition)
7504 MarkVTableUsed(NameLoc, RecordDef, true);
7506 // FIXME: We don't have any representation for explicit instantiations of
7507 // member classes. Such a representation is not needed for compilation, but it
7508 // should be available for clients that want to see all of the declarations in
7513 DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
7514 SourceLocation ExternLoc,
7515 SourceLocation TemplateLoc,
7517 // Explicit instantiations always require a name.
7518 // TODO: check if/when DNInfo should replace Name.
7519 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7520 DeclarationName Name = NameInfo.getName();
7522 if (!D.isInvalidType())
7523 Diag(D.getDeclSpec().getLocStart(),
7524 diag::err_explicit_instantiation_requires_name)
7525 << D.getDeclSpec().getSourceRange()
7526 << D.getSourceRange();
7531 // The scope passed in may not be a decl scope. Zip up the scope tree until
7532 // we find one that is.
7533 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7534 (S->getFlags() & Scope::TemplateParamScope) != 0)
7537 // Determine the type of the declaration.
7538 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
7539 QualType R = T->getType();
7544 // A storage-class-specifier shall not be specified in [...] an explicit
7545 // instantiation (14.7.2) directive.
7546 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
7547 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
7550 } else if (D.getDeclSpec().getStorageClassSpec()
7551 != DeclSpec::SCS_unspecified) {
7552 // Complain about then remove the storage class specifier.
7553 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
7554 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7556 D.getMutableDeclSpec().ClearStorageClassSpecs();
7559 // C++0x [temp.explicit]p1:
7560 // [...] An explicit instantiation of a function template shall not use the
7561 // inline or constexpr specifiers.
7562 // Presumably, this also applies to member functions of class templates as
7564 if (D.getDeclSpec().isInlineSpecified())
7565 Diag(D.getDeclSpec().getInlineSpecLoc(),
7566 getLangOpts().CPlusPlus11 ?
7567 diag::err_explicit_instantiation_inline :
7568 diag::warn_explicit_instantiation_inline_0x)
7569 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7570 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
7571 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
7572 // not already specified.
7573 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7574 diag::err_explicit_instantiation_constexpr);
7576 // C++0x [temp.explicit]p2:
7577 // There are two forms of explicit instantiation: an explicit instantiation
7578 // definition and an explicit instantiation declaration. An explicit
7579 // instantiation declaration begins with the extern keyword. [...]
7580 TemplateSpecializationKind TSK
7581 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7582 : TSK_ExplicitInstantiationDeclaration;
7584 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
7585 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
7587 if (!R->isFunctionType()) {
7588 // C++ [temp.explicit]p1:
7589 // A [...] static data member of a class template can be explicitly
7590 // instantiated from the member definition associated with its class
7592 // C++1y [temp.explicit]p1:
7593 // A [...] variable [...] template specialization can be explicitly
7594 // instantiated from its template.
7595 if (Previous.isAmbiguous())
7598 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
7599 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
7601 if (!PrevTemplate) {
7602 if (!Prev || !Prev->isStaticDataMember()) {
7603 // We expect to see a data data member here.
7604 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
7606 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7608 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
7612 if (!Prev->getInstantiatedFromStaticDataMember()) {
7613 // FIXME: Check for explicit specialization?
7614 Diag(D.getIdentifierLoc(),
7615 diag::err_explicit_instantiation_data_member_not_instantiated)
7617 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
7618 // FIXME: Can we provide a note showing where this was declared?
7622 // Explicitly instantiate a variable template.
7624 // C++1y [dcl.spec.auto]p6:
7625 // ... A program that uses auto or decltype(auto) in a context not
7626 // explicitly allowed in this section is ill-formed.
7628 // This includes auto-typed variable template instantiations.
7629 if (R->isUndeducedType()) {
7630 Diag(T->getTypeLoc().getLocStart(),
7631 diag::err_auto_not_allowed_var_inst);
7635 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7636 // C++1y [temp.explicit]p3:
7637 // If the explicit instantiation is for a variable, the unqualified-id
7638 // in the declaration shall be a template-id.
7639 Diag(D.getIdentifierLoc(),
7640 diag::err_explicit_instantiation_without_template_id)
7642 Diag(PrevTemplate->getLocation(),
7643 diag::note_explicit_instantiation_here);
7647 // Translate the parser's template argument list into our AST format.
7648 TemplateArgumentListInfo TemplateArgs =
7649 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
7651 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
7652 D.getIdentifierLoc(), TemplateArgs);
7653 if (Res.isInvalid())
7656 // Ignore access control bits, we don't need them for redeclaration
7658 Prev = cast<VarDecl>(Res.get());
7661 // C++0x [temp.explicit]p2:
7662 // If the explicit instantiation is for a member function, a member class
7663 // or a static data member of a class template specialization, the name of
7664 // the class template specialization in the qualified-id for the member
7665 // name shall be a simple-template-id.
7667 // C++98 has the same restriction, just worded differently.
7669 // This does not apply to variable template specializations, where the
7670 // template-id is in the unqualified-id instead.
7671 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
7672 Diag(D.getIdentifierLoc(),
7673 diag::ext_explicit_instantiation_without_qualified_id)
7674 << Prev << D.getCXXScopeSpec().getRange();
7676 // Check the scope of this explicit instantiation.
7677 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
7679 // Verify that it is okay to explicitly instantiate here.
7680 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
7681 SourceLocation POI = Prev->getPointOfInstantiation();
7682 bool HasNoEffect = false;
7683 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
7684 PrevTSK, POI, HasNoEffect))
7688 // Instantiate static data member or variable template.
7690 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
7692 // Merge attributes.
7693 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
7694 ProcessDeclAttributeList(S, Prev, Attr);
7696 if (TSK == TSK_ExplicitInstantiationDefinition)
7697 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
7700 // Check the new variable specialization against the parsed input.
7701 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
7702 Diag(T->getTypeLoc().getLocStart(),
7703 diag::err_invalid_var_template_spec_type)
7704 << 0 << PrevTemplate << R << Prev->getType();
7705 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
7706 << 2 << PrevTemplate->getDeclName();
7710 // FIXME: Create an ExplicitInstantiation node?
7711 return (Decl*) nullptr;
7714 // If the declarator is a template-id, translate the parser's template
7715 // argument list into our AST format.
7716 bool HasExplicitTemplateArgs = false;
7717 TemplateArgumentListInfo TemplateArgs;
7718 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7719 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
7720 HasExplicitTemplateArgs = true;
7723 // C++ [temp.explicit]p1:
7724 // A [...] function [...] can be explicitly instantiated from its template.
7725 // A member function [...] of a class template can be explicitly
7726 // instantiated from the member definition associated with its class
7728 UnresolvedSet<8> Matches;
7729 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
7730 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7732 NamedDecl *Prev = *P;
7733 if (!HasExplicitTemplateArgs) {
7734 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
7735 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType());
7736 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
7739 Matches.addDecl(Method, P.getAccess());
7740 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
7746 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
7750 TemplateDeductionInfo Info(FailedCandidates.getLocation());
7751 FunctionDecl *Specialization = nullptr;
7752 if (TemplateDeductionResult TDK
7753 = DeduceTemplateArguments(FunTmpl,
7754 (HasExplicitTemplateArgs ? &TemplateArgs
7756 R, Specialization, Info)) {
7757 // Keep track of almost-matches.
7758 FailedCandidates.addCandidate()
7759 .set(FunTmpl->getTemplatedDecl(),
7760 MakeDeductionFailureInfo(Context, TDK, Info));
7765 Matches.addDecl(Specialization, P.getAccess());
7768 // Find the most specialized function template specialization.
7769 UnresolvedSetIterator Result = getMostSpecialized(
7770 Matches.begin(), Matches.end(), FailedCandidates,
7771 D.getIdentifierLoc(),
7772 PDiag(diag::err_explicit_instantiation_not_known) << Name,
7773 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
7774 PDiag(diag::note_explicit_instantiation_candidate));
7776 if (Result == Matches.end())
7779 // Ignore access control bits, we don't need them for redeclaration checking.
7780 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
7782 // C++11 [except.spec]p4
7783 // In an explicit instantiation an exception-specification may be specified,
7784 // but is not required.
7785 // If an exception-specification is specified in an explicit instantiation
7786 // directive, it shall be compatible with the exception-specifications of
7787 // other declarations of that function.
7788 if (auto *FPT = R->getAs<FunctionProtoType>())
7789 if (FPT->hasExceptionSpec()) {
7791 diag::err_mismatched_exception_spec_explicit_instantiation;
7792 if (getLangOpts().MicrosoftExt)
7793 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
7794 bool Result = CheckEquivalentExceptionSpec(
7795 PDiag(DiagID) << Specialization->getType(),
7796 PDiag(diag::note_explicit_instantiation_here),
7797 Specialization->getType()->getAs<FunctionProtoType>(),
7798 Specialization->getLocation(), FPT, D.getLocStart());
7799 // In Microsoft mode, mismatching exception specifications just cause a
7801 if (!getLangOpts().MicrosoftExt && Result)
7805 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
7806 Diag(D.getIdentifierLoc(),
7807 diag::err_explicit_instantiation_member_function_not_instantiated)
7809 << (Specialization->getTemplateSpecializationKind() ==
7810 TSK_ExplicitSpecialization);
7811 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
7815 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
7816 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
7817 PrevDecl = Specialization;
7820 bool HasNoEffect = false;
7821 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
7823 PrevDecl->getTemplateSpecializationKind(),
7824 PrevDecl->getPointOfInstantiation(),
7828 // FIXME: We may still want to build some representation of this
7829 // explicit specialization.
7831 return (Decl*) nullptr;
7834 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
7835 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
7837 ProcessDeclAttributeList(S, Specialization, Attr);
7839 if (Specialization->isDefined()) {
7840 // Let the ASTConsumer know that this function has been explicitly
7841 // instantiated now, and its linkage might have changed.
7842 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
7843 } else if (TSK == TSK_ExplicitInstantiationDefinition)
7844 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
7846 // C++0x [temp.explicit]p2:
7847 // If the explicit instantiation is for a member function, a member class
7848 // or a static data member of a class template specialization, the name of
7849 // the class template specialization in the qualified-id for the member
7850 // name shall be a simple-template-id.
7852 // C++98 has the same restriction, just worded differently.
7853 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
7854 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
7855 D.getCXXScopeSpec().isSet() &&
7856 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
7857 Diag(D.getIdentifierLoc(),
7858 diag::ext_explicit_instantiation_without_qualified_id)
7859 << Specialization << D.getCXXScopeSpec().getRange();
7861 CheckExplicitInstantiationScope(*this,
7862 FunTmpl? (NamedDecl *)FunTmpl
7863 : Specialization->getInstantiatedFromMemberFunction(),
7864 D.getIdentifierLoc(),
7865 D.getCXXScopeSpec().isSet());
7867 // FIXME: Create some kind of ExplicitInstantiationDecl here.
7868 return (Decl*) nullptr;
7872 Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
7873 const CXXScopeSpec &SS, IdentifierInfo *Name,
7874 SourceLocation TagLoc, SourceLocation NameLoc) {
7875 // This has to hold, because SS is expected to be defined.
7876 assert(Name && "Expected a name in a dependent tag");
7878 NestedNameSpecifier *NNS = SS.getScopeRep();
7882 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7884 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
7885 Diag(NameLoc, diag::err_dependent_tag_decl)
7886 << (TUK == TUK_Definition) << Kind << SS.getRange();
7890 // Create the resulting type.
7891 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
7892 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
7894 // Create type-source location information for this type.
7896 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
7897 TL.setElaboratedKeywordLoc(TagLoc);
7898 TL.setQualifierLoc(SS.getWithLocInContext(Context));
7899 TL.setNameLoc(NameLoc);
7900 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
7904 Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
7905 const CXXScopeSpec &SS, const IdentifierInfo &II,
7906 SourceLocation IdLoc) {
7910 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
7912 getLangOpts().CPlusPlus11 ?
7913 diag::warn_cxx98_compat_typename_outside_of_template :
7914 diag::ext_typename_outside_of_template)
7915 << FixItHint::CreateRemoval(TypenameLoc);
7917 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
7918 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
7919 TypenameLoc, QualifierLoc, II, IdLoc);
7923 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
7924 if (isa<DependentNameType>(T)) {
7925 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
7926 TL.setElaboratedKeywordLoc(TypenameLoc);
7927 TL.setQualifierLoc(QualifierLoc);
7928 TL.setNameLoc(IdLoc);
7930 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
7931 TL.setElaboratedKeywordLoc(TypenameLoc);
7932 TL.setQualifierLoc(QualifierLoc);
7933 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
7936 return CreateParsedType(T, TSI);
7940 Sema::ActOnTypenameType(Scope *S,
7941 SourceLocation TypenameLoc,
7942 const CXXScopeSpec &SS,
7943 SourceLocation TemplateKWLoc,
7944 TemplateTy TemplateIn,
7945 SourceLocation TemplateNameLoc,
7946 SourceLocation LAngleLoc,
7947 ASTTemplateArgsPtr TemplateArgsIn,
7948 SourceLocation RAngleLoc) {
7949 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
7951 getLangOpts().CPlusPlus11 ?
7952 diag::warn_cxx98_compat_typename_outside_of_template :
7953 diag::ext_typename_outside_of_template)
7954 << FixItHint::CreateRemoval(TypenameLoc);
7956 // Translate the parser's template argument list in our AST format.
7957 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
7958 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
7960 TemplateName Template = TemplateIn.get();
7961 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
7962 // Construct a dependent template specialization type.
7963 assert(DTN && "dependent template has non-dependent name?");
7964 assert(DTN->getQualifier() == SS.getScopeRep());
7965 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
7966 DTN->getQualifier(),
7967 DTN->getIdentifier(),
7970 // Create source-location information for this type.
7971 TypeLocBuilder Builder;
7972 DependentTemplateSpecializationTypeLoc SpecTL
7973 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
7974 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
7975 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
7976 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
7977 SpecTL.setTemplateNameLoc(TemplateNameLoc);
7978 SpecTL.setLAngleLoc(LAngleLoc);
7979 SpecTL.setRAngleLoc(RAngleLoc);
7980 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7981 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
7982 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
7985 QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
7989 // Provide source-location information for the template specialization type.
7990 TypeLocBuilder Builder;
7991 TemplateSpecializationTypeLoc SpecTL
7992 = Builder.push<TemplateSpecializationTypeLoc>(T);
7993 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
7994 SpecTL.setTemplateNameLoc(TemplateNameLoc);
7995 SpecTL.setLAngleLoc(LAngleLoc);
7996 SpecTL.setRAngleLoc(RAngleLoc);
7997 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7998 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
8000 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
8001 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
8002 TL.setElaboratedKeywordLoc(TypenameLoc);
8003 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8005 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
8006 return CreateParsedType(T, TSI);
8010 /// Determine whether this failed name lookup should be treated as being
8011 /// disabled by a usage of std::enable_if.
8012 static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
8013 SourceRange &CondRange) {
8014 // We must be looking for a ::type...
8015 if (!II.isStr("type"))
8018 // ... within an explicitly-written template specialization...
8019 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
8021 TypeLoc EnableIfTy = NNS.getTypeLoc();
8022 TemplateSpecializationTypeLoc EnableIfTSTLoc =
8023 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
8024 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
8026 const TemplateSpecializationType *EnableIfTST =
8027 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
8029 // ... which names a complete class template declaration...
8030 const TemplateDecl *EnableIfDecl =
8031 EnableIfTST->getTemplateName().getAsTemplateDecl();
8032 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
8035 // ... called "enable_if".
8036 const IdentifierInfo *EnableIfII =
8037 EnableIfDecl->getDeclName().getAsIdentifierInfo();
8038 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
8041 // Assume the first template argument is the condition.
8042 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
8046 /// \brief Build the type that describes a C++ typename specifier,
8047 /// e.g., "typename T::type".
8049 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
8050 SourceLocation KeywordLoc,
8051 NestedNameSpecifierLoc QualifierLoc,
8052 const IdentifierInfo &II,
8053 SourceLocation IILoc) {
8055 SS.Adopt(QualifierLoc);
8057 DeclContext *Ctx = computeDeclContext(SS);
8059 // If the nested-name-specifier is dependent and couldn't be
8060 // resolved to a type, build a typename type.
8061 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
8062 return Context.getDependentNameType(Keyword,
8063 QualifierLoc.getNestedNameSpecifier(),
8067 // If the nested-name-specifier refers to the current instantiation,
8068 // the "typename" keyword itself is superfluous. In C++03, the
8069 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
8070 // allows such extraneous "typename" keywords, and we retroactively
8071 // apply this DR to C++03 code with only a warning. In any case we continue.
8073 if (RequireCompleteDeclContext(SS, Ctx))
8076 DeclarationName Name(&II);
8077 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
8078 LookupQualifiedName(Result, Ctx, SS);
8079 unsigned DiagID = 0;
8080 Decl *Referenced = nullptr;
8081 switch (Result.getResultKind()) {
8082 case LookupResult::NotFound: {
8083 // If we're looking up 'type' within a template named 'enable_if', produce
8084 // a more specific diagnostic.
8085 SourceRange CondRange;
8086 if (isEnableIf(QualifierLoc, II, CondRange)) {
8087 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
8088 << Ctx << CondRange;
8092 DiagID = diag::err_typename_nested_not_found;
8096 case LookupResult::FoundUnresolvedValue: {
8097 // We found a using declaration that is a value. Most likely, the using
8098 // declaration itself is meant to have the 'typename' keyword.
8099 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
8101 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
8102 << Name << Ctx << FullRange;
8103 if (UnresolvedUsingValueDecl *Using
8104 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
8105 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
8106 Diag(Loc, diag::note_using_value_decl_missing_typename)
8107 << FixItHint::CreateInsertion(Loc, "typename ");
8110 // Fall through to create a dependent typename type, from which we can recover
8113 case LookupResult::NotFoundInCurrentInstantiation:
8114 // Okay, it's a member of an unknown instantiation.
8115 return Context.getDependentNameType(Keyword,
8116 QualifierLoc.getNestedNameSpecifier(),
8119 case LookupResult::Found:
8120 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
8121 // We found a type. Build an ElaboratedType, since the
8122 // typename-specifier was just sugar.
8123 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
8124 return Context.getElaboratedType(ETK_Typename,
8125 QualifierLoc.getNestedNameSpecifier(),
8126 Context.getTypeDeclType(Type));
8129 DiagID = diag::err_typename_nested_not_type;
8130 Referenced = Result.getFoundDecl();
8133 case LookupResult::FoundOverloaded:
8134 DiagID = diag::err_typename_nested_not_type;
8135 Referenced = *Result.begin();
8138 case LookupResult::Ambiguous:
8142 // If we get here, it's because name lookup did not find a
8143 // type. Emit an appropriate diagnostic and return an error.
8144 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
8146 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
8148 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
8154 // See Sema::RebuildTypeInCurrentInstantiation
8155 class CurrentInstantiationRebuilder
8156 : public TreeTransform<CurrentInstantiationRebuilder> {
8158 DeclarationName Entity;
8161 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
8163 CurrentInstantiationRebuilder(Sema &SemaRef,
8165 DeclarationName Entity)
8166 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
8167 Loc(Loc), Entity(Entity) { }
8169 /// \brief Determine whether the given type \p T has already been
8172 /// For the purposes of type reconstruction, a type has already been
8173 /// transformed if it is NULL or if it is not dependent.
8174 bool AlreadyTransformed(QualType T) {
8175 return T.isNull() || !T->isDependentType();
8178 /// \brief Returns the location of the entity whose type is being
8180 SourceLocation getBaseLocation() { return Loc; }
8182 /// \brief Returns the name of the entity whose type is being rebuilt.
8183 DeclarationName getBaseEntity() { return Entity; }
8185 /// \brief Sets the "base" location and entity when that
8186 /// information is known based on another transformation.
8187 void setBase(SourceLocation Loc, DeclarationName Entity) {
8189 this->Entity = Entity;
8192 ExprResult TransformLambdaExpr(LambdaExpr *E) {
8193 // Lambdas never need to be transformed.
8199 /// \brief Rebuilds a type within the context of the current instantiation.
8201 /// The type \p T is part of the type of an out-of-line member definition of
8202 /// a class template (or class template partial specialization) that was parsed
8203 /// and constructed before we entered the scope of the class template (or
8204 /// partial specialization thereof). This routine will rebuild that type now
8205 /// that we have entered the declarator's scope, which may produce different
8206 /// canonical types, e.g.,
8209 /// template<typename T>
8211 /// typedef T* pointer;
8215 /// template<typename T>
8216 /// typename X<T>::pointer X<T>::data() { ... }
8219 /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
8220 /// since we do not know that we can look into X<T> when we parsed the type.
8221 /// This function will rebuild the type, performing the lookup of "pointer"
8222 /// in X<T> and returning an ElaboratedType whose canonical type is the same
8223 /// as the canonical type of T*, allowing the return types of the out-of-line
8224 /// definition and the declaration to match.
8225 TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
8227 DeclarationName Name) {
8228 if (!T || !T->getType()->isDependentType())
8231 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
8232 return Rebuilder.TransformType(T);
8235 ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
8236 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
8238 return Rebuilder.TransformExpr(E);
8241 bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
8245 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
8246 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
8248 NestedNameSpecifierLoc Rebuilt
8249 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
8257 /// \brief Rebuild the template parameters now that we know we're in a current
8259 bool Sema::RebuildTemplateParamsInCurrentInstantiation(
8260 TemplateParameterList *Params) {
8261 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8262 Decl *Param = Params->getParam(I);
8264 // There is nothing to rebuild in a type parameter.
8265 if (isa<TemplateTypeParmDecl>(Param))
8268 // Rebuild the template parameter list of a template template parameter.
8269 if (TemplateTemplateParmDecl *TTP
8270 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
8271 if (RebuildTemplateParamsInCurrentInstantiation(
8272 TTP->getTemplateParameters()))
8278 // Rebuild the type of a non-type template parameter.
8279 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
8280 TypeSourceInfo *NewTSI
8281 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
8282 NTTP->getLocation(),
8283 NTTP->getDeclName());
8287 if (NewTSI != NTTP->getTypeSourceInfo()) {
8288 NTTP->setTypeSourceInfo(NewTSI);
8289 NTTP->setType(NewTSI->getType());
8296 /// \brief Produces a formatted string that describes the binding of
8297 /// template parameters to template arguments.
8299 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8300 const TemplateArgumentList &Args) {
8301 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
8305 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8306 const TemplateArgument *Args,
8308 SmallString<128> Str;
8309 llvm::raw_svector_ostream Out(Str);
8311 if (!Params || Params->size() == 0 || NumArgs == 0)
8312 return std::string();
8314 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8323 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
8324 Out << Id->getName();
8330 Args[I].print(getPrintingPolicy(), Out);
8337 void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
8338 CachedTokens &Toks) {
8342 LateParsedTemplate *LPT = new LateParsedTemplate;
8344 // Take tokens to avoid allocations
8345 LPT->Toks.swap(Toks);
8347 LateParsedTemplateMap.insert(std::make_pair(FD, LPT));
8349 FD->setLateTemplateParsed(true);
8352 void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
8355 FD->setLateTemplateParsed(false);
8358 bool Sema::IsInsideALocalClassWithinATemplateFunction() {
8359 DeclContext *DC = CurContext;
8362 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
8363 const FunctionDecl *FD = RD->isLocalClass();
8364 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
8365 } else if (DC->isTranslationUnit() || DC->isNamespace())
8368 DC = DC->getParent();