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/ASTContext.h"
14 #include "clang/AST/ASTConsumer.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/Sema/DeclSpec.h"
24 #include "clang/Sema/Lookup.h"
25 #include "clang/Sema/ParsedTemplate.h"
26 #include "clang/Sema/Scope.h"
27 #include "clang/Sema/SemaInternal.h"
28 #include "clang/Sema/Template.h"
29 #include "clang/Sema/TemplateDeduction.h"
30 #include "llvm/ADT/SmallBitVector.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/StringExtras.h"
33 using namespace clang;
36 // Exported for use by Parser.
38 clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
40 if (!N) return SourceRange();
41 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
44 /// \brief Determine whether the declaration found is acceptable as the name
45 /// of a template and, if so, return that template declaration. Otherwise,
47 static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
49 bool AllowFunctionTemplates) {
50 NamedDecl *D = Orig->getUnderlyingDecl();
52 if (isa<TemplateDecl>(D)) {
53 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
59 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
60 // C++ [temp.local]p1:
61 // Like normal (non-template) classes, class templates have an
62 // injected-class-name (Clause 9). The injected-class-name
63 // can be used with or without a template-argument-list. When
64 // it is used without a template-argument-list, it is
65 // equivalent to the injected-class-name followed by the
66 // template-parameters of the class template enclosed in
67 // <>. When it is used with a template-argument-list, it
68 // refers to the specified class template specialization,
69 // which could be the current specialization or another
71 if (Record->isInjectedClassName()) {
72 Record = cast<CXXRecordDecl>(Record->getDeclContext());
73 if (Record->getDescribedClassTemplate())
74 return Record->getDescribedClassTemplate();
76 if (ClassTemplateSpecializationDecl *Spec
77 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
78 return Spec->getSpecializedTemplate();
87 void Sema::FilterAcceptableTemplateNames(LookupResult &R,
88 bool AllowFunctionTemplates) {
89 // The set of class templates we've already seen.
90 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
91 LookupResult::Filter filter = R.makeFilter();
92 while (filter.hasNext()) {
93 NamedDecl *Orig = filter.next();
94 NamedDecl *Repl = isAcceptableTemplateName(Context, Orig,
95 AllowFunctionTemplates);
98 else if (Repl != Orig) {
100 // C++ [temp.local]p3:
101 // A lookup that finds an injected-class-name (10.2) can result in an
102 // ambiguity in certain cases (for example, if it is found in more than
103 // one base class). If all of the injected-class-names that are found
104 // refer to specializations of the same class template, and if the name
105 // is used as a template-name, the reference refers to the class
106 // template itself and not a specialization thereof, and is not
108 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
109 if (!ClassTemplates.insert(ClassTmpl)) {
114 // FIXME: we promote access to public here as a workaround to
115 // the fact that LookupResult doesn't let us remember that we
116 // found this template through a particular injected class name,
117 // which means we end up doing nasty things to the invariants.
118 // Pretending that access is public is *much* safer.
119 filter.replace(Repl, AS_public);
125 bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
126 bool AllowFunctionTemplates) {
127 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
128 if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
134 TemplateNameKind Sema::isTemplateName(Scope *S,
136 bool hasTemplateKeyword,
138 ParsedType ObjectTypePtr,
139 bool EnteringContext,
140 TemplateTy &TemplateResult,
141 bool &MemberOfUnknownSpecialization) {
142 assert(getLangOpts().CPlusPlus && "No template names in C!");
144 DeclarationName TName;
145 MemberOfUnknownSpecialization = false;
147 switch (Name.getKind()) {
148 case UnqualifiedId::IK_Identifier:
149 TName = DeclarationName(Name.Identifier);
152 case UnqualifiedId::IK_OperatorFunctionId:
153 TName = Context.DeclarationNames.getCXXOperatorName(
154 Name.OperatorFunctionId.Operator);
157 case UnqualifiedId::IK_LiteralOperatorId:
158 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
162 return TNK_Non_template;
165 QualType ObjectType = ObjectTypePtr.get();
167 LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
168 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
169 MemberOfUnknownSpecialization);
170 if (R.empty()) return TNK_Non_template;
171 if (R.isAmbiguous()) {
172 // Suppress diagnostics; we'll redo this lookup later.
173 R.suppressDiagnostics();
175 // FIXME: we might have ambiguous templates, in which case we
176 // should at least parse them properly!
177 return TNK_Non_template;
180 TemplateName Template;
181 TemplateNameKind TemplateKind;
183 unsigned ResultCount = R.end() - R.begin();
184 if (ResultCount > 1) {
185 // We assume that we'll preserve the qualifier from a function
186 // template name in other ways.
187 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
188 TemplateKind = TNK_Function_template;
190 // We'll do this lookup again later.
191 R.suppressDiagnostics();
193 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
195 if (SS.isSet() && !SS.isInvalid()) {
196 NestedNameSpecifier *Qualifier
197 = static_cast<NestedNameSpecifier *>(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 = 0;
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 CorrectionCandidateCallback FilterCCC;
322 FilterCCC.WantTypeSpecifiers = false;
323 FilterCCC.WantExpressionKeywords = false;
324 FilterCCC.WantRemainingKeywords = false;
325 FilterCCC.WantCXXNamedCasts = true;
326 if (TypoCorrection Corrected = CorrectTypo(Found.getLookupNameInfo(),
327 Found.getLookupKind(), S, &SS,
328 FilterCCC, 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 = 0;
423 return Owned(CXXDependentScopeMemberExpr::Create(Context,
424 /*This*/ 0, ThisType,
426 /*Op*/ SourceLocation(),
427 SS.getWithLocInContext(Context),
429 FirstQualifierInScope,
434 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
438 Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
439 SourceLocation TemplateKWLoc,
440 const DeclarationNameInfo &NameInfo,
441 const TemplateArgumentListInfo *TemplateArgs) {
442 return Owned(DependentScopeDeclRefExpr::Create(Context,
443 SS.getWithLocInContext(Context),
449 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
450 /// that the template parameter 'PrevDecl' is being shadowed by a new
451 /// declaration at location Loc. Returns true to indicate that this is
452 /// an error, and false otherwise.
453 void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
454 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
456 // Microsoft Visual C++ permits template parameters to be shadowed.
457 if (getLangOpts().MicrosoftExt)
460 // C++ [temp.local]p4:
461 // A template-parameter shall not be redeclared within its
462 // scope (including nested scopes).
463 Diag(Loc, diag::err_template_param_shadow)
464 << cast<NamedDecl>(PrevDecl)->getDeclName();
465 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
469 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
470 /// the parameter D to reference the templated declaration and return a pointer
471 /// to the template declaration. Otherwise, do nothing to D and return null.
472 TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
473 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
474 D = Temp->getTemplatedDecl();
480 ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
481 SourceLocation EllipsisLoc) const {
482 assert(Kind == Template &&
483 "Only template template arguments can be pack expansions here");
484 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
485 "Template template argument pack expansion without packs");
486 ParsedTemplateArgument Result(*this);
487 Result.EllipsisLoc = EllipsisLoc;
491 static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
492 const ParsedTemplateArgument &Arg) {
494 switch (Arg.getKind()) {
495 case ParsedTemplateArgument::Type: {
497 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
499 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
500 return TemplateArgumentLoc(TemplateArgument(T), DI);
503 case ParsedTemplateArgument::NonType: {
504 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
505 return TemplateArgumentLoc(TemplateArgument(E), E);
508 case ParsedTemplateArgument::Template: {
509 TemplateName Template = Arg.getAsTemplate().get();
510 TemplateArgument TArg;
511 if (Arg.getEllipsisLoc().isValid())
512 TArg = TemplateArgument(Template, Optional<unsigned int>());
515 return TemplateArgumentLoc(TArg,
516 Arg.getScopeSpec().getWithLocInContext(
519 Arg.getEllipsisLoc());
523 llvm_unreachable("Unhandled parsed template argument");
526 /// \brief Translates template arguments as provided by the parser
527 /// into template arguments used by semantic analysis.
528 void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
529 TemplateArgumentListInfo &TemplateArgs) {
530 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
531 TemplateArgs.addArgument(translateTemplateArgument(*this,
535 static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
537 IdentifierInfo *Name) {
538 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
539 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration);
540 if (PrevDecl && PrevDecl->isTemplateParameter())
541 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
544 /// ActOnTypeParameter - Called when a C++ template type parameter
545 /// (e.g., "typename T") has been parsed. Typename specifies whether
546 /// the keyword "typename" was used to declare the type parameter
547 /// (otherwise, "class" was used), and KeyLoc is the location of the
548 /// "class" or "typename" keyword. ParamName is the name of the
549 /// parameter (NULL indicates an unnamed template parameter) and
550 /// ParamNameLoc is the location of the parameter name (if any).
551 /// If the type parameter has a default argument, it will be added
552 /// later via ActOnTypeParameterDefault.
553 Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
554 SourceLocation EllipsisLoc,
555 SourceLocation KeyLoc,
556 IdentifierInfo *ParamName,
557 SourceLocation ParamNameLoc,
558 unsigned Depth, unsigned Position,
559 SourceLocation EqualLoc,
560 ParsedType DefaultArg) {
561 assert(S->isTemplateParamScope() &&
562 "Template type parameter not in template parameter scope!");
563 bool Invalid = false;
565 SourceLocation Loc = ParamNameLoc;
569 TemplateTypeParmDecl *Param
570 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
571 KeyLoc, Loc, Depth, Position, ParamName,
573 Param->setAccess(AS_public);
575 Param->setInvalidDecl();
578 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
580 // Add the template parameter into the current scope.
582 IdResolver.AddDecl(Param);
585 // C++0x [temp.param]p9:
586 // A default template-argument may be specified for any kind of
587 // template-parameter that is not a template parameter pack.
588 if (DefaultArg && Ellipsis) {
589 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
590 DefaultArg = ParsedType();
593 // Handle the default argument, if provided.
595 TypeSourceInfo *DefaultTInfo;
596 GetTypeFromParser(DefaultArg, &DefaultTInfo);
598 assert(DefaultTInfo && "expected source information for type");
600 // Check for unexpanded parameter packs.
601 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
602 UPPC_DefaultArgument))
605 // Check the template argument itself.
606 if (CheckTemplateArgument(Param, DefaultTInfo)) {
607 Param->setInvalidDecl();
611 Param->setDefaultArgument(DefaultTInfo, false);
617 /// \brief Check that the type of a non-type template parameter is
620 /// \returns the (possibly-promoted) parameter type if valid;
621 /// otherwise, produces a diagnostic and returns a NULL type.
623 Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
624 // We don't allow variably-modified types as the type of non-type template
626 if (T->isVariablyModifiedType()) {
627 Diag(Loc, diag::err_variably_modified_nontype_template_param)
632 // C++ [temp.param]p4:
634 // A non-type template-parameter shall have one of the following
635 // (optionally cv-qualified) types:
637 // -- integral or enumeration type,
638 if (T->isIntegralOrEnumerationType() ||
639 // -- pointer to object or pointer to function,
640 T->isPointerType() ||
641 // -- reference to object or reference to function,
642 T->isReferenceType() ||
643 // -- pointer to member,
644 T->isMemberPointerType() ||
645 // -- std::nullptr_t.
646 T->isNullPtrType() ||
647 // If T is a dependent type, we can't do the check now, so we
648 // assume that it is well-formed.
649 T->isDependentType()) {
650 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
651 // are ignored when determining its type.
652 return T.getUnqualifiedType();
655 // C++ [temp.param]p8:
657 // A non-type template-parameter of type "array of T" or
658 // "function returning T" is adjusted to be of type "pointer to
659 // T" or "pointer to function returning T", respectively.
660 else if (T->isArrayType())
661 // FIXME: Keep the type prior to promotion?
662 return Context.getArrayDecayedType(T);
663 else if (T->isFunctionType())
664 // FIXME: Keep the type prior to promotion?
665 return Context.getPointerType(T);
667 Diag(Loc, diag::err_template_nontype_parm_bad_type)
673 Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
676 SourceLocation EqualLoc,
678 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
679 QualType T = TInfo->getType();
681 assert(S->isTemplateParamScope() &&
682 "Non-type template parameter not in template parameter scope!");
683 bool Invalid = false;
685 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
687 T = Context.IntTy; // Recover with an 'int' type.
691 IdentifierInfo *ParamName = D.getIdentifier();
692 bool IsParameterPack = D.hasEllipsis();
693 NonTypeTemplateParmDecl *Param
694 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
696 D.getIdentifierLoc(),
697 Depth, Position, ParamName, T,
698 IsParameterPack, TInfo);
699 Param->setAccess(AS_public);
702 Param->setInvalidDecl();
705 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
708 // Add the template parameter into the current scope.
710 IdResolver.AddDecl(Param);
713 // C++0x [temp.param]p9:
714 // A default template-argument may be specified for any kind of
715 // template-parameter that is not a template parameter pack.
716 if (Default && IsParameterPack) {
717 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
721 // Check the well-formedness of the default template argument, if provided.
723 // Check for unexpanded parameter packs.
724 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
727 TemplateArgument Converted;
728 ExprResult DefaultRes = CheckTemplateArgument(Param, Param->getType(), Default, Converted);
729 if (DefaultRes.isInvalid()) {
730 Param->setInvalidDecl();
733 Default = DefaultRes.take();
735 Param->setDefaultArgument(Default, false);
741 /// ActOnTemplateTemplateParameter - Called when a C++ template template
742 /// parameter (e.g. T in template <template \<typename> class T> class array)
743 /// has been parsed. S is the current scope.
744 Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
745 SourceLocation TmpLoc,
746 TemplateParameterList *Params,
747 SourceLocation EllipsisLoc,
748 IdentifierInfo *Name,
749 SourceLocation NameLoc,
752 SourceLocation EqualLoc,
753 ParsedTemplateArgument Default) {
754 assert(S->isTemplateParamScope() &&
755 "Template template parameter not in template parameter scope!");
757 // Construct the parameter object.
758 bool IsParameterPack = EllipsisLoc.isValid();
759 TemplateTemplateParmDecl *Param =
760 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
761 NameLoc.isInvalid()? TmpLoc : NameLoc,
762 Depth, Position, IsParameterPack,
764 Param->setAccess(AS_public);
766 // If the template template parameter has a name, then link the identifier
767 // into the scope and lookup mechanisms.
769 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
772 IdResolver.AddDecl(Param);
775 if (Params->size() == 0) {
776 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
777 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
778 Param->setInvalidDecl();
781 // C++0x [temp.param]p9:
782 // A default template-argument may be specified for any kind of
783 // template-parameter that is not a template parameter pack.
784 if (IsParameterPack && !Default.isInvalid()) {
785 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
786 Default = ParsedTemplateArgument();
789 if (!Default.isInvalid()) {
790 // Check only that we have a template template argument. We don't want to
791 // try to check well-formedness now, because our template template parameter
792 // might have dependent types in its template parameters, which we wouldn't
793 // be able to match now.
795 // If none of the template template parameter's template arguments mention
796 // other template parameters, we could actually perform more checking here.
797 // However, it isn't worth doing.
798 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
799 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
800 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
801 << DefaultArg.getSourceRange();
805 // Check for unexpanded parameter packs.
806 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
807 DefaultArg.getArgument().getAsTemplate(),
808 UPPC_DefaultArgument))
811 Param->setDefaultArgument(DefaultArg, false);
817 /// ActOnTemplateParameterList - Builds a TemplateParameterList that
818 /// contains the template parameters in Params/NumParams.
819 TemplateParameterList *
820 Sema::ActOnTemplateParameterList(unsigned Depth,
821 SourceLocation ExportLoc,
822 SourceLocation TemplateLoc,
823 SourceLocation LAngleLoc,
824 Decl **Params, unsigned NumParams,
825 SourceLocation RAngleLoc) {
826 if (ExportLoc.isValid())
827 Diag(ExportLoc, diag::warn_template_export_unsupported);
829 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
830 (NamedDecl**)Params, NumParams,
834 static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
836 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
840 Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
841 SourceLocation KWLoc, CXXScopeSpec &SS,
842 IdentifierInfo *Name, SourceLocation NameLoc,
844 TemplateParameterList *TemplateParams,
845 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
846 unsigned NumOuterTemplateParamLists,
847 TemplateParameterList** OuterTemplateParamLists) {
848 assert(TemplateParams && TemplateParams->size() > 0 &&
849 "No template parameters");
850 assert(TUK != TUK_Reference && "Can only declare or define class templates");
851 bool Invalid = false;
853 // Check that we can declare a template here.
854 if (CheckTemplateDeclScope(S, TemplateParams))
857 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
858 assert(Kind != TTK_Enum && "can't build template of enumerated type");
860 // There is no such thing as an unnamed class template.
862 Diag(KWLoc, diag::err_template_unnamed_class);
866 // Find any previous declaration with this name. For a friend with no
867 // scope explicitly specified, we only look for tag declarations (per
868 // C++11 [basic.lookup.elab]p2).
869 DeclContext *SemanticContext;
870 LookupResult Previous(*this, Name, NameLoc,
871 (SS.isEmpty() && TUK == TUK_Friend)
872 ? LookupTagName : LookupOrdinaryName,
874 if (SS.isNotEmpty() && !SS.isInvalid()) {
875 SemanticContext = computeDeclContext(SS, true);
876 if (!SemanticContext) {
877 // FIXME: Horrible, horrible hack! We can't currently represent this
878 // in the AST, and historically we have just ignored such friend
879 // class templates, so don't complain here.
880 Diag(NameLoc, TUK == TUK_Friend
881 ? diag::warn_template_qualified_friend_ignored
882 : diag::err_template_qualified_declarator_no_match)
883 << SS.getScopeRep() << SS.getRange();
884 return TUK != TUK_Friend;
887 if (RequireCompleteDeclContext(SS, SemanticContext))
890 // If we're adding a template to a dependent context, we may need to
891 // rebuilding some of the types used within the template parameter list,
892 // now that we know what the current instantiation is.
893 if (SemanticContext->isDependentContext()) {
894 ContextRAII SavedContext(*this, SemanticContext);
895 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
897 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
898 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
900 LookupQualifiedName(Previous, SemanticContext);
902 SemanticContext = CurContext;
903 LookupName(Previous, S);
906 if (Previous.isAmbiguous())
909 NamedDecl *PrevDecl = 0;
910 if (Previous.begin() != Previous.end())
911 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
913 // If there is a previous declaration with the same name, check
914 // whether this is a valid redeclaration.
915 ClassTemplateDecl *PrevClassTemplate
916 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
918 // We may have found the injected-class-name of a class template,
919 // class template partial specialization, or class template specialization.
920 // In these cases, grab the template that is being defined or specialized.
921 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
922 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
923 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
925 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
926 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
928 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
929 ->getSpecializedTemplate();
933 if (TUK == TUK_Friend) {
934 // C++ [namespace.memdef]p3:
935 // [...] When looking for a prior declaration of a class or a function
936 // declared as a friend, and when the name of the friend class or
937 // function is neither a qualified name nor a template-id, scopes outside
938 // the innermost enclosing namespace scope are not considered.
940 DeclContext *OutermostContext = CurContext;
941 while (!OutermostContext->isFileContext())
942 OutermostContext = OutermostContext->getLookupParent();
945 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
946 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
947 SemanticContext = PrevDecl->getDeclContext();
949 // Declarations in outer scopes don't matter. However, the outermost
950 // context we computed is the semantic context for our new
952 PrevDecl = PrevClassTemplate = 0;
953 SemanticContext = OutermostContext;
955 // Check that the chosen semantic context doesn't already contain a
956 // declaration of this name as a non-tag type.
957 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
959 DeclContext *LookupContext = SemanticContext;
960 while (LookupContext->isTransparentContext())
961 LookupContext = LookupContext->getLookupParent();
962 LookupQualifiedName(Previous, LookupContext);
964 if (Previous.isAmbiguous())
967 if (Previous.begin() != Previous.end())
968 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
971 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
972 PrevDecl = PrevClassTemplate = 0;
974 if (PrevClassTemplate) {
975 // Ensure that the template parameter lists are compatible. Skip this check
976 // for a friend in a dependent context: the template parameter list itself
977 // could be dependent.
978 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
979 !TemplateParameterListsAreEqual(TemplateParams,
980 PrevClassTemplate->getTemplateParameters(),
985 // C++ [temp.class]p4:
986 // In a redeclaration, partial specialization, explicit
987 // specialization or explicit instantiation of a class template,
988 // the class-key shall agree in kind with the original class
989 // template declaration (7.1.5.3).
990 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
991 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
992 TUK == TUK_Definition, KWLoc, *Name)) {
993 Diag(KWLoc, diag::err_use_with_wrong_tag)
995 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
996 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
997 Kind = PrevRecordDecl->getTagKind();
1000 // Check for redefinition of this class template.
1001 if (TUK == TUK_Definition) {
1002 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
1003 Diag(NameLoc, diag::err_redefinition) << Name;
1004 Diag(Def->getLocation(), diag::note_previous_definition);
1005 // FIXME: Would it make sense to try to "forget" the previous
1006 // definition, as part of error recovery?
1010 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
1011 // Maybe we will complain about the shadowed template parameter.
1012 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1013 // Just pretend that we didn't see the previous declaration.
1015 } else if (PrevDecl) {
1017 // A class template shall not have the same name as any other
1018 // template, class, function, object, enumeration, enumerator,
1019 // namespace, or type in the same scope (3.3), except as specified
1021 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1022 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1026 // Check the template parameter list of this declaration, possibly
1027 // merging in the template parameter list from the previous class
1028 // template declaration. Skip this check for a friend in a dependent
1029 // context, because the template parameter list might be dependent.
1030 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1031 CheckTemplateParameterList(
1033 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters() : 0,
1034 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1035 SemanticContext->isDependentContext())
1036 ? TPC_ClassTemplateMember
1037 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1038 : TPC_ClassTemplate))
1042 // If the name of the template was qualified, we must be defining the
1043 // template out-of-line.
1044 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1045 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
1046 : diag::err_member_decl_does_not_match)
1047 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
1052 CXXRecordDecl *NewClass =
1053 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
1055 PrevClassTemplate->getTemplatedDecl() : 0,
1056 /*DelayTypeCreation=*/true);
1057 SetNestedNameSpecifier(NewClass, SS);
1058 if (NumOuterTemplateParamLists > 0)
1059 NewClass->setTemplateParameterListsInfo(Context,
1060 NumOuterTemplateParamLists,
1061 OuterTemplateParamLists);
1063 // Add alignment attributes if necessary; these attributes are checked when
1064 // the ASTContext lays out the structure.
1065 if (TUK == TUK_Definition) {
1066 AddAlignmentAttributesForRecord(NewClass);
1067 AddMsStructLayoutForRecord(NewClass);
1070 ClassTemplateDecl *NewTemplate
1071 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1072 DeclarationName(Name), TemplateParams,
1073 NewClass, PrevClassTemplate);
1074 NewClass->setDescribedClassTemplate(NewTemplate);
1076 if (ModulePrivateLoc.isValid())
1077 NewTemplate->setModulePrivate();
1079 // Build the type for the class template declaration now.
1080 QualType T = NewTemplate->getInjectedClassNameSpecialization();
1081 T = Context.getInjectedClassNameType(NewClass, T);
1082 assert(T->isDependentType() && "Class template type is not dependent?");
1085 // If we are providing an explicit specialization of a member that is a
1086 // class template, make a note of that.
1087 if (PrevClassTemplate &&
1088 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1089 PrevClassTemplate->setMemberSpecialization();
1091 // Set the access specifier.
1092 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
1093 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
1095 // Set the lexical context of these templates
1096 NewClass->setLexicalDeclContext(CurContext);
1097 NewTemplate->setLexicalDeclContext(CurContext);
1099 if (TUK == TUK_Definition)
1100 NewClass->startDefinition();
1103 ProcessDeclAttributeList(S, NewClass, Attr);
1105 if (PrevClassTemplate)
1106 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1108 AddPushedVisibilityAttribute(NewClass);
1110 if (TUK != TUK_Friend)
1111 PushOnScopeChains(NewTemplate, S);
1113 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
1114 NewTemplate->setAccess(PrevClassTemplate->getAccess());
1115 NewClass->setAccess(PrevClassTemplate->getAccess());
1118 NewTemplate->setObjectOfFriendDecl();
1120 // Friend templates are visible in fairly strange ways.
1121 if (!CurContext->isDependentContext()) {
1122 DeclContext *DC = SemanticContext->getRedeclContext();
1123 DC->makeDeclVisibleInContext(NewTemplate);
1124 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1125 PushOnScopeChains(NewTemplate, EnclosingScope,
1126 /* AddToContext = */ false);
1129 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
1130 NewClass->getLocation(),
1132 /*FIXME:*/NewClass->getLocation());
1133 Friend->setAccess(AS_public);
1134 CurContext->addDecl(Friend);
1138 NewTemplate->setInvalidDecl();
1139 NewClass->setInvalidDecl();
1142 ActOnDocumentableDecl(NewTemplate);
1147 /// \brief Diagnose the presence of a default template argument on a
1148 /// template parameter, which is ill-formed in certain contexts.
1150 /// \returns true if the default template argument should be dropped.
1151 static bool DiagnoseDefaultTemplateArgument(Sema &S,
1152 Sema::TemplateParamListContext TPC,
1153 SourceLocation ParamLoc,
1154 SourceRange DefArgRange) {
1156 case Sema::TPC_ClassTemplate:
1157 case Sema::TPC_VarTemplate:
1158 case Sema::TPC_TypeAliasTemplate:
1161 case Sema::TPC_FunctionTemplate:
1162 case Sema::TPC_FriendFunctionTemplateDefinition:
1163 // C++ [temp.param]p9:
1164 // A default template-argument shall not be specified in a
1165 // function template declaration or a function template
1167 // If a friend function template declaration specifies a default
1168 // template-argument, that declaration shall be a definition and shall be
1169 // the only declaration of the function template in the translation unit.
1170 // (C++98/03 doesn't have this wording; see DR226).
1171 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
1172 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1173 : diag::ext_template_parameter_default_in_function_template)
1177 case Sema::TPC_ClassTemplateMember:
1178 // C++0x [temp.param]p9:
1179 // A default template-argument shall not be specified in the
1180 // template-parameter-lists of the definition of a member of a
1181 // class template that appears outside of the member's class.
1182 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1186 case Sema::TPC_FriendClassTemplate:
1187 case Sema::TPC_FriendFunctionTemplate:
1188 // C++ [temp.param]p9:
1189 // A default template-argument shall not be specified in a
1190 // friend template declaration.
1191 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1195 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1196 // for friend function templates if there is only a single
1197 // declaration (and it is a definition). Strange!
1200 llvm_unreachable("Invalid TemplateParamListContext!");
1203 /// \brief Check for unexpanded parameter packs within the template parameters
1204 /// of a template template parameter, recursively.
1205 static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1206 TemplateTemplateParmDecl *TTP) {
1207 // A template template parameter which is a parameter pack is also a pack
1209 if (TTP->isParameterPack())
1212 TemplateParameterList *Params = TTP->getTemplateParameters();
1213 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1214 NamedDecl *P = Params->getParam(I);
1215 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
1216 if (!NTTP->isParameterPack() &&
1217 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
1218 NTTP->getTypeSourceInfo(),
1219 Sema::UPPC_NonTypeTemplateParameterType))
1225 if (TemplateTemplateParmDecl *InnerTTP
1226 = dyn_cast<TemplateTemplateParmDecl>(P))
1227 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1234 /// \brief Checks the validity of a template parameter list, possibly
1235 /// considering the template parameter list from a previous
1238 /// If an "old" template parameter list is provided, it must be
1239 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
1240 /// template parameter list.
1242 /// \param NewParams Template parameter list for a new template
1243 /// declaration. This template parameter list will be updated with any
1244 /// default arguments that are carried through from the previous
1245 /// template parameter list.
1247 /// \param OldParams If provided, template parameter list from a
1248 /// previous declaration of the same template. Default template
1249 /// arguments will be merged from the old template parameter list to
1250 /// the new template parameter list.
1252 /// \param TPC Describes the context in which we are checking the given
1253 /// template parameter list.
1255 /// \returns true if an error occurred, false otherwise.
1256 bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
1257 TemplateParameterList *OldParams,
1258 TemplateParamListContext TPC) {
1259 bool Invalid = false;
1261 // C++ [temp.param]p10:
1262 // The set of default template-arguments available for use with a
1263 // template declaration or definition is obtained by merging the
1264 // default arguments from the definition (if in scope) and all
1265 // declarations in scope in the same way default function
1266 // arguments are (8.3.6).
1267 bool SawDefaultArgument = false;
1268 SourceLocation PreviousDefaultArgLoc;
1270 // Dummy initialization to avoid warnings.
1271 TemplateParameterList::iterator OldParam = NewParams->end();
1273 OldParam = OldParams->begin();
1275 bool RemoveDefaultArguments = false;
1276 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1277 NewParamEnd = NewParams->end();
1278 NewParam != NewParamEnd; ++NewParam) {
1279 // Variables used to diagnose redundant default arguments
1280 bool RedundantDefaultArg = false;
1281 SourceLocation OldDefaultLoc;
1282 SourceLocation NewDefaultLoc;
1284 // Variable used to diagnose missing default arguments
1285 bool MissingDefaultArg = false;
1287 // Variable used to diagnose non-final parameter packs
1288 bool SawParameterPack = false;
1290 if (TemplateTypeParmDecl *NewTypeParm
1291 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
1292 // Check the presence of a default argument here.
1293 if (NewTypeParm->hasDefaultArgument() &&
1294 DiagnoseDefaultTemplateArgument(*this, TPC,
1295 NewTypeParm->getLocation(),
1296 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1298 NewTypeParm->removeDefaultArgument();
1300 // Merge default arguments for template type parameters.
1301 TemplateTypeParmDecl *OldTypeParm
1302 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
1304 if (NewTypeParm->isParameterPack()) {
1305 assert(!NewTypeParm->hasDefaultArgument() &&
1306 "Parameter packs can't have a default argument!");
1307 SawParameterPack = true;
1308 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
1309 NewTypeParm->hasDefaultArgument()) {
1310 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1311 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1312 SawDefaultArgument = true;
1313 RedundantDefaultArg = true;
1314 PreviousDefaultArgLoc = NewDefaultLoc;
1315 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1316 // Merge the default argument from the old declaration to the
1318 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
1320 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1321 } else if (NewTypeParm->hasDefaultArgument()) {
1322 SawDefaultArgument = true;
1323 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1324 } else if (SawDefaultArgument)
1325 MissingDefaultArg = true;
1326 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
1327 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
1328 // Check for unexpanded parameter packs.
1329 if (!NewNonTypeParm->isParameterPack() &&
1330 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
1331 NewNonTypeParm->getTypeSourceInfo(),
1332 UPPC_NonTypeTemplateParameterType)) {
1337 // Check the presence of a default argument here.
1338 if (NewNonTypeParm->hasDefaultArgument() &&
1339 DiagnoseDefaultTemplateArgument(*this, TPC,
1340 NewNonTypeParm->getLocation(),
1341 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1342 NewNonTypeParm->removeDefaultArgument();
1345 // Merge default arguments for non-type template parameters
1346 NonTypeTemplateParmDecl *OldNonTypeParm
1347 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
1348 if (NewNonTypeParm->isParameterPack()) {
1349 assert(!NewNonTypeParm->hasDefaultArgument() &&
1350 "Parameter packs can't have a default argument!");
1351 if (!NewNonTypeParm->isPackExpansion())
1352 SawParameterPack = true;
1353 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
1354 NewNonTypeParm->hasDefaultArgument()) {
1355 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1356 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1357 SawDefaultArgument = true;
1358 RedundantDefaultArg = true;
1359 PreviousDefaultArgLoc = NewDefaultLoc;
1360 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1361 // Merge the default argument from the old declaration to the
1363 // FIXME: We need to create a new kind of "default argument"
1364 // expression that points to a previous non-type template
1366 NewNonTypeParm->setDefaultArgument(
1367 OldNonTypeParm->getDefaultArgument(),
1368 /*Inherited=*/ true);
1369 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1370 } else if (NewNonTypeParm->hasDefaultArgument()) {
1371 SawDefaultArgument = true;
1372 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1373 } else if (SawDefaultArgument)
1374 MissingDefaultArg = true;
1376 TemplateTemplateParmDecl *NewTemplateParm
1377 = cast<TemplateTemplateParmDecl>(*NewParam);
1379 // Check for unexpanded parameter packs, recursively.
1380 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
1385 // Check the presence of a default argument here.
1386 if (NewTemplateParm->hasDefaultArgument() &&
1387 DiagnoseDefaultTemplateArgument(*this, TPC,
1388 NewTemplateParm->getLocation(),
1389 NewTemplateParm->getDefaultArgument().getSourceRange()))
1390 NewTemplateParm->removeDefaultArgument();
1392 // Merge default arguments for template template parameters
1393 TemplateTemplateParmDecl *OldTemplateParm
1394 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
1395 if (NewTemplateParm->isParameterPack()) {
1396 assert(!NewTemplateParm->hasDefaultArgument() &&
1397 "Parameter packs can't have a default argument!");
1398 if (!NewTemplateParm->isPackExpansion())
1399 SawParameterPack = true;
1400 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
1401 NewTemplateParm->hasDefaultArgument()) {
1402 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1403 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
1404 SawDefaultArgument = true;
1405 RedundantDefaultArg = true;
1406 PreviousDefaultArgLoc = NewDefaultLoc;
1407 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1408 // Merge the default argument from the old declaration to the
1410 // FIXME: We need to create a new kind of "default argument" expression
1411 // that points to a previous template template parameter.
1412 NewTemplateParm->setDefaultArgument(
1413 OldTemplateParm->getDefaultArgument(),
1414 /*Inherited=*/ true);
1415 PreviousDefaultArgLoc
1416 = OldTemplateParm->getDefaultArgument().getLocation();
1417 } else if (NewTemplateParm->hasDefaultArgument()) {
1418 SawDefaultArgument = true;
1419 PreviousDefaultArgLoc
1420 = NewTemplateParm->getDefaultArgument().getLocation();
1421 } else if (SawDefaultArgument)
1422 MissingDefaultArg = true;
1425 // C++11 [temp.param]p11:
1426 // If a template parameter of a primary class template or alias template
1427 // is a template parameter pack, it shall be the last template parameter.
1428 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
1429 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
1430 TPC == TPC_TypeAliasTemplate)) {
1431 Diag((*NewParam)->getLocation(),
1432 diag::err_template_param_pack_must_be_last_template_parameter);
1436 if (RedundantDefaultArg) {
1437 // C++ [temp.param]p12:
1438 // A template-parameter shall not be given default arguments
1439 // by two different declarations in the same scope.
1440 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1441 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1443 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
1444 // C++ [temp.param]p11:
1445 // If a template-parameter of a class template has a default
1446 // template-argument, each subsequent template-parameter shall either
1447 // have a default template-argument supplied or be a template parameter
1449 Diag((*NewParam)->getLocation(),
1450 diag::err_template_param_default_arg_missing);
1451 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1453 RemoveDefaultArguments = true;
1456 // If we have an old template parameter list that we're merging
1457 // in, move on to the next parameter.
1462 // We were missing some default arguments at the end of the list, so remove
1463 // all of the default arguments.
1464 if (RemoveDefaultArguments) {
1465 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1466 NewParamEnd = NewParams->end();
1467 NewParam != NewParamEnd; ++NewParam) {
1468 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1469 TTP->removeDefaultArgument();
1470 else if (NonTypeTemplateParmDecl *NTTP
1471 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1472 NTTP->removeDefaultArgument();
1474 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1483 /// A class which looks for a use of a certain level of template
1485 struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1486 typedef RecursiveASTVisitor<DependencyChecker> super;
1491 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1492 NamedDecl *ND = Params->getParam(0);
1493 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1494 Depth = PD->getDepth();
1495 } else if (NonTypeTemplateParmDecl *PD =
1496 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1497 Depth = PD->getDepth();
1499 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1503 bool Matches(unsigned ParmDepth) {
1504 if (ParmDepth >= Depth) {
1511 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1512 return !Matches(T->getDepth());
1515 bool TraverseTemplateName(TemplateName N) {
1516 if (TemplateTemplateParmDecl *PD =
1517 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
1518 if (Matches(PD->getDepth())) return false;
1519 return super::TraverseTemplateName(N);
1522 bool VisitDeclRefExpr(DeclRefExpr *E) {
1523 if (NonTypeTemplateParmDecl *PD =
1524 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl())) {
1525 if (PD->getDepth() == Depth) {
1530 return super::VisitDeclRefExpr(E);
1533 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1534 return TraverseType(T->getInjectedSpecializationType());
1539 /// Determines whether a given type depends on the given parameter
1542 DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
1543 DependencyChecker Checker(Params);
1544 Checker.TraverseType(T);
1545 return Checker.Match;
1548 // Find the source range corresponding to the named type in the given
1549 // nested-name-specifier, if any.
1550 static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
1552 const CXXScopeSpec &SS) {
1553 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
1554 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1555 if (const Type *CurType = NNS->getAsType()) {
1556 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1557 return NNSLoc.getTypeLoc().getSourceRange();
1561 NNSLoc = NNSLoc.getPrefix();
1564 return SourceRange();
1567 /// \brief Match the given template parameter lists to the given scope
1568 /// specifier, returning the template parameter list that applies to the
1571 /// \param DeclStartLoc the start of the declaration that has a scope
1572 /// specifier or a template parameter list.
1574 /// \param DeclLoc The location of the declaration itself.
1576 /// \param SS the scope specifier that will be matched to the given template
1577 /// parameter lists. This scope specifier precedes a qualified name that is
1580 /// \param ParamLists the template parameter lists, from the outermost to the
1581 /// innermost template parameter lists.
1583 /// \param IsFriend Whether to apply the slightly different rules for
1584 /// matching template parameters to scope specifiers in friend
1587 /// \param IsExplicitSpecialization will be set true if the entity being
1588 /// declared is an explicit specialization, false otherwise.
1590 /// \returns the template parameter list, if any, that corresponds to the
1591 /// name that is preceded by the scope specifier @p SS. This template
1592 /// parameter list may have template parameters (if we're declaring a
1593 /// template) or may have no template parameters (if we're declaring a
1594 /// template specialization), or may be NULL (if what we're declaring isn't
1595 /// itself a template).
1596 TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
1597 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
1598 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
1599 bool &IsExplicitSpecialization, bool &Invalid) {
1600 IsExplicitSpecialization = false;
1603 // The sequence of nested types to which we will match up the template
1604 // parameter lists. We first build this list by starting with the type named
1605 // by the nested-name-specifier and walking out until we run out of types.
1606 SmallVector<QualType, 4> NestedTypes;
1608 if (SS.getScopeRep()) {
1609 if (CXXRecordDecl *Record
1610 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1611 T = Context.getTypeDeclType(Record);
1613 T = QualType(SS.getScopeRep()->getAsType(), 0);
1616 // If we found an explicit specialization that prevents us from needing
1617 // 'template<>' headers, this will be set to the location of that
1618 // explicit specialization.
1619 SourceLocation ExplicitSpecLoc;
1621 while (!T.isNull()) {
1622 NestedTypes.push_back(T);
1624 // Retrieve the parent of a record type.
1625 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1626 // If this type is an explicit specialization, we're done.
1627 if (ClassTemplateSpecializationDecl *Spec
1628 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1629 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
1630 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1631 ExplicitSpecLoc = Spec->getLocation();
1634 } else if (Record->getTemplateSpecializationKind()
1635 == TSK_ExplicitSpecialization) {
1636 ExplicitSpecLoc = Record->getLocation();
1640 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1641 T = Context.getTypeDeclType(Parent);
1647 if (const TemplateSpecializationType *TST
1648 = T->getAs<TemplateSpecializationType>()) {
1649 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1650 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1651 T = Context.getTypeDeclType(Parent);
1658 // Look one step prior in a dependent template specialization type.
1659 if (const DependentTemplateSpecializationType *DependentTST
1660 = T->getAs<DependentTemplateSpecializationType>()) {
1661 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1662 T = QualType(NNS->getAsType(), 0);
1668 // Look one step prior in a dependent name type.
1669 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1670 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1671 T = QualType(NNS->getAsType(), 0);
1677 // Retrieve the parent of an enumeration type.
1678 if (const EnumType *EnumT = T->getAs<EnumType>()) {
1679 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1681 EnumDecl *Enum = EnumT->getDecl();
1683 // Get to the parent type.
1684 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1685 T = Context.getTypeDeclType(Parent);
1693 // Reverse the nested types list, since we want to traverse from the outermost
1694 // to the innermost while checking template-parameter-lists.
1695 std::reverse(NestedTypes.begin(), NestedTypes.end());
1697 // C++0x [temp.expl.spec]p17:
1698 // A member or a member template may be nested within many
1699 // enclosing class templates. In an explicit specialization for
1700 // such a member, the member declaration shall be preceded by a
1701 // template<> for each enclosing class template that is
1702 // explicitly specialized.
1703 bool SawNonEmptyTemplateParameterList = false;
1704 unsigned ParamIdx = 0;
1705 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
1707 T = NestedTypes[TypeIdx];
1709 // Whether we expect a 'template<>' header.
1710 bool NeedEmptyTemplateHeader = false;
1712 // Whether we expect a template header with parameters.
1713 bool NeedNonemptyTemplateHeader = false;
1715 // For a dependent type, the set of template parameters that we
1717 TemplateParameterList *ExpectedTemplateParams = 0;
1719 // C++0x [temp.expl.spec]p15:
1720 // A member or a member template may be nested within many enclosing
1721 // class templates. In an explicit specialization for such a member, the
1722 // member declaration shall be preceded by a template<> for each
1723 // enclosing class template that is explicitly specialized.
1724 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1725 if (ClassTemplatePartialSpecializationDecl *Partial
1726 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1727 ExpectedTemplateParams = Partial->getTemplateParameters();
1728 NeedNonemptyTemplateHeader = true;
1729 } else if (Record->isDependentType()) {
1730 if (Record->getDescribedClassTemplate()) {
1731 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1732 ->getTemplateParameters();
1733 NeedNonemptyTemplateHeader = true;
1735 } else if (ClassTemplateSpecializationDecl *Spec
1736 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1737 // C++0x [temp.expl.spec]p4:
1738 // Members of an explicitly specialized class template are defined
1739 // in the same manner as members of normal classes, and not using
1740 // the template<> syntax.
1741 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
1742 NeedEmptyTemplateHeader = true;
1745 } else if (Record->getTemplateSpecializationKind()) {
1746 if (Record->getTemplateSpecializationKind()
1747 != TSK_ExplicitSpecialization &&
1748 TypeIdx == NumTypes - 1)
1749 IsExplicitSpecialization = true;
1753 } else if (const TemplateSpecializationType *TST
1754 = T->getAs<TemplateSpecializationType>()) {
1755 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1756 ExpectedTemplateParams = Template->getTemplateParameters();
1757 NeedNonemptyTemplateHeader = true;
1759 } else if (T->getAs<DependentTemplateSpecializationType>()) {
1760 // FIXME: We actually could/should check the template arguments here
1761 // against the corresponding template parameter list.
1762 NeedNonemptyTemplateHeader = false;
1765 // C++ [temp.expl.spec]p16:
1766 // In an explicit specialization declaration for a member of a class
1767 // template or a member template that ap- pears in namespace scope, the
1768 // member template and some of its enclosing class templates may remain
1769 // unspecialized, except that the declaration shall not explicitly
1770 // specialize a class member template if its en- closing class templates
1771 // are not explicitly specialized as well.
1772 if (ParamIdx < ParamLists.size()) {
1773 if (ParamLists[ParamIdx]->size() == 0) {
1774 if (SawNonEmptyTemplateParameterList) {
1775 Diag(DeclLoc, diag::err_specialize_member_of_template)
1776 << ParamLists[ParamIdx]->getSourceRange();
1778 IsExplicitSpecialization = false;
1782 SawNonEmptyTemplateParameterList = true;
1785 if (NeedEmptyTemplateHeader) {
1786 // If we're on the last of the types, and we need a 'template<>' header
1787 // here, then it's an explicit specialization.
1788 if (TypeIdx == NumTypes - 1)
1789 IsExplicitSpecialization = true;
1791 if (ParamIdx < ParamLists.size()) {
1792 if (ParamLists[ParamIdx]->size() > 0) {
1793 // The header has template parameters when it shouldn't. Complain.
1794 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1795 diag::err_template_param_list_matches_nontemplate)
1797 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
1798 ParamLists[ParamIdx]->getRAngleLoc())
1799 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1804 // Consume this template header.
1810 // We don't have a template header, but we should.
1811 SourceLocation ExpectedTemplateLoc;
1812 if (!ParamLists.empty())
1813 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
1815 ExpectedTemplateLoc = DeclStartLoc;
1817 Diag(DeclLoc, diag::err_template_spec_needs_header)
1818 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS)
1819 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
1825 if (NeedNonemptyTemplateHeader) {
1826 // In friend declarations we can have template-ids which don't
1827 // depend on the corresponding template parameter lists. But
1828 // assume that empty parameter lists are supposed to match this
1830 if (IsFriend && T->isDependentType()) {
1831 if (ParamIdx < ParamLists.size() &&
1832 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
1833 ExpectedTemplateParams = 0;
1838 if (ParamIdx < ParamLists.size()) {
1839 // Check the template parameter list, if we can.
1840 if (ExpectedTemplateParams &&
1841 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
1842 ExpectedTemplateParams,
1843 true, TPL_TemplateMatch))
1847 CheckTemplateParameterList(ParamLists[ParamIdx], 0,
1848 TPC_ClassTemplateMember))
1855 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
1857 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1863 // If there were at least as many template-ids as there were template
1864 // parameter lists, then there are no template parameter lists remaining for
1865 // the declaration itself.
1866 if (ParamIdx >= ParamLists.size())
1869 // If there were too many template parameter lists, complain about that now.
1870 if (ParamIdx < ParamLists.size() - 1) {
1871 bool HasAnyExplicitSpecHeader = false;
1872 bool AllExplicitSpecHeaders = true;
1873 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
1874 if (ParamLists[I]->size() == 0)
1875 HasAnyExplicitSpecHeader = true;
1877 AllExplicitSpecHeaders = false;
1880 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1881 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
1882 : diag::err_template_spec_extra_headers)
1883 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1884 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
1886 // If there was a specialization somewhere, such that 'template<>' is
1887 // not required, and there were any 'template<>' headers, note where the
1888 // specialization occurred.
1889 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
1890 Diag(ExplicitSpecLoc,
1891 diag::note_explicit_template_spec_does_not_need_header)
1892 << NestedTypes.back();
1894 // We have a template parameter list with no corresponding scope, which
1895 // means that the resulting template declaration can't be instantiated
1896 // properly (we'll end up with dependent nodes when we shouldn't).
1897 if (!AllExplicitSpecHeaders)
1901 // C++ [temp.expl.spec]p16:
1902 // In an explicit specialization declaration for a member of a class
1903 // template or a member template that ap- pears in namespace scope, the
1904 // member template and some of its enclosing class templates may remain
1905 // unspecialized, except that the declaration shall not explicitly
1906 // specialize a class member template if its en- closing class templates
1907 // are not explicitly specialized as well.
1908 if (ParamLists.back()->size() == 0 && SawNonEmptyTemplateParameterList) {
1909 Diag(DeclLoc, diag::err_specialize_member_of_template)
1910 << ParamLists[ParamIdx]->getSourceRange();
1912 IsExplicitSpecialization = false;
1916 // Return the last template parameter list, which corresponds to the
1917 // entity being declared.
1918 return ParamLists.back();
1921 void Sema::NoteAllFoundTemplates(TemplateName Name) {
1922 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
1923 Diag(Template->getLocation(), diag::note_template_declared_here)
1924 << (isa<FunctionTemplateDecl>(Template)
1926 : isa<ClassTemplateDecl>(Template)
1928 : isa<VarTemplateDecl>(Template)
1930 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
1931 << Template->getDeclName();
1935 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
1936 for (OverloadedTemplateStorage::iterator I = OST->begin(),
1939 Diag((*I)->getLocation(), diag::note_template_declared_here)
1940 << 0 << (*I)->getDeclName();
1946 QualType Sema::CheckTemplateIdType(TemplateName Name,
1947 SourceLocation TemplateLoc,
1948 TemplateArgumentListInfo &TemplateArgs) {
1949 DependentTemplateName *DTN
1950 = Name.getUnderlying().getAsDependentTemplateName();
1951 if (DTN && DTN->isIdentifier())
1952 // When building a template-id where the template-name is dependent,
1953 // assume the template is a type template. Either our assumption is
1954 // correct, or the code is ill-formed and will be diagnosed when the
1955 // dependent name is substituted.
1956 return Context.getDependentTemplateSpecializationType(ETK_None,
1957 DTN->getQualifier(),
1958 DTN->getIdentifier(),
1961 TemplateDecl *Template = Name.getAsTemplateDecl();
1962 if (!Template || isa<FunctionTemplateDecl>(Template)) {
1963 // We might have a substituted template template parameter pack. If so,
1964 // build a template specialization type for it.
1965 if (Name.getAsSubstTemplateTemplateParmPack())
1966 return Context.getTemplateSpecializationType(Name, TemplateArgs);
1968 Diag(TemplateLoc, diag::err_template_id_not_a_type)
1970 NoteAllFoundTemplates(Name);
1974 // Check that the template argument list is well-formed for this
1976 SmallVector<TemplateArgument, 4> Converted;
1977 bool ExpansionIntoFixedList = false;
1978 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
1979 false, Converted, &ExpansionIntoFixedList))
1984 bool InstantiationDependent = false;
1985 TypeAliasTemplateDecl *AliasTemplate = 0;
1986 if (!ExpansionIntoFixedList &&
1987 (AliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Template))) {
1988 // Find the canonical type for this type alias template specialization.
1989 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
1990 if (Pattern->isInvalidDecl())
1993 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
1994 Converted.data(), Converted.size());
1996 // Only substitute for the innermost template argument list.
1997 MultiLevelTemplateArgumentList TemplateArgLists;
1998 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
1999 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2000 for (unsigned I = 0; I < Depth; ++I)
2001 TemplateArgLists.addOuterTemplateArguments(None);
2003 LocalInstantiationScope Scope(*this);
2004 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
2005 if (Inst.isInvalid())
2008 CanonType = SubstType(Pattern->getUnderlyingType(),
2009 TemplateArgLists, AliasTemplate->getLocation(),
2010 AliasTemplate->getDeclName());
2011 if (CanonType.isNull())
2013 } else if (Name.isDependent() ||
2014 TemplateSpecializationType::anyDependentTemplateArguments(
2015 TemplateArgs, InstantiationDependent)) {
2016 // This class template specialization is a dependent
2017 // type. Therefore, its canonical type is another class template
2018 // specialization type that contains all of the converted
2019 // arguments in canonical form. This ensures that, e.g., A<T> and
2020 // A<T, T> have identical types when A is declared as:
2022 // template<typename T, typename U = T> struct A;
2023 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
2024 CanonType = Context.getTemplateSpecializationType(CanonName,
2028 // FIXME: CanonType is not actually the canonical type, and unfortunately
2029 // it is a TemplateSpecializationType that we will never use again.
2030 // In the future, we need to teach getTemplateSpecializationType to only
2031 // build the canonical type and return that to us.
2032 CanonType = Context.getCanonicalType(CanonType);
2034 // This might work out to be a current instantiation, in which
2035 // case the canonical type needs to be the InjectedClassNameType.
2037 // TODO: in theory this could be a simple hashtable lookup; most
2038 // changes to CurContext don't change the set of current
2040 if (isa<ClassTemplateDecl>(Template)) {
2041 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2042 // If we get out to a namespace, we're done.
2043 if (Ctx->isFileContext()) break;
2045 // If this isn't a record, keep looking.
2046 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2047 if (!Record) continue;
2049 // Look for one of the two cases with InjectedClassNameTypes
2050 // and check whether it's the same template.
2051 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2052 !Record->getDescribedClassTemplate())
2055 // Fetch the injected class name type and check whether its
2056 // injected type is equal to the type we just built.
2057 QualType ICNT = Context.getTypeDeclType(Record);
2058 QualType Injected = cast<InjectedClassNameType>(ICNT)
2059 ->getInjectedSpecializationType();
2061 if (CanonType != Injected->getCanonicalTypeInternal())
2064 // If so, the canonical type of this TST is the injected
2065 // class name type of the record we just found.
2066 assert(ICNT.isCanonical());
2071 } else if (ClassTemplateDecl *ClassTemplate
2072 = dyn_cast<ClassTemplateDecl>(Template)) {
2073 // Find the class template specialization declaration that
2074 // corresponds to these arguments.
2075 void *InsertPos = 0;
2076 ClassTemplateSpecializationDecl *Decl
2077 = ClassTemplate->findSpecialization(Converted.data(), Converted.size(),
2080 // This is the first time we have referenced this class template
2081 // specialization. Create the canonical declaration and add it to
2082 // the set of specializations.
2083 Decl = ClassTemplateSpecializationDecl::Create(Context,
2084 ClassTemplate->getTemplatedDecl()->getTagKind(),
2085 ClassTemplate->getDeclContext(),
2086 ClassTemplate->getTemplatedDecl()->getLocStart(),
2087 ClassTemplate->getLocation(),
2090 Converted.size(), 0);
2091 ClassTemplate->AddSpecialization(Decl, InsertPos);
2092 if (ClassTemplate->isOutOfLine())
2093 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
2096 // Diagnose uses of this specialization.
2097 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2099 CanonType = Context.getTypeDeclType(Decl);
2100 assert(isa<RecordType>(CanonType) &&
2101 "type of non-dependent specialization is not a RecordType");
2104 // Build the fully-sugared type for this class template
2105 // specialization, which refers back to the class template
2106 // specialization we created or found.
2107 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
2111 Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
2112 TemplateTy TemplateD, SourceLocation TemplateLoc,
2113 SourceLocation LAngleLoc,
2114 ASTTemplateArgsPtr TemplateArgsIn,
2115 SourceLocation RAngleLoc,
2116 bool IsCtorOrDtorName) {
2120 TemplateName Template = TemplateD.get();
2122 // Translate the parser's template argument list in our AST format.
2123 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2124 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2126 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2128 = Context.getDependentTemplateSpecializationType(ETK_None,
2129 DTN->getQualifier(),
2130 DTN->getIdentifier(),
2132 // Build type-source information.
2134 DependentTemplateSpecializationTypeLoc SpecTL
2135 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2136 SpecTL.setElaboratedKeywordLoc(SourceLocation());
2137 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
2138 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2139 SpecTL.setTemplateNameLoc(TemplateLoc);
2140 SpecTL.setLAngleLoc(LAngleLoc);
2141 SpecTL.setRAngleLoc(RAngleLoc);
2142 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2143 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2144 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2147 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2149 if (Result.isNull())
2152 // Build type-source information.
2154 TemplateSpecializationTypeLoc SpecTL
2155 = TLB.push<TemplateSpecializationTypeLoc>(Result);
2156 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2157 SpecTL.setTemplateNameLoc(TemplateLoc);
2158 SpecTL.setLAngleLoc(LAngleLoc);
2159 SpecTL.setRAngleLoc(RAngleLoc);
2160 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2161 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
2163 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2164 // constructor or destructor name (in such a case, the scope specifier
2165 // will be attached to the enclosing Decl or Expr node).
2166 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
2167 // Create an elaborated-type-specifier containing the nested-name-specifier.
2168 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2169 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
2170 ElabTL.setElaboratedKeywordLoc(SourceLocation());
2171 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2174 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
2177 TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
2178 TypeSpecifierType TagSpec,
2179 SourceLocation TagLoc,
2181 SourceLocation TemplateKWLoc,
2182 TemplateTy TemplateD,
2183 SourceLocation TemplateLoc,
2184 SourceLocation LAngleLoc,
2185 ASTTemplateArgsPtr TemplateArgsIn,
2186 SourceLocation RAngleLoc) {
2187 TemplateName Template = TemplateD.get();
2189 // Translate the parser's template argument list in our AST format.
2190 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2191 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2193 // Determine the tag kind
2194 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
2195 ElaboratedTypeKeyword Keyword
2196 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
2198 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2199 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
2200 DTN->getQualifier(),
2201 DTN->getIdentifier(),
2204 // Build type-source information.
2206 DependentTemplateSpecializationTypeLoc SpecTL
2207 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2208 SpecTL.setElaboratedKeywordLoc(TagLoc);
2209 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
2210 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2211 SpecTL.setTemplateNameLoc(TemplateLoc);
2212 SpecTL.setLAngleLoc(LAngleLoc);
2213 SpecTL.setRAngleLoc(RAngleLoc);
2214 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2215 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2216 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2219 if (TypeAliasTemplateDecl *TAT =
2220 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2221 // C++0x [dcl.type.elab]p2:
2222 // If the identifier resolves to a typedef-name or the simple-template-id
2223 // resolves to an alias template specialization, the
2224 // elaborated-type-specifier is ill-formed.
2225 Diag(TemplateLoc, diag::err_tag_reference_non_tag) << 4;
2226 Diag(TAT->getLocation(), diag::note_declared_at);
2229 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2230 if (Result.isNull())
2231 return TypeResult(true);
2233 // Check the tag kind
2234 if (const RecordType *RT = Result->getAs<RecordType>()) {
2235 RecordDecl *D = RT->getDecl();
2237 IdentifierInfo *Id = D->getIdentifier();
2238 assert(Id && "templated class must have an identifier");
2240 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
2242 Diag(TagLoc, diag::err_use_with_wrong_tag)
2244 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
2245 Diag(D->getLocation(), diag::note_previous_use);
2249 // Provide source-location information for the template specialization.
2251 TemplateSpecializationTypeLoc SpecTL
2252 = TLB.push<TemplateSpecializationTypeLoc>(Result);
2253 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2254 SpecTL.setTemplateNameLoc(TemplateLoc);
2255 SpecTL.setLAngleLoc(LAngleLoc);
2256 SpecTL.setRAngleLoc(RAngleLoc);
2257 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2258 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
2260 // Construct an elaborated type containing the nested-name-specifier (if any)
2262 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2263 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
2264 ElabTL.setElaboratedKeywordLoc(TagLoc);
2265 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2266 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
2269 static bool CheckTemplatePartialSpecializationArgs(
2270 Sema &S, TemplateParameterList *TemplateParams,
2271 SmallVectorImpl<TemplateArgument> &TemplateArgs);
2273 static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
2274 NamedDecl *PrevDecl,
2276 bool IsPartialSpecialization);
2278 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
2280 static bool isTemplateArgumentTemplateParameter(
2281 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
2282 switch (Arg.getKind()) {
2283 case TemplateArgument::Null:
2284 case TemplateArgument::NullPtr:
2285 case TemplateArgument::Integral:
2286 case TemplateArgument::Declaration:
2287 case TemplateArgument::Pack:
2288 case TemplateArgument::TemplateExpansion:
2291 case TemplateArgument::Type: {
2292 QualType Type = Arg.getAsType();
2293 const TemplateTypeParmType *TPT =
2294 Arg.getAsType()->getAs<TemplateTypeParmType>();
2295 return TPT && !Type.hasQualifiers() &&
2296 TPT->getDepth() == Depth && TPT->getIndex() == Index;
2299 case TemplateArgument::Expression: {
2300 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
2301 if (!DRE || !DRE->getDecl())
2303 const NonTypeTemplateParmDecl *NTTP =
2304 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2305 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
2308 case TemplateArgument::Template:
2309 const TemplateTemplateParmDecl *TTP =
2310 dyn_cast_or_null<TemplateTemplateParmDecl>(
2311 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
2312 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
2314 llvm_unreachable("unexpected kind of template argument");
2317 static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
2318 ArrayRef<TemplateArgument> Args) {
2319 if (Params->size() != Args.size())
2322 unsigned Depth = Params->getDepth();
2324 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2325 TemplateArgument Arg = Args[I];
2327 // If the parameter is a pack expansion, the argument must be a pack
2328 // whose only element is a pack expansion.
2329 if (Params->getParam(I)->isParameterPack()) {
2330 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
2331 !Arg.pack_begin()->isPackExpansion())
2333 Arg = Arg.pack_begin()->getPackExpansionPattern();
2336 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
2343 DeclResult Sema::ActOnVarTemplateSpecialization(
2344 Scope *S, VarTemplateDecl *VarTemplate, Declarator &D, TypeSourceInfo *DI,
2345 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
2346 VarDecl::StorageClass SC, bool IsPartialSpecialization) {
2347 assert(VarTemplate && "A variable template id without template?");
2349 // D must be variable template id.
2350 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
2351 "Variable template specialization is declared with a template it.");
2353 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
2354 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
2355 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
2356 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
2357 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
2358 TemplateId->NumArgs);
2359 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2360 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
2361 TemplateName Name(VarTemplate);
2363 // Check for unexpanded parameter packs in any of the template arguments.
2364 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2365 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
2366 UPPC_PartialSpecialization))
2369 // Check that the template argument list is well-formed for this
2371 SmallVector<TemplateArgument, 4> Converted;
2372 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
2376 // Check that the type of this variable template specialization
2377 // matches the expected type.
2378 TypeSourceInfo *ExpectedDI;
2380 // Do substitution on the type of the declaration
2381 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
2382 Converted.data(), Converted.size());
2383 InstantiatingTemplate Inst(*this, TemplateKWLoc, VarTemplate);
2384 if (Inst.isInvalid())
2386 VarDecl *Templated = VarTemplate->getTemplatedDecl();
2388 SubstType(Templated->getTypeSourceInfo(),
2389 MultiLevelTemplateArgumentList(TemplateArgList),
2390 Templated->getTypeSpecStartLoc(), Templated->getDeclName());
2395 // Find the variable template (partial) specialization declaration that
2396 // corresponds to these arguments.
2397 if (IsPartialSpecialization) {
2398 if (CheckTemplatePartialSpecializationArgs(
2399 *this, VarTemplate->getTemplateParameters(), Converted))
2402 bool InstantiationDependent;
2403 if (!Name.isDependent() &&
2404 !TemplateSpecializationType::anyDependentTemplateArguments(
2405 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
2406 InstantiationDependent)) {
2407 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
2408 << VarTemplate->getDeclName();
2409 IsPartialSpecialization = false;
2412 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
2414 // C++ [temp.class.spec]p9b3:
2416 // -- The argument list of the specialization shall not be identical
2417 // to the implicit argument list of the primary template.
2418 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2419 << /*variable template*/ 1
2420 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
2421 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
2422 // FIXME: Recover from this by treating the declaration as a redeclaration
2423 // of the primary template.
2428 void *InsertPos = 0;
2429 VarTemplateSpecializationDecl *PrevDecl = 0;
2431 if (IsPartialSpecialization)
2432 // FIXME: Template parameter list matters too
2433 PrevDecl = VarTemplate->findPartialSpecialization(
2434 Converted.data(), Converted.size(), InsertPos);
2436 PrevDecl = VarTemplate->findSpecialization(Converted.data(),
2437 Converted.size(), InsertPos);
2439 VarTemplateSpecializationDecl *Specialization = 0;
2441 // Check whether we can declare a variable template specialization in
2442 // the current scope.
2443 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
2445 IsPartialSpecialization))
2448 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2449 // Since the only prior variable template specialization with these
2450 // arguments was referenced but not declared, reuse that
2451 // declaration node as our own, updating its source location and
2452 // the list of outer template parameters to reflect our new declaration.
2453 Specialization = PrevDecl;
2454 Specialization->setLocation(TemplateNameLoc);
2456 } else if (IsPartialSpecialization) {
2457 // Create a new class template partial specialization declaration node.
2458 VarTemplatePartialSpecializationDecl *PrevPartial =
2459 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
2460 VarTemplatePartialSpecializationDecl *Partial =
2461 VarTemplatePartialSpecializationDecl::Create(
2462 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
2463 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
2464 Converted.data(), Converted.size(), TemplateArgs);
2467 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
2468 Specialization = Partial;
2470 // If we are providing an explicit specialization of a member variable
2471 // template specialization, make a note of that.
2472 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
2473 PrevPartial->setMemberSpecialization();
2475 // Check that all of the template parameters of the variable template
2476 // partial specialization are deducible from the template
2477 // arguments. If not, this variable template partial specialization
2478 // will never be used.
2479 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
2480 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2481 TemplateParams->getDepth(), DeducibleParams);
2483 if (!DeducibleParams.all()) {
2484 unsigned NumNonDeducible =
2485 DeducibleParams.size() - DeducibleParams.count();
2486 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2487 << /*variable template*/ 1 << (NumNonDeducible > 1)
2488 << SourceRange(TemplateNameLoc, RAngleLoc);
2489 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2490 if (!DeducibleParams[I]) {
2491 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2492 if (Param->getDeclName())
2493 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2494 << Param->getDeclName();
2496 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2502 // Create a new class template specialization declaration node for
2503 // this explicit specialization or friend declaration.
2504 Specialization = VarTemplateSpecializationDecl::Create(
2505 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
2506 VarTemplate, DI->getType(), DI, SC, Converted.data(), Converted.size());
2507 Specialization->setTemplateArgsInfo(TemplateArgs);
2510 VarTemplate->AddSpecialization(Specialization, InsertPos);
2513 // C++ [temp.expl.spec]p6:
2514 // If a template, a member template or the member of a class template is
2515 // explicitly specialized then that specialization shall be declared
2516 // before the first use of that specialization that would cause an implicit
2517 // instantiation to take place, in every translation unit in which such a
2518 // use occurs; no diagnostic is required.
2519 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
2521 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
2522 // Is there any previous explicit specialization declaration?
2523 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
2530 SourceRange Range(TemplateNameLoc, RAngleLoc);
2531 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
2534 Diag(PrevDecl->getPointOfInstantiation(),
2535 diag::note_instantiation_required_here)
2536 << (PrevDecl->getTemplateSpecializationKind() !=
2537 TSK_ImplicitInstantiation);
2542 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
2543 Specialization->setLexicalDeclContext(CurContext);
2545 // Add the specialization into its lexical context, so that it can
2546 // be seen when iterating through the list of declarations in that
2547 // context. However, specializations are not found by name lookup.
2548 CurContext->addDecl(Specialization);
2550 // Note that this is an explicit specialization.
2551 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2554 // Check that this isn't a redefinition of this specialization,
2555 // merging with previous declarations.
2556 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
2558 PrevSpec.addDecl(PrevDecl);
2559 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
2560 } else if (Specialization->isStaticDataMember() &&
2561 Specialization->isOutOfLine()) {
2562 Specialization->setAccess(VarTemplate->getAccess());
2565 // Link instantiations of static data members back to the template from
2566 // which they were instantiated.
2567 if (Specialization->isStaticDataMember())
2568 Specialization->setInstantiationOfStaticDataMember(
2569 VarTemplate->getTemplatedDecl(),
2570 Specialization->getSpecializationKind());
2572 return Specialization;
2576 /// \brief A partial specialization whose template arguments have matched
2577 /// a given template-id.
2578 struct PartialSpecMatchResult {
2579 VarTemplatePartialSpecializationDecl *Partial;
2580 TemplateArgumentList *Args;
2585 Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
2586 SourceLocation TemplateNameLoc,
2587 const TemplateArgumentListInfo &TemplateArgs) {
2588 assert(Template && "A variable template id without template?");
2590 // Check that the template argument list is well-formed for this template.
2591 SmallVector<TemplateArgument, 4> Converted;
2592 bool ExpansionIntoFixedList = false;
2593 if (CheckTemplateArgumentList(
2594 Template, TemplateNameLoc,
2595 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
2596 Converted, &ExpansionIntoFixedList))
2599 // Find the variable template specialization declaration that
2600 // corresponds to these arguments.
2601 void *InsertPos = 0;
2602 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
2603 Converted.data(), Converted.size(), InsertPos))
2604 // If we already have a variable template specialization, return it.
2607 // This is the first time we have referenced this variable template
2608 // specialization. Create the canonical declaration and add it to
2609 // the set of specializations, based on the closest partial specialization
2610 // that it represents. That is,
2611 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
2612 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
2613 Converted.data(), Converted.size());
2614 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
2615 bool AmbiguousPartialSpec = false;
2616 typedef PartialSpecMatchResult MatchResult;
2617 SmallVector<MatchResult, 4> Matched;
2618 SourceLocation PointOfInstantiation = TemplateNameLoc;
2619 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
2621 // 1. Attempt to find the closest partial specialization that this
2622 // specializes, if any.
2623 // If any of the template arguments is dependent, then this is probably
2624 // a placeholder for an incomplete declarative context; which must be
2625 // complete by instantiation time. Thus, do not search through the partial
2626 // specializations yet.
2627 // TODO: Unify with InstantiateClassTemplateSpecialization()?
2628 // Perhaps better after unification of DeduceTemplateArguments() and
2629 // getMoreSpecializedPartialSpecialization().
2630 bool InstantiationDependent = false;
2631 if (!TemplateSpecializationType::anyDependentTemplateArguments(
2632 TemplateArgs, InstantiationDependent)) {
2634 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2635 Template->getPartialSpecializations(PartialSpecs);
2637 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2638 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2639 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2641 if (TemplateDeductionResult Result =
2642 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
2643 // Store the failed-deduction information for use in diagnostics, later.
2644 // TODO: Actually use the failed-deduction info?
2645 FailedCandidates.addCandidate()
2646 .set(Partial, MakeDeductionFailureInfo(Context, Result, Info));
2649 Matched.push_back(PartialSpecMatchResult());
2650 Matched.back().Partial = Partial;
2651 Matched.back().Args = Info.take();
2655 // If we're dealing with a member template where the template parameters
2656 // have been instantiated, this provides the original template parameters
2657 // from which the member template's parameters were instantiated.
2658 SmallVector<const NamedDecl *, 4> InstantiatedTemplateParameters;
2660 if (Matched.size() >= 1) {
2661 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
2662 if (Matched.size() == 1) {
2663 // -- If exactly one matching specialization is found, the
2664 // instantiation is generated from that specialization.
2665 // We don't need to do anything for this.
2667 // -- If more than one matching specialization is found, the
2668 // partial order rules (14.5.4.2) are used to determine
2669 // whether one of the specializations is more specialized
2670 // than the others. If none of the specializations is more
2671 // specialized than all of the other matching
2672 // specializations, then the use of the variable template is
2673 // ambiguous and the program is ill-formed.
2674 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
2675 PEnd = Matched.end();
2677 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2678 PointOfInstantiation) ==
2683 // Determine if the best partial specialization is more specialized than
2685 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2686 PEnd = Matched.end();
2688 if (P != Best && getMoreSpecializedPartialSpecialization(
2689 P->Partial, Best->Partial,
2690 PointOfInstantiation) != Best->Partial) {
2691 AmbiguousPartialSpec = true;
2697 // Instantiate using the best variable template partial specialization.
2698 InstantiationPattern = Best->Partial;
2699 InstantiationArgs = Best->Args;
2701 // -- If no match is found, the instantiation is generated
2702 // from the primary template.
2703 // InstantiationPattern = Template->getTemplatedDecl();
2707 // 2. Create the canonical declaration.
2708 // Note that we do not instantiate the variable just yet, since
2709 // instantiation is handled in DoMarkVarDeclReferenced().
2710 // FIXME: LateAttrs et al.?
2711 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
2712 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
2713 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
2717 if (AmbiguousPartialSpec) {
2718 // Partial ordering did not produce a clear winner. Complain.
2719 Decl->setInvalidDecl();
2720 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2723 // Print the matching partial specializations.
2724 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2725 PEnd = Matched.end();
2727 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2728 << getTemplateArgumentBindingsText(
2729 P->Partial->getTemplateParameters(), *P->Args);
2733 if (VarTemplatePartialSpecializationDecl *D =
2734 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
2735 Decl->setInstantiationOf(D, InstantiationArgs);
2737 assert(Decl && "No variable template specialization?");
2742 Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
2743 const DeclarationNameInfo &NameInfo,
2744 VarTemplateDecl *Template, SourceLocation TemplateLoc,
2745 const TemplateArgumentListInfo *TemplateArgs) {
2747 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
2749 if (Decl.isInvalid())
2752 VarDecl *Var = cast<VarDecl>(Decl.get());
2753 if (!Var->getTemplateSpecializationKind())
2754 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
2757 // Build an ordinary singleton decl ref.
2758 return BuildDeclarationNameExpr(SS, NameInfo, Var,
2759 /*FoundD=*/0, TemplateArgs);
2762 ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
2763 SourceLocation TemplateKWLoc,
2766 const TemplateArgumentListInfo *TemplateArgs) {
2767 // FIXME: Can we do any checking at this point? I guess we could check the
2768 // template arguments that we have against the template name, if the template
2769 // name refers to a single template. That's not a terribly common case,
2771 // foo<int> could identify a single function unambiguously
2772 // This approach does NOT work, since f<int>(1);
2773 // gets resolved prior to resorting to overload resolution
2774 // i.e., template<class T> void f(double);
2775 // vs template<class T, class U> void f(U);
2777 // These should be filtered out by our callers.
2778 assert(!R.empty() && "empty lookup results when building templateid");
2779 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
2781 // In C++1y, check variable template ids.
2782 if (R.getAsSingle<VarTemplateDecl>()) {
2783 return Owned(CheckVarTemplateId(SS, R.getLookupNameInfo(),
2784 R.getAsSingle<VarTemplateDecl>(),
2785 TemplateKWLoc, TemplateArgs));
2788 // We don't want lookup warnings at this point.
2789 R.suppressDiagnostics();
2791 UnresolvedLookupExpr *ULE
2792 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2793 SS.getWithLocInContext(Context),
2795 R.getLookupNameInfo(),
2796 RequiresADL, TemplateArgs,
2797 R.begin(), R.end());
2802 // We actually only call this from template instantiation.
2804 Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
2805 SourceLocation TemplateKWLoc,
2806 const DeclarationNameInfo &NameInfo,
2807 const TemplateArgumentListInfo *TemplateArgs) {
2809 assert(TemplateArgs || TemplateKWLoc.isValid());
2811 if (!(DC = computeDeclContext(SS, false)) ||
2812 DC->isDependentContext() ||
2813 RequireCompleteDeclContext(SS, DC))
2814 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
2816 bool MemberOfUnknownSpecialization;
2817 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2818 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
2819 MemberOfUnknownSpecialization);
2821 if (R.isAmbiguous())
2825 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
2826 << NameInfo.getName() << SS.getRange();
2830 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
2831 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
2832 << (NestedNameSpecifier*) SS.getScopeRep()
2833 << NameInfo.getName() << SS.getRange();
2834 Diag(Temp->getLocation(), diag::note_referenced_class_template);
2838 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
2841 /// \brief Form a dependent template name.
2843 /// This action forms a dependent template name given the template
2844 /// name and its (presumably dependent) scope specifier. For
2845 /// example, given "MetaFun::template apply", the scope specifier \p
2846 /// SS will be "MetaFun::", \p TemplateKWLoc contains the location
2847 /// of the "template" keyword, and "apply" is the \p Name.
2848 TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
2850 SourceLocation TemplateKWLoc,
2851 UnqualifiedId &Name,
2852 ParsedType ObjectType,
2853 bool EnteringContext,
2854 TemplateTy &Result) {
2855 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
2857 getLangOpts().CPlusPlus11 ?
2858 diag::warn_cxx98_compat_template_outside_of_template :
2859 diag::ext_template_outside_of_template)
2860 << FixItHint::CreateRemoval(TemplateKWLoc);
2862 DeclContext *LookupCtx = 0;
2864 LookupCtx = computeDeclContext(SS, EnteringContext);
2865 if (!LookupCtx && ObjectType)
2866 LookupCtx = computeDeclContext(ObjectType.get());
2868 // C++0x [temp.names]p5:
2869 // If a name prefixed by the keyword template is not the name of
2870 // a template, the program is ill-formed. [Note: the keyword
2871 // template may not be applied to non-template members of class
2872 // templates. -end note ] [ Note: as is the case with the
2873 // typename prefix, the template prefix is allowed in cases
2874 // where it is not strictly necessary; i.e., when the
2875 // nested-name-specifier or the expression on the left of the ->
2876 // or . is not dependent on a template-parameter, or the use
2877 // does not appear in the scope of a template. -end note]
2879 // Note: C++03 was more strict here, because it banned the use of
2880 // the "template" keyword prior to a template-name that was not a
2881 // dependent name. C++ DR468 relaxed this requirement (the
2882 // "template" keyword is now permitted). We follow the C++0x
2883 // rules, even in C++03 mode with a warning, retroactively applying the DR.
2884 bool MemberOfUnknownSpecialization;
2885 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
2886 ObjectType, EnteringContext, Result,
2887 MemberOfUnknownSpecialization);
2888 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
2889 isa<CXXRecordDecl>(LookupCtx) &&
2890 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
2891 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
2892 // This is a dependent template. Handle it below.
2893 } else if (TNK == TNK_Non_template) {
2894 Diag(Name.getLocStart(),
2895 diag::err_template_kw_refers_to_non_template)
2896 << GetNameFromUnqualifiedId(Name).getName()
2897 << Name.getSourceRange()
2899 return TNK_Non_template;
2901 // We found something; return it.
2906 NestedNameSpecifier *Qualifier
2907 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2909 switch (Name.getKind()) {
2910 case UnqualifiedId::IK_Identifier:
2911 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
2913 return TNK_Dependent_template_name;
2915 case UnqualifiedId::IK_OperatorFunctionId:
2916 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
2917 Name.OperatorFunctionId.Operator));
2918 return TNK_Dependent_template_name;
2920 case UnqualifiedId::IK_LiteralOperatorId:
2922 "We don't support these; Parse shouldn't have allowed propagation");
2928 Diag(Name.getLocStart(),
2929 diag::err_template_kw_refers_to_non_template)
2930 << GetNameFromUnqualifiedId(Name).getName()
2931 << Name.getSourceRange()
2933 return TNK_Non_template;
2936 bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
2937 const TemplateArgumentLoc &AL,
2938 SmallVectorImpl<TemplateArgument> &Converted) {
2939 const TemplateArgument &Arg = AL.getArgument();
2941 // Check template type parameter.
2942 switch(Arg.getKind()) {
2943 case TemplateArgument::Type:
2944 // C++ [temp.arg.type]p1:
2945 // A template-argument for a template-parameter which is a
2946 // type shall be a type-id.
2948 case TemplateArgument::Template: {
2949 // We have a template type parameter but the template argument
2950 // is a template without any arguments.
2951 SourceRange SR = AL.getSourceRange();
2952 TemplateName Name = Arg.getAsTemplate();
2953 Diag(SR.getBegin(), diag::err_template_missing_args)
2955 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
2956 Diag(Decl->getLocation(), diag::note_template_decl_here);
2960 case TemplateArgument::Expression: {
2961 // We have a template type parameter but the template argument is an
2962 // expression; see if maybe it is missing the "typename" keyword.
2964 DeclarationNameInfo NameInfo;
2966 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
2967 SS.Adopt(ArgExpr->getQualifierLoc());
2968 NameInfo = ArgExpr->getNameInfo();
2969 } else if (DependentScopeDeclRefExpr *ArgExpr =
2970 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
2971 SS.Adopt(ArgExpr->getQualifierLoc());
2972 NameInfo = ArgExpr->getNameInfo();
2973 } else if (CXXDependentScopeMemberExpr *ArgExpr =
2974 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
2975 if (ArgExpr->isImplicitAccess()) {
2976 SS.Adopt(ArgExpr->getQualifierLoc());
2977 NameInfo = ArgExpr->getMemberNameInfo();
2981 if (NameInfo.getName().isIdentifier()) {
2982 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
2983 LookupParsedName(Result, CurScope, &SS);
2985 if (Result.getAsSingle<TypeDecl>() ||
2986 Result.getResultKind() ==
2987 LookupResult::NotFoundInCurrentInstantiation) {
2988 // FIXME: Add a FixIt and fix up the template argument for recovery.
2989 SourceLocation Loc = AL.getSourceRange().getBegin();
2990 Diag(Loc, diag::err_template_arg_must_be_type_suggest);
2991 Diag(Param->getLocation(), diag::note_template_param_here);
2998 // We have a template type parameter but the template argument
3000 SourceRange SR = AL.getSourceRange();
3001 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
3002 Diag(Param->getLocation(), diag::note_template_param_here);
3008 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
3011 // Add the converted template type argument.
3012 QualType ArgType = Context.getCanonicalType(Arg.getAsType());
3015 // If an explicitly-specified template argument type is a lifetime type
3016 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
3017 if (getLangOpts().ObjCAutoRefCount &&
3018 ArgType->isObjCLifetimeType() &&
3019 !ArgType.getObjCLifetime()) {
3021 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
3022 ArgType = Context.getQualifiedType(ArgType, Qs);
3025 Converted.push_back(TemplateArgument(ArgType));
3029 /// \brief Substitute template arguments into the default template argument for
3030 /// the given template type parameter.
3032 /// \param SemaRef the semantic analysis object for which we are performing
3033 /// the substitution.
3035 /// \param Template the template that we are synthesizing template arguments
3038 /// \param TemplateLoc the location of the template name that started the
3039 /// template-id we are checking.
3041 /// \param RAngleLoc the location of the right angle bracket ('>') that
3042 /// terminates the template-id.
3044 /// \param Param the template template parameter whose default we are
3045 /// substituting into.
3047 /// \param Converted the list of template arguments provided for template
3048 /// parameters that precede \p Param in the template parameter list.
3049 /// \returns the substituted template argument, or NULL if an error occurred.
3050 static TypeSourceInfo *
3051 SubstDefaultTemplateArgument(Sema &SemaRef,
3052 TemplateDecl *Template,
3053 SourceLocation TemplateLoc,
3054 SourceLocation RAngleLoc,
3055 TemplateTypeParmDecl *Param,
3056 SmallVectorImpl<TemplateArgument> &Converted) {
3057 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
3059 // If the argument type is dependent, instantiate it now based
3060 // on the previously-computed template arguments.
3061 if (ArgType->getType()->isDependentType()) {
3062 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
3063 Template, Converted,
3064 SourceRange(TemplateLoc, RAngleLoc));
3065 if (Inst.isInvalid())
3068 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3069 Converted.data(), Converted.size());
3071 // Only substitute for the innermost template argument list.
3072 MultiLevelTemplateArgumentList TemplateArgLists;
3073 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3074 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3075 TemplateArgLists.addOuterTemplateArguments(None);
3077 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
3079 SemaRef.SubstType(ArgType, TemplateArgLists,
3080 Param->getDefaultArgumentLoc(), Param->getDeclName());
3086 /// \brief Substitute template arguments into the default template argument for
3087 /// the given non-type template parameter.
3089 /// \param SemaRef the semantic analysis object for which we are performing
3090 /// the substitution.
3092 /// \param Template the template that we are synthesizing template arguments
3095 /// \param TemplateLoc the location of the template name that started the
3096 /// template-id we are checking.
3098 /// \param RAngleLoc the location of the right angle bracket ('>') that
3099 /// terminates the template-id.
3101 /// \param Param the non-type template parameter whose default we are
3102 /// substituting into.
3104 /// \param Converted the list of template arguments provided for template
3105 /// parameters that precede \p Param in the template parameter list.
3107 /// \returns the substituted template argument, or NULL if an error occurred.
3109 SubstDefaultTemplateArgument(Sema &SemaRef,
3110 TemplateDecl *Template,
3111 SourceLocation TemplateLoc,
3112 SourceLocation RAngleLoc,
3113 NonTypeTemplateParmDecl *Param,
3114 SmallVectorImpl<TemplateArgument> &Converted) {
3115 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
3116 Template, Converted,
3117 SourceRange(TemplateLoc, RAngleLoc));
3118 if (Inst.isInvalid())
3121 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3122 Converted.data(), Converted.size());
3124 // Only substitute for the innermost template argument list.
3125 MultiLevelTemplateArgumentList TemplateArgLists;
3126 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3127 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3128 TemplateArgLists.addOuterTemplateArguments(None);
3130 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
3131 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
3132 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
3135 /// \brief Substitute template arguments into the default template argument for
3136 /// the given template template 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.
3156 /// \param QualifierLoc Will be set to the nested-name-specifier (with
3157 /// source-location information) that precedes the template name.
3159 /// \returns the substituted template argument, or NULL if an error occurred.
3161 SubstDefaultTemplateArgument(Sema &SemaRef,
3162 TemplateDecl *Template,
3163 SourceLocation TemplateLoc,
3164 SourceLocation RAngleLoc,
3165 TemplateTemplateParmDecl *Param,
3166 SmallVectorImpl<TemplateArgument> &Converted,
3167 NestedNameSpecifierLoc &QualifierLoc) {
3168 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Template, Converted,
3169 SourceRange(TemplateLoc, RAngleLoc));
3170 if (Inst.isInvalid())
3171 return TemplateName();
3173 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3174 Converted.data(), Converted.size());
3176 // Only substitute for the innermost template argument list.
3177 MultiLevelTemplateArgumentList TemplateArgLists;
3178 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3179 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3180 TemplateArgLists.addOuterTemplateArguments(None);
3182 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
3183 // Substitute into the nested-name-specifier first,
3184 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
3187 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
3189 return TemplateName();
3192 return SemaRef.SubstTemplateName(
3194 Param->getDefaultArgument().getArgument().getAsTemplate(),
3195 Param->getDefaultArgument().getTemplateNameLoc(),
3199 /// \brief If the given template parameter has a default template
3200 /// argument, substitute into that default template argument and
3201 /// return the corresponding template argument.
3203 Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
3204 SourceLocation TemplateLoc,
3205 SourceLocation RAngleLoc,
3207 SmallVectorImpl<TemplateArgument>
3209 bool &HasDefaultArg) {
3210 HasDefaultArg = false;
3212 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
3213 if (!TypeParm->hasDefaultArgument())
3214 return TemplateArgumentLoc();
3216 HasDefaultArg = true;
3217 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
3223 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3225 return TemplateArgumentLoc();
3228 if (NonTypeTemplateParmDecl *NonTypeParm
3229 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3230 if (!NonTypeParm->hasDefaultArgument())
3231 return TemplateArgumentLoc();
3233 HasDefaultArg = true;
3234 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
3239 if (Arg.isInvalid())
3240 return TemplateArgumentLoc();
3242 Expr *ArgE = Arg.takeAs<Expr>();
3243 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
3246 TemplateTemplateParmDecl *TempTempParm
3247 = cast<TemplateTemplateParmDecl>(Param);
3248 if (!TempTempParm->hasDefaultArgument())
3249 return TemplateArgumentLoc();
3251 HasDefaultArg = true;
3252 NestedNameSpecifierLoc QualifierLoc;
3253 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
3260 return TemplateArgumentLoc();
3262 return TemplateArgumentLoc(TemplateArgument(TName),
3263 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
3264 TempTempParm->getDefaultArgument().getTemplateNameLoc());
3267 /// \brief Check that the given template argument corresponds to the given
3268 /// template parameter.
3270 /// \param Param The template parameter against which the argument will be
3273 /// \param Arg The template argument.
3275 /// \param Template The template in which the template argument resides.
3277 /// \param TemplateLoc The location of the template name for the template
3278 /// whose argument list we're matching.
3280 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
3281 /// the template argument list.
3283 /// \param ArgumentPackIndex The index into the argument pack where this
3284 /// argument will be placed. Only valid if the parameter is a parameter pack.
3286 /// \param Converted The checked, converted argument will be added to the
3287 /// end of this small vector.
3289 /// \param CTAK Describes how we arrived at this particular template argument:
3290 /// explicitly written, deduced, etc.
3292 /// \returns true on error, false otherwise.
3293 bool Sema::CheckTemplateArgument(NamedDecl *Param,
3294 const TemplateArgumentLoc &Arg,
3295 NamedDecl *Template,
3296 SourceLocation TemplateLoc,
3297 SourceLocation RAngleLoc,
3298 unsigned ArgumentPackIndex,
3299 SmallVectorImpl<TemplateArgument> &Converted,
3300 CheckTemplateArgumentKind CTAK) {
3301 // Check template type parameters.
3302 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3303 return CheckTemplateTypeArgument(TTP, Arg, Converted);
3305 // Check non-type template parameters.
3306 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3307 // Do substitution on the type of the non-type template parameter
3308 // with the template arguments we've seen thus far. But if the
3309 // template has a dependent context then we cannot substitute yet.
3310 QualType NTTPType = NTTP->getType();
3311 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
3312 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
3314 if (NTTPType->isDependentType() &&
3315 !isa<TemplateTemplateParmDecl>(Template) &&
3316 !Template->getDeclContext()->isDependentContext()) {
3317 // Do substitution on the type of the non-type template parameter.
3318 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
3320 SourceRange(TemplateLoc, RAngleLoc));
3321 if (Inst.isInvalid())
3324 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3325 Converted.data(), Converted.size());
3326 NTTPType = SubstType(NTTPType,
3327 MultiLevelTemplateArgumentList(TemplateArgs),
3328 NTTP->getLocation(),
3329 NTTP->getDeclName());
3330 // If that worked, check the non-type template parameter type
3332 if (!NTTPType.isNull())
3333 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
3334 NTTP->getLocation());
3335 if (NTTPType.isNull())
3339 switch (Arg.getArgument().getKind()) {
3340 case TemplateArgument::Null:
3341 llvm_unreachable("Should never see a NULL template argument here");
3343 case TemplateArgument::Expression: {
3344 TemplateArgument Result;
3346 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
3348 if (Res.isInvalid())
3351 Converted.push_back(Result);
3355 case TemplateArgument::Declaration:
3356 case TemplateArgument::Integral:
3357 case TemplateArgument::NullPtr:
3358 // We've already checked this template argument, so just copy
3359 // it to the list of converted arguments.
3360 Converted.push_back(Arg.getArgument());
3363 case TemplateArgument::Template:
3364 case TemplateArgument::TemplateExpansion:
3365 // We were given a template template argument. It may not be ill-formed;
3367 if (DependentTemplateName *DTN
3368 = Arg.getArgument().getAsTemplateOrTemplatePattern()
3369 .getAsDependentTemplateName()) {
3370 // We have a template argument such as \c T::template X, which we
3371 // parsed as a template template argument. However, since we now
3372 // know that we need a non-type template argument, convert this
3373 // template name into an expression.
3375 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
3376 Arg.getTemplateNameLoc());
3379 SS.Adopt(Arg.getTemplateQualifierLoc());
3380 // FIXME: the template-template arg was a DependentTemplateName,
3381 // so it was provided with a template keyword. However, its source
3382 // location is not stored in the template argument structure.
3383 SourceLocation TemplateKWLoc;
3384 ExprResult E = Owned(DependentScopeDeclRefExpr::Create(Context,
3385 SS.getWithLocInContext(Context),
3389 // If we parsed the template argument as a pack expansion, create a
3390 // pack expansion expression.
3391 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
3392 E = ActOnPackExpansion(E.take(), Arg.getTemplateEllipsisLoc());
3397 TemplateArgument Result;
3398 E = CheckTemplateArgument(NTTP, NTTPType, E.take(), Result);
3402 Converted.push_back(Result);
3406 // We have a template argument that actually does refer to a class
3407 // template, alias template, or template template parameter, and
3408 // therefore cannot be a non-type template argument.
3409 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
3410 << Arg.getSourceRange();
3412 Diag(Param->getLocation(), diag::note_template_param_here);
3415 case TemplateArgument::Type: {
3416 // We have a non-type template parameter but the template
3417 // argument is a type.
3419 // C++ [temp.arg]p2:
3420 // In a template-argument, an ambiguity between a type-id and
3421 // an expression is resolved to a type-id, regardless of the
3422 // form of the corresponding template-parameter.
3424 // We warn specifically about this case, since it can be rather
3425 // confusing for users.
3426 QualType T = Arg.getArgument().getAsType();
3427 SourceRange SR = Arg.getSourceRange();
3428 if (T->isFunctionType())
3429 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
3431 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
3432 Diag(Param->getLocation(), diag::note_template_param_here);
3436 case TemplateArgument::Pack:
3437 llvm_unreachable("Caller must expand template argument packs");
3444 // Check template template parameters.
3445 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
3447 // Substitute into the template parameter list of the template
3448 // template parameter, since previously-supplied template arguments
3449 // may appear within the template template parameter.
3451 // Set up a template instantiation context.
3452 LocalInstantiationScope Scope(*this);
3453 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
3454 TempParm, Converted,
3455 SourceRange(TemplateLoc, RAngleLoc));
3456 if (Inst.isInvalid())
3459 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3460 Converted.data(), Converted.size());
3461 TempParm = cast_or_null<TemplateTemplateParmDecl>(
3462 SubstDecl(TempParm, CurContext,
3463 MultiLevelTemplateArgumentList(TemplateArgs)));
3468 switch (Arg.getArgument().getKind()) {
3469 case TemplateArgument::Null:
3470 llvm_unreachable("Should never see a NULL template argument here");
3472 case TemplateArgument::Template:
3473 case TemplateArgument::TemplateExpansion:
3474 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
3477 Converted.push_back(Arg.getArgument());
3480 case TemplateArgument::Expression:
3481 case TemplateArgument::Type:
3482 // We have a template template parameter but the template
3483 // argument does not refer to a template.
3484 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
3485 << getLangOpts().CPlusPlus11;
3488 case TemplateArgument::Declaration:
3489 llvm_unreachable("Declaration argument with template template parameter");
3490 case TemplateArgument::Integral:
3491 llvm_unreachable("Integral argument with template template parameter");
3492 case TemplateArgument::NullPtr:
3493 llvm_unreachable("Null pointer argument with template template parameter");
3495 case TemplateArgument::Pack:
3496 llvm_unreachable("Caller must expand template argument packs");
3502 /// \brief Diagnose an arity mismatch in the
3503 static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
3504 SourceLocation TemplateLoc,
3505 TemplateArgumentListInfo &TemplateArgs) {
3506 TemplateParameterList *Params = Template->getTemplateParameters();
3507 unsigned NumParams = Params->size();
3508 unsigned NumArgs = TemplateArgs.size();
3511 if (NumArgs > NumParams)
3512 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
3513 TemplateArgs.getRAngleLoc());
3514 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3515 << (NumArgs > NumParams)
3516 << (isa<ClassTemplateDecl>(Template)? 0 :
3517 isa<FunctionTemplateDecl>(Template)? 1 :
3518 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3519 << Template << Range;
3520 S.Diag(Template->getLocation(), diag::note_template_decl_here)
3521 << Params->getSourceRange();
3525 /// \brief Check whether the template parameter is a pack expansion, and if so,
3526 /// determine the number of parameters produced by that expansion. For instance:
3529 /// template<typename ...Ts> struct A {
3530 /// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
3534 /// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
3535 /// is not a pack expansion, so returns an empty Optional.
3536 static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
3537 if (NonTypeTemplateParmDecl *NTTP
3538 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3539 if (NTTP->isExpandedParameterPack())
3540 return NTTP->getNumExpansionTypes();
3543 if (TemplateTemplateParmDecl *TTP
3544 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3545 if (TTP->isExpandedParameterPack())
3546 return TTP->getNumExpansionTemplateParameters();
3552 /// \brief Check that the given template argument list is well-formed
3553 /// for specializing the given template.
3554 bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
3555 SourceLocation TemplateLoc,
3556 TemplateArgumentListInfo &TemplateArgs,
3557 bool PartialTemplateArgs,
3558 SmallVectorImpl<TemplateArgument> &Converted,
3559 bool *ExpansionIntoFixedList) {
3560 if (ExpansionIntoFixedList)
3561 *ExpansionIntoFixedList = false;
3563 TemplateParameterList *Params = Template->getTemplateParameters();
3565 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
3567 // C++ [temp.arg]p1:
3568 // [...] The type and form of each template-argument specified in
3569 // a template-id shall match the type and form specified for the
3570 // corresponding parameter declared by the template in its
3571 // template-parameter-list.
3572 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
3573 SmallVector<TemplateArgument, 2> ArgumentPack;
3574 unsigned ArgIdx = 0, NumArgs = TemplateArgs.size();
3575 LocalInstantiationScope InstScope(*this, true);
3576 for (TemplateParameterList::iterator Param = Params->begin(),
3577 ParamEnd = Params->end();
3578 Param != ParamEnd; /* increment in loop */) {
3579 // If we have an expanded parameter pack, make sure we don't have too
3581 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
3582 if (*Expansions == ArgumentPack.size()) {
3583 // We're done with this parameter pack. Pack up its arguments and add
3584 // them to the list.
3585 Converted.push_back(
3586 TemplateArgument::CreatePackCopy(Context,
3587 ArgumentPack.data(),
3588 ArgumentPack.size()));
3589 ArgumentPack.clear();
3591 // This argument is assigned to the next parameter.
3594 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
3595 // Not enough arguments for this parameter pack.
3596 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3598 << (isa<ClassTemplateDecl>(Template)? 0 :
3599 isa<FunctionTemplateDecl>(Template)? 1 :
3600 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3602 Diag(Template->getLocation(), diag::note_template_decl_here)
3603 << Params->getSourceRange();
3608 if (ArgIdx < NumArgs) {
3609 // Check the template argument we were given.
3610 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
3611 TemplateLoc, RAngleLoc,
3612 ArgumentPack.size(), Converted))
3615 // We're now done with this argument.
3618 if ((*Param)->isTemplateParameterPack()) {
3619 // The template parameter was a template parameter pack, so take the
3620 // deduced argument and place it on the argument pack. Note that we
3621 // stay on the same template parameter so that we can deduce more
3623 ArgumentPack.push_back(Converted.pop_back_val());
3625 // Move to the next template parameter.
3629 // If we just saw a pack expansion, then directly convert the remaining
3630 // arguments, because we don't know what parameters they'll match up
3632 if (TemplateArgs[ArgIdx-1].getArgument().isPackExpansion()) {
3633 bool InFinalParameterPack = Param != ParamEnd &&
3634 Param + 1 == ParamEnd &&
3635 (*Param)->isTemplateParameterPack() &&
3636 !getExpandedPackSize(*Param);
3638 if (!InFinalParameterPack && !ArgumentPack.empty()) {
3639 // If we were part way through filling in an expanded parameter pack,
3640 // fall back to just producing individual arguments.
3641 Converted.insert(Converted.end(),
3642 ArgumentPack.begin(), ArgumentPack.end());
3643 ArgumentPack.clear();
3646 while (ArgIdx < NumArgs) {
3647 if (InFinalParameterPack)
3648 ArgumentPack.push_back(TemplateArgs[ArgIdx].getArgument());
3650 Converted.push_back(TemplateArgs[ArgIdx].getArgument());
3654 // Push the argument pack onto the list of converted arguments.
3655 if (InFinalParameterPack) {
3656 Converted.push_back(
3657 TemplateArgument::CreatePackCopy(Context,
3658 ArgumentPack.data(),
3659 ArgumentPack.size()));
3660 ArgumentPack.clear();
3661 } else if (ExpansionIntoFixedList) {
3662 // We have expanded a pack into a fixed list.
3663 *ExpansionIntoFixedList = true;
3672 // If we're checking a partial template argument list, we're done.
3673 if (PartialTemplateArgs) {
3674 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
3675 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
3676 ArgumentPack.data(),
3677 ArgumentPack.size()));
3682 // If we have a template parameter pack with no more corresponding
3683 // arguments, just break out now and we'll fill in the argument pack below.
3684 if ((*Param)->isTemplateParameterPack()) {
3685 assert(!getExpandedPackSize(*Param) &&
3686 "Should have dealt with this already");
3688 // A non-expanded parameter pack before the end of the parameter list
3689 // only occurs for an ill-formed template parameter list, unless we've
3690 // got a partial argument list for a function template, so just bail out.
3691 if (Param + 1 != ParamEnd)
3694 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
3695 ArgumentPack.data(),
3696 ArgumentPack.size()));
3697 ArgumentPack.clear();
3703 // Check whether we have a default argument.
3704 TemplateArgumentLoc Arg;
3706 // Retrieve the default template argument from the template
3707 // parameter. For each kind of template parameter, we substitute the
3708 // template arguments provided thus far and any "outer" template arguments
3709 // (when the template parameter was part of a nested template) into
3710 // the default argument.
3711 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
3712 if (!TTP->hasDefaultArgument())
3713 return diagnoseArityMismatch(*this, Template, TemplateLoc,
3716 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
3725 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
3727 } else if (NonTypeTemplateParmDecl *NTTP
3728 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
3729 if (!NTTP->hasDefaultArgument())
3730 return diagnoseArityMismatch(*this, Template, TemplateLoc,
3733 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
3741 Expr *Ex = E.takeAs<Expr>();
3742 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
3744 TemplateTemplateParmDecl *TempParm
3745 = cast<TemplateTemplateParmDecl>(*Param);
3747 if (!TempParm->hasDefaultArgument())
3748 return diagnoseArityMismatch(*this, Template, TemplateLoc,
3751 NestedNameSpecifierLoc QualifierLoc;
3752 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
3761 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
3762 TempParm->getDefaultArgument().getTemplateNameLoc());
3765 // Introduce an instantiation record that describes where we are using
3766 // the default template argument.
3767 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
3768 SourceRange(TemplateLoc, RAngleLoc));
3769 if (Inst.isInvalid())
3772 // Check the default template argument.
3773 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
3774 RAngleLoc, 0, Converted))
3777 // Core issue 150 (assumed resolution): if this is a template template
3778 // parameter, keep track of the default template arguments from the
3779 // template definition.
3780 if (isTemplateTemplateParameter)
3781 TemplateArgs.addArgument(Arg);
3783 // Move to the next template parameter and argument.
3788 // If we have any leftover arguments, then there were too many arguments.
3789 // Complain and fail.
3790 if (ArgIdx < NumArgs)
3791 return diagnoseArityMismatch(*this, Template, TemplateLoc, TemplateArgs);
3797 class UnnamedLocalNoLinkageFinder
3798 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
3803 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
3806 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
3808 bool Visit(QualType T) {
3809 return inherited::Visit(T.getTypePtr());
3812 #define TYPE(Class, Parent) \
3813 bool Visit##Class##Type(const Class##Type *);
3814 #define ABSTRACT_TYPE(Class, Parent) \
3815 bool Visit##Class##Type(const Class##Type *) { return false; }
3816 #define NON_CANONICAL_TYPE(Class, Parent) \
3817 bool Visit##Class##Type(const Class##Type *) { return false; }
3818 #include "clang/AST/TypeNodes.def"
3820 bool VisitTagDecl(const TagDecl *Tag);
3821 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
3825 bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
3829 bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
3830 return Visit(T->getElementType());
3833 bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
3834 return Visit(T->getPointeeType());
3837 bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
3838 const BlockPointerType* T) {
3839 return Visit(T->getPointeeType());
3842 bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
3843 const LValueReferenceType* T) {
3844 return Visit(T->getPointeeType());
3847 bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
3848 const RValueReferenceType* T) {
3849 return Visit(T->getPointeeType());
3852 bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
3853 const MemberPointerType* T) {
3854 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
3857 bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
3858 const ConstantArrayType* T) {
3859 return Visit(T->getElementType());
3862 bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
3863 const IncompleteArrayType* T) {
3864 return Visit(T->getElementType());
3867 bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
3868 const VariableArrayType* T) {
3869 return Visit(T->getElementType());
3872 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
3873 const DependentSizedArrayType* T) {
3874 return Visit(T->getElementType());
3877 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
3878 const DependentSizedExtVectorType* T) {
3879 return Visit(T->getElementType());
3882 bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
3883 return Visit(T->getElementType());
3886 bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
3887 return Visit(T->getElementType());
3890 bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
3891 const FunctionProtoType* T) {
3892 for (FunctionProtoType::arg_type_iterator A = T->arg_type_begin(),
3893 AEnd = T->arg_type_end();
3899 return Visit(T->getResultType());
3902 bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
3903 const FunctionNoProtoType* T) {
3904 return Visit(T->getResultType());
3907 bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
3908 const UnresolvedUsingType*) {
3912 bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
3916 bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
3917 return Visit(T->getUnderlyingType());
3920 bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
3924 bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
3925 const UnaryTransformType*) {
3929 bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
3930 return Visit(T->getDeducedType());
3933 bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
3934 return VisitTagDecl(T->getDecl());
3937 bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
3938 return VisitTagDecl(T->getDecl());
3941 bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
3942 const TemplateTypeParmType*) {
3946 bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
3947 const SubstTemplateTypeParmPackType *) {
3951 bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
3952 const TemplateSpecializationType*) {
3956 bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
3957 const InjectedClassNameType* T) {
3958 return VisitTagDecl(T->getDecl());
3961 bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
3962 const DependentNameType* T) {
3963 return VisitNestedNameSpecifier(T->getQualifier());
3966 bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
3967 const DependentTemplateSpecializationType* T) {
3968 return VisitNestedNameSpecifier(T->getQualifier());
3971 bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
3972 const PackExpansionType* T) {
3973 return Visit(T->getPattern());
3976 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
3980 bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
3981 const ObjCInterfaceType *) {
3985 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
3986 const ObjCObjectPointerType *) {
3990 bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
3991 return Visit(T->getValueType());
3994 bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
3995 if (Tag->getDeclContext()->isFunctionOrMethod()) {
3996 S.Diag(SR.getBegin(),
3997 S.getLangOpts().CPlusPlus11 ?
3998 diag::warn_cxx98_compat_template_arg_local_type :
3999 diag::ext_template_arg_local_type)
4000 << S.Context.getTypeDeclType(Tag) << SR;
4004 if (!Tag->hasNameForLinkage()) {
4005 S.Diag(SR.getBegin(),
4006 S.getLangOpts().CPlusPlus11 ?
4007 diag::warn_cxx98_compat_template_arg_unnamed_type :
4008 diag::ext_template_arg_unnamed_type) << SR;
4009 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
4016 bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
4017 NestedNameSpecifier *NNS) {
4018 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
4021 switch (NNS->getKind()) {
4022 case NestedNameSpecifier::Identifier:
4023 case NestedNameSpecifier::Namespace:
4024 case NestedNameSpecifier::NamespaceAlias:
4025 case NestedNameSpecifier::Global:
4028 case NestedNameSpecifier::TypeSpec:
4029 case NestedNameSpecifier::TypeSpecWithTemplate:
4030 return Visit(QualType(NNS->getAsType(), 0));
4032 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
4036 /// \brief Check a template argument against its corresponding
4037 /// template type parameter.
4039 /// This routine implements the semantics of C++ [temp.arg.type]. It
4040 /// returns true if an error occurred, and false otherwise.
4041 bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
4042 TypeSourceInfo *ArgInfo) {
4043 assert(ArgInfo && "invalid TypeSourceInfo");
4044 QualType Arg = ArgInfo->getType();
4045 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
4047 if (Arg->isVariablyModifiedType()) {
4048 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
4049 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
4050 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
4053 // C++03 [temp.arg.type]p2:
4054 // A local type, a type with no linkage, an unnamed type or a type
4055 // compounded from any of these types shall not be used as a
4056 // template-argument for a template type-parameter.
4058 // C++11 allows these, and even in C++03 we allow them as an extension with
4060 if (LangOpts.CPlusPlus11 ?
4061 Diags.getDiagnosticLevel(diag::warn_cxx98_compat_template_arg_unnamed_type,
4062 SR.getBegin()) != DiagnosticsEngine::Ignored ||
4063 Diags.getDiagnosticLevel(diag::warn_cxx98_compat_template_arg_local_type,
4064 SR.getBegin()) != DiagnosticsEngine::Ignored :
4065 Arg->hasUnnamedOrLocalType()) {
4066 UnnamedLocalNoLinkageFinder Finder(*this, SR);
4067 (void)Finder.Visit(Context.getCanonicalType(Arg));
4073 enum NullPointerValueKind {
4079 /// \brief Determine whether the given template argument is a null pointer
4080 /// value of the appropriate type.
4081 static NullPointerValueKind
4082 isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
4083 QualType ParamType, Expr *Arg) {
4084 if (Arg->isValueDependent() || Arg->isTypeDependent())
4085 return NPV_NotNullPointer;
4087 if (!S.getLangOpts().CPlusPlus11)
4088 return NPV_NotNullPointer;
4090 // Determine whether we have a constant expression.
4091 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
4092 if (ArgRV.isInvalid())
4096 Expr::EvalResult EvalResult;
4097 SmallVector<PartialDiagnosticAt, 8> Notes;
4098 EvalResult.Diag = &Notes;
4099 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
4100 EvalResult.HasSideEffects) {
4101 SourceLocation DiagLoc = Arg->getExprLoc();
4103 // If our only note is the usual "invalid subexpression" note, just point
4104 // the caret at its location rather than producing an essentially
4106 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
4107 diag::note_invalid_subexpr_in_const_expr) {
4108 DiagLoc = Notes[0].first;
4112 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
4113 << Arg->getType() << Arg->getSourceRange();
4114 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
4115 S.Diag(Notes[I].first, Notes[I].second);
4117 S.Diag(Param->getLocation(), diag::note_template_param_here);
4121 // C++11 [temp.arg.nontype]p1:
4122 // - an address constant expression of type std::nullptr_t
4123 if (Arg->getType()->isNullPtrType())
4124 return NPV_NullPointer;
4126 // - a constant expression that evaluates to a null pointer value (4.10); or
4127 // - a constant expression that evaluates to a null member pointer value
4129 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
4130 (EvalResult.Val.isMemberPointer() &&
4131 !EvalResult.Val.getMemberPointerDecl())) {
4132 // If our expression has an appropriate type, we've succeeded.
4133 bool ObjCLifetimeConversion;
4134 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
4135 S.IsQualificationConversion(Arg->getType(), ParamType, false,
4136 ObjCLifetimeConversion))
4137 return NPV_NullPointer;
4139 // The types didn't match, but we know we got a null pointer; complain,
4140 // then recover as if the types were correct.
4141 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
4142 << Arg->getType() << ParamType << Arg->getSourceRange();
4143 S.Diag(Param->getLocation(), diag::note_template_param_here);
4144 return NPV_NullPointer;
4147 // If we don't have a null pointer value, but we do have a NULL pointer
4148 // constant, suggest a cast to the appropriate type.
4149 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
4150 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
4151 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
4153 << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
4154 << FixItHint::CreateInsertion(S.PP.getLocForEndOfToken(Arg->getLocEnd()),
4156 S.Diag(Param->getLocation(), diag::note_template_param_here);
4157 return NPV_NullPointer;
4160 // FIXME: If we ever want to support general, address-constant expressions
4161 // as non-type template arguments, we should return the ExprResult here to
4162 // be interpreted by the caller.
4163 return NPV_NotNullPointer;
4166 /// \brief Checks whether the given template argument is compatible with its
4167 /// template parameter.
4168 static bool CheckTemplateArgumentIsCompatibleWithParameter(
4169 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
4170 Expr *Arg, QualType ArgType) {
4171 bool ObjCLifetimeConversion;
4172 if (ParamType->isPointerType() &&
4173 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
4174 S.IsQualificationConversion(ArgType, ParamType, false,
4175 ObjCLifetimeConversion)) {
4176 // For pointer-to-object types, qualification conversions are
4179 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
4180 if (!ParamRef->getPointeeType()->isFunctionType()) {
4181 // C++ [temp.arg.nontype]p5b3:
4182 // For a non-type template-parameter of type reference to
4183 // object, no conversions apply. The type referred to by the
4184 // reference may be more cv-qualified than the (otherwise
4185 // identical) type of the template- argument. The
4186 // template-parameter is bound directly to the
4187 // template-argument, which shall be an lvalue.
4189 // FIXME: Other qualifiers?
4190 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
4191 unsigned ArgQuals = ArgType.getCVRQualifiers();
4193 if ((ParamQuals | ArgQuals) != ParamQuals) {
4194 S.Diag(Arg->getLocStart(),
4195 diag::err_template_arg_ref_bind_ignores_quals)
4196 << ParamType << Arg->getType() << Arg->getSourceRange();
4197 S.Diag(Param->getLocation(), diag::note_template_param_here);
4203 // At this point, the template argument refers to an object or
4204 // function with external linkage. We now need to check whether the
4205 // argument and parameter types are compatible.
4206 if (!S.Context.hasSameUnqualifiedType(ArgType,
4207 ParamType.getNonReferenceType())) {
4208 // We can't perform this conversion or binding.
4209 if (ParamType->isReferenceType())
4210 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
4211 << ParamType << ArgIn->getType() << Arg->getSourceRange();
4213 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4214 << ArgIn->getType() << ParamType << Arg->getSourceRange();
4215 S.Diag(Param->getLocation(), diag::note_template_param_here);
4223 /// \brief Checks whether the given template argument is the address
4224 /// of an object or function according to C++ [temp.arg.nontype]p1.
4226 CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
4227 NonTypeTemplateParmDecl *Param,
4230 TemplateArgument &Converted) {
4231 bool Invalid = false;
4233 QualType ArgType = Arg->getType();
4235 // If our parameter has pointer type, check for a null template value.
4236 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
4237 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
4238 case NPV_NullPointer:
4239 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
4240 Converted = TemplateArgument(ParamType, /*isNullPtr*/true);
4246 case NPV_NotNullPointer:
4251 bool AddressTaken = false;
4252 SourceLocation AddrOpLoc;
4253 if (S.getLangOpts().MicrosoftExt) {
4254 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
4255 // dereference and address-of operators.
4256 Arg = Arg->IgnoreParenCasts();
4258 bool ExtWarnMSTemplateArg = false;
4259 UnaryOperatorKind FirstOpKind;
4260 SourceLocation FirstOpLoc;
4261 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4262 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
4263 if (UnOpKind == UO_Deref)
4264 ExtWarnMSTemplateArg = true;
4265 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
4266 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
4267 if (!AddrOpLoc.isValid()) {
4268 FirstOpKind = UnOpKind;
4269 FirstOpLoc = UnOp->getOperatorLoc();
4274 if (FirstOpLoc.isValid()) {
4275 if (ExtWarnMSTemplateArg)
4276 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
4277 << ArgIn->getSourceRange();
4279 if (FirstOpKind == UO_AddrOf)
4280 AddressTaken = true;
4281 else if (Arg->getType()->isPointerType()) {
4282 // We cannot let pointers get dereferenced here, that is obviously not a
4283 // constant expression.
4284 assert(FirstOpKind == UO_Deref);
4285 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4286 << Arg->getSourceRange();
4290 // See through any implicit casts we added to fix the type.
4291 Arg = Arg->IgnoreImpCasts();
4293 // C++ [temp.arg.nontype]p1:
4295 // A template-argument for a non-type, non-template
4296 // template-parameter shall be one of: [...]
4298 // -- the address of an object or function with external
4299 // linkage, including function templates and function
4300 // template-ids but excluding non-static class members,
4301 // expressed as & id-expression where the & is optional if
4302 // the name refers to a function or array, or if the
4303 // corresponding template-parameter is a reference; or
4305 // In C++98/03 mode, give an extension warning on any extra parentheses.
4306 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4307 bool ExtraParens = false;
4308 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4309 if (!Invalid && !ExtraParens) {
4310 S.Diag(Arg->getLocStart(),
4311 S.getLangOpts().CPlusPlus11
4312 ? diag::warn_cxx98_compat_template_arg_extra_parens
4313 : diag::ext_template_arg_extra_parens)
4314 << Arg->getSourceRange();
4318 Arg = Parens->getSubExpr();
4321 while (SubstNonTypeTemplateParmExpr *subst =
4322 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4323 Arg = subst->getReplacement()->IgnoreImpCasts();
4325 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4326 if (UnOp->getOpcode() == UO_AddrOf) {
4327 Arg = UnOp->getSubExpr();
4328 AddressTaken = true;
4329 AddrOpLoc = UnOp->getOperatorLoc();
4333 while (SubstNonTypeTemplateParmExpr *subst =
4334 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4335 Arg = subst->getReplacement()->IgnoreImpCasts();
4338 // Stop checking the precise nature of the argument if it is value dependent,
4339 // it should be checked when instantiated.
4340 if (Arg->isValueDependent()) {
4341 Converted = TemplateArgument(ArgIn);
4345 if (isa<CXXUuidofExpr>(Arg)) {
4346 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
4347 ArgIn, Arg, ArgType))
4350 Converted = TemplateArgument(ArgIn);
4354 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
4356 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4357 << Arg->getSourceRange();
4358 S.Diag(Param->getLocation(), diag::note_template_param_here);
4362 ValueDecl *Entity = DRE->getDecl();
4364 // Cannot refer to non-static data members
4365 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
4366 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
4367 << Entity << Arg->getSourceRange();
4368 S.Diag(Param->getLocation(), diag::note_template_param_here);
4372 // Cannot refer to non-static member functions
4373 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
4374 if (!Method->isStatic()) {
4375 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
4376 << Method << Arg->getSourceRange();
4377 S.Diag(Param->getLocation(), diag::note_template_param_here);
4382 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
4383 VarDecl *Var = dyn_cast<VarDecl>(Entity);
4385 // A non-type template argument must refer to an object or function.
4386 if (!Func && !Var) {
4387 // We found something, but we don't know specifically what it is.
4388 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
4389 << Arg->getSourceRange();
4390 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4394 // Address / reference template args must have external linkage in C++98.
4395 if (Entity->getFormalLinkage() == InternalLinkage) {
4396 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
4397 diag::warn_cxx98_compat_template_arg_object_internal :
4398 diag::ext_template_arg_object_internal)
4399 << !Func << Entity << Arg->getSourceRange();
4400 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4402 } else if (!Entity->hasLinkage()) {
4403 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
4404 << !Func << Entity << Arg->getSourceRange();
4405 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4411 // If the template parameter has pointer type, the function decays.
4412 if (ParamType->isPointerType() && !AddressTaken)
4413 ArgType = S.Context.getPointerType(Func->getType());
4414 else if (AddressTaken && ParamType->isReferenceType()) {
4415 // If we originally had an address-of operator, but the
4416 // parameter has reference type, complain and (if things look
4417 // like they will work) drop the address-of operator.
4418 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
4419 ParamType.getNonReferenceType())) {
4420 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4422 S.Diag(Param->getLocation(), diag::note_template_param_here);
4426 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4428 << FixItHint::CreateRemoval(AddrOpLoc);
4429 S.Diag(Param->getLocation(), diag::note_template_param_here);
4431 ArgType = Func->getType();
4434 // A value of reference type is not an object.
4435 if (Var->getType()->isReferenceType()) {
4436 S.Diag(Arg->getLocStart(),
4437 diag::err_template_arg_reference_var)
4438 << Var->getType() << Arg->getSourceRange();
4439 S.Diag(Param->getLocation(), diag::note_template_param_here);
4443 // A template argument must have static storage duration.
4444 if (Var->getTLSKind()) {
4445 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
4446 << Arg->getSourceRange();
4447 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
4451 // If the template parameter has pointer type, we must have taken
4452 // the address of this object.
4453 if (ParamType->isReferenceType()) {
4455 // If we originally had an address-of operator, but the
4456 // parameter has reference type, complain and (if things look
4457 // like they will work) drop the address-of operator.
4458 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
4459 ParamType.getNonReferenceType())) {
4460 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4462 S.Diag(Param->getLocation(), diag::note_template_param_here);
4466 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4468 << FixItHint::CreateRemoval(AddrOpLoc);
4469 S.Diag(Param->getLocation(), diag::note_template_param_here);
4471 ArgType = Var->getType();
4473 } else if (!AddressTaken && ParamType->isPointerType()) {
4474 if (Var->getType()->isArrayType()) {
4475 // Array-to-pointer decay.
4476 ArgType = S.Context.getArrayDecayedType(Var->getType());
4478 // If the template parameter has pointer type but the address of
4479 // this object was not taken, complain and (possibly) recover by
4480 // taking the address of the entity.
4481 ArgType = S.Context.getPointerType(Var->getType());
4482 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
4483 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4485 S.Diag(Param->getLocation(), diag::note_template_param_here);
4489 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4491 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
4493 S.Diag(Param->getLocation(), diag::note_template_param_here);
4498 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
4502 // Create the template argument.
4503 Converted = TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()),
4504 ParamType->isReferenceType());
4505 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
4509 /// \brief Checks whether the given template argument is a pointer to
4510 /// member constant according to C++ [temp.arg.nontype]p1.
4511 static bool CheckTemplateArgumentPointerToMember(Sema &S,
4512 NonTypeTemplateParmDecl *Param,
4515 TemplateArgument &Converted) {
4516 bool Invalid = false;
4518 // Check for a null pointer value.
4519 Expr *Arg = ResultArg;
4520 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
4523 case NPV_NullPointer:
4524 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
4525 Converted = TemplateArgument(ParamType, /*isNullPtr*/true);
4527 case NPV_NotNullPointer:
4531 bool ObjCLifetimeConversion;
4532 if (S.IsQualificationConversion(Arg->getType(),
4533 ParamType.getNonReferenceType(),
4534 false, ObjCLifetimeConversion)) {
4535 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
4536 Arg->getValueKind()).take();
4538 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
4539 ParamType.getNonReferenceType())) {
4540 // We can't perform this conversion.
4541 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4542 << Arg->getType() << ParamType << Arg->getSourceRange();
4543 S.Diag(Param->getLocation(), diag::note_template_param_here);
4547 // See through any implicit casts we added to fix the type.
4548 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
4549 Arg = Cast->getSubExpr();
4551 // C++ [temp.arg.nontype]p1:
4553 // A template-argument for a non-type, non-template
4554 // template-parameter shall be one of: [...]
4556 // -- a pointer to member expressed as described in 5.3.1.
4557 DeclRefExpr *DRE = 0;
4559 // In C++98/03 mode, give an extension warning on any extra parentheses.
4560 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4561 bool ExtraParens = false;
4562 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4563 if (!Invalid && !ExtraParens) {
4564 S.Diag(Arg->getLocStart(),
4565 S.getLangOpts().CPlusPlus11 ?
4566 diag::warn_cxx98_compat_template_arg_extra_parens :
4567 diag::ext_template_arg_extra_parens)
4568 << Arg->getSourceRange();
4572 Arg = Parens->getSubExpr();
4575 while (SubstNonTypeTemplateParmExpr *subst =
4576 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4577 Arg = subst->getReplacement()->IgnoreImpCasts();
4579 // A pointer-to-member constant written &Class::member.
4580 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4581 if (UnOp->getOpcode() == UO_AddrOf) {
4582 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
4583 if (DRE && !DRE->getQualifier())
4587 // A constant of pointer-to-member type.
4588 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
4589 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
4590 if (VD->getType()->isMemberPointerType()) {
4591 if (isa<NonTypeTemplateParmDecl>(VD)) {
4592 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
4593 Converted = TemplateArgument(Arg);
4595 VD = cast<ValueDecl>(VD->getCanonicalDecl());
4596 Converted = TemplateArgument(VD, /*isReferenceParam*/false);
4607 return S.Diag(Arg->getLocStart(),
4608 diag::err_template_arg_not_pointer_to_member_form)
4609 << Arg->getSourceRange();
4611 if (isa<FieldDecl>(DRE->getDecl()) ||
4612 isa<IndirectFieldDecl>(DRE->getDecl()) ||
4613 isa<CXXMethodDecl>(DRE->getDecl())) {
4614 assert((isa<FieldDecl>(DRE->getDecl()) ||
4615 isa<IndirectFieldDecl>(DRE->getDecl()) ||
4616 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
4617 "Only non-static member pointers can make it here");
4619 // Okay: this is the address of a non-static member, and therefore
4620 // a member pointer constant.
4621 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
4622 Converted = TemplateArgument(Arg);
4624 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
4625 Converted = TemplateArgument(D, /*isReferenceParam*/false);
4630 // We found something else, but we don't know specifically what it is.
4631 S.Diag(Arg->getLocStart(),
4632 diag::err_template_arg_not_pointer_to_member_form)
4633 << Arg->getSourceRange();
4634 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4638 /// \brief Check a template argument against its corresponding
4639 /// non-type template parameter.
4641 /// This routine implements the semantics of C++ [temp.arg.nontype].
4642 /// If an error occurred, it returns ExprError(); otherwise, it
4643 /// returns the converted template argument. \p
4644 /// InstantiatedParamType is the type of the non-type template
4645 /// parameter after it has been instantiated.
4646 ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
4647 QualType InstantiatedParamType, Expr *Arg,
4648 TemplateArgument &Converted,
4649 CheckTemplateArgumentKind CTAK) {
4650 SourceLocation StartLoc = Arg->getLocStart();
4652 // If either the parameter has a dependent type or the argument is
4653 // type-dependent, there's nothing we can check now.
4654 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
4655 // FIXME: Produce a cloned, canonical expression?
4656 Converted = TemplateArgument(Arg);
4660 // C++ [temp.arg.nontype]p5:
4661 // The following conversions are performed on each expression used
4662 // as a non-type template-argument. If a non-type
4663 // template-argument cannot be converted to the type of the
4664 // corresponding template-parameter then the program is
4666 QualType ParamType = InstantiatedParamType;
4667 if (ParamType->isIntegralOrEnumerationType()) {
4669 // -- for a non-type template-parameter of integral or
4670 // enumeration type, conversions permitted in a converted
4671 // constant expression are applied.
4674 // -- for a non-type template-parameter of integral or
4675 // enumeration type, integral promotions (4.5) and integral
4676 // conversions (4.7) are applied.
4678 if (CTAK == CTAK_Deduced &&
4679 !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) {
4680 // C++ [temp.deduct.type]p17:
4681 // If, in the declaration of a function template with a non-type
4682 // template-parameter, the non-type template-parameter is used
4683 // in an expression in the function parameter-list and, if the
4684 // corresponding template-argument is deduced, the
4685 // template-argument type shall match the type of the
4686 // template-parameter exactly, except that a template-argument
4687 // deduced from an array bound may be of any integral type.
4688 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
4689 << Arg->getType().getUnqualifiedType()
4690 << ParamType.getUnqualifiedType();
4691 Diag(Param->getLocation(), diag::note_template_param_here);
4695 if (getLangOpts().CPlusPlus11) {
4696 // We can't check arbitrary value-dependent arguments.
4697 // FIXME: If there's no viable conversion to the template parameter type,
4698 // we should be able to diagnose that prior to instantiation.
4699 if (Arg->isValueDependent()) {
4700 Converted = TemplateArgument(Arg);
4704 // C++ [temp.arg.nontype]p1:
4705 // A template-argument for a non-type, non-template template-parameter
4708 // -- for a non-type template-parameter of integral or enumeration
4709 // type, a converted constant expression of the type of the
4710 // template-parameter; or
4712 ExprResult ArgResult =
4713 CheckConvertedConstantExpression(Arg, ParamType, Value,
4715 if (ArgResult.isInvalid())
4718 // Widen the argument value to sizeof(parameter type). This is almost
4719 // always a no-op, except when the parameter type is bool. In
4720 // that case, this may extend the argument from 1 bit to 8 bits.
4721 QualType IntegerType = ParamType;
4722 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
4723 IntegerType = Enum->getDecl()->getIntegerType();
4724 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
4726 Converted = TemplateArgument(Context, Value,
4727 Context.getCanonicalType(ParamType));
4731 ExprResult ArgResult = DefaultLvalueConversion(Arg);
4732 if (ArgResult.isInvalid())
4734 Arg = ArgResult.take();
4736 QualType ArgType = Arg->getType();
4738 // C++ [temp.arg.nontype]p1:
4739 // A template-argument for a non-type, non-template
4740 // template-parameter shall be one of:
4742 // -- an integral constant-expression of integral or enumeration
4744 // -- the name of a non-type template-parameter; or
4745 SourceLocation NonConstantLoc;
4747 if (!ArgType->isIntegralOrEnumerationType()) {
4748 Diag(Arg->getLocStart(),
4749 diag::err_template_arg_not_integral_or_enumeral)
4750 << ArgType << Arg->getSourceRange();
4751 Diag(Param->getLocation(), diag::note_template_param_here);
4753 } else if (!Arg->isValueDependent()) {
4754 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
4758 TmplArgICEDiagnoser(QualType T) : T(T) { }
4760 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc,
4762 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
4764 } Diagnoser(ArgType);
4766 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
4772 // From here on out, all we care about are the unqualified forms
4773 // of the parameter and argument types.
4774 ParamType = ParamType.getUnqualifiedType();
4775 ArgType = ArgType.getUnqualifiedType();
4777 // Try to convert the argument to the parameter's type.
4778 if (Context.hasSameType(ParamType, ArgType)) {
4779 // Okay: no conversion necessary
4780 } else if (ParamType->isBooleanType()) {
4781 // This is an integral-to-boolean conversion.
4782 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).take();
4783 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
4784 !ParamType->isEnumeralType()) {
4785 // This is an integral promotion or conversion.
4786 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).take();
4788 // We can't perform this conversion.
4789 Diag(Arg->getLocStart(),
4790 diag::err_template_arg_not_convertible)
4791 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
4792 Diag(Param->getLocation(), diag::note_template_param_here);
4796 // Add the value of this argument to the list of converted
4797 // arguments. We use the bitwidth and signedness of the template
4799 if (Arg->isValueDependent()) {
4800 // The argument is value-dependent. Create a new
4801 // TemplateArgument with the converted expression.
4802 Converted = TemplateArgument(Arg);
4806 QualType IntegerType = Context.getCanonicalType(ParamType);
4807 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
4808 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
4810 if (ParamType->isBooleanType()) {
4811 // Value must be zero or one.
4813 unsigned AllowedBits = Context.getTypeSize(IntegerType);
4814 if (Value.getBitWidth() != AllowedBits)
4815 Value = Value.extOrTrunc(AllowedBits);
4816 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
4818 llvm::APSInt OldValue = Value;
4820 // Coerce the template argument's value to the value it will have
4821 // based on the template parameter's type.
4822 unsigned AllowedBits = Context.getTypeSize(IntegerType);
4823 if (Value.getBitWidth() != AllowedBits)
4824 Value = Value.extOrTrunc(AllowedBits);
4825 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
4827 // Complain if an unsigned parameter received a negative value.
4828 if (IntegerType->isUnsignedIntegerOrEnumerationType()
4829 && (OldValue.isSigned() && OldValue.isNegative())) {
4830 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
4831 << OldValue.toString(10) << Value.toString(10) << Param->getType()
4832 << Arg->getSourceRange();
4833 Diag(Param->getLocation(), diag::note_template_param_here);
4836 // Complain if we overflowed the template parameter's type.
4837 unsigned RequiredBits;
4838 if (IntegerType->isUnsignedIntegerOrEnumerationType())
4839 RequiredBits = OldValue.getActiveBits();
4840 else if (OldValue.isUnsigned())
4841 RequiredBits = OldValue.getActiveBits() + 1;
4843 RequiredBits = OldValue.getMinSignedBits();
4844 if (RequiredBits > AllowedBits) {
4845 Diag(Arg->getLocStart(),
4846 diag::warn_template_arg_too_large)
4847 << OldValue.toString(10) << Value.toString(10) << Param->getType()
4848 << Arg->getSourceRange();
4849 Diag(Param->getLocation(), diag::note_template_param_here);
4853 Converted = TemplateArgument(Context, Value,
4854 ParamType->isEnumeralType()
4855 ? Context.getCanonicalType(ParamType)
4860 QualType ArgType = Arg->getType();
4861 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
4863 // Handle pointer-to-function, reference-to-function, and
4864 // pointer-to-member-function all in (roughly) the same way.
4865 if (// -- For a non-type template-parameter of type pointer to
4866 // function, only the function-to-pointer conversion (4.3) is
4867 // applied. If the template-argument represents a set of
4868 // overloaded functions (or a pointer to such), the matching
4869 // function is selected from the set (13.4).
4870 (ParamType->isPointerType() &&
4871 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
4872 // -- For a non-type template-parameter of type reference to
4873 // function, no conversions apply. If the template-argument
4874 // represents a set of overloaded functions, the matching
4875 // function is selected from the set (13.4).
4876 (ParamType->isReferenceType() &&
4877 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
4878 // -- For a non-type template-parameter of type pointer to
4879 // member function, no conversions apply. If the
4880 // template-argument represents a set of overloaded member
4881 // functions, the matching member function is selected from
4883 (ParamType->isMemberPointerType() &&
4884 ParamType->getAs<MemberPointerType>()->getPointeeType()
4885 ->isFunctionType())) {
4887 if (Arg->getType() == Context.OverloadTy) {
4888 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
4891 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
4894 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
4895 ArgType = Arg->getType();
4900 if (!ParamType->isMemberPointerType()) {
4901 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
4908 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
4914 if (ParamType->isPointerType()) {
4915 // -- for a non-type template-parameter of type pointer to
4916 // object, qualification conversions (4.4) and the
4917 // array-to-pointer conversion (4.2) are applied.
4918 // C++0x also allows a value of std::nullptr_t.
4919 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
4920 "Only object pointers allowed here");
4922 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
4929 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
4930 // -- For a non-type template-parameter of type reference to
4931 // object, no conversions apply. The type referred to by the
4932 // reference may be more cv-qualified than the (otherwise
4933 // identical) type of the template-argument. The
4934 // template-parameter is bound directly to the
4935 // template-argument, which must be an lvalue.
4936 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
4937 "Only object references allowed here");
4939 if (Arg->getType() == Context.OverloadTy) {
4940 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
4941 ParamRefType->getPointeeType(),
4944 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
4947 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
4948 ArgType = Arg->getType();
4953 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
4960 // Deal with parameters of type std::nullptr_t.
4961 if (ParamType->isNullPtrType()) {
4962 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
4963 Converted = TemplateArgument(Arg);
4967 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
4968 case NPV_NotNullPointer:
4969 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
4970 << Arg->getType() << ParamType;
4971 Diag(Param->getLocation(), diag::note_template_param_here);
4977 case NPV_NullPointer:
4978 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
4979 Converted = TemplateArgument(ParamType, /*isNullPtr*/true);
4984 // -- For a non-type template-parameter of type pointer to data
4985 // member, qualification conversions (4.4) are applied.
4986 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
4988 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
4994 /// \brief Check a template argument against its corresponding
4995 /// template template parameter.
4997 /// This routine implements the semantics of C++ [temp.arg.template].
4998 /// It returns true if an error occurred, and false otherwise.
4999 bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
5000 const TemplateArgumentLoc &Arg,
5001 unsigned ArgumentPackIndex) {
5002 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
5003 TemplateDecl *Template = Name.getAsTemplateDecl();
5005 // Any dependent template name is fine.
5006 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
5010 // C++0x [temp.arg.template]p1:
5011 // A template-argument for a template template-parameter shall be
5012 // the name of a class template or an alias template, expressed as an
5013 // id-expression. When the template-argument names a class template, only
5014 // primary class templates are considered when matching the
5015 // template template argument with the corresponding parameter;
5016 // partial specializations are not considered even if their
5017 // parameter lists match that of the template template parameter.
5019 // Note that we also allow template template parameters here, which
5020 // will happen when we are dealing with, e.g., class template
5021 // partial specializations.
5022 if (!isa<ClassTemplateDecl>(Template) &&
5023 !isa<TemplateTemplateParmDecl>(Template) &&
5024 !isa<TypeAliasTemplateDecl>(Template)) {
5025 assert(isa<FunctionTemplateDecl>(Template) &&
5026 "Only function templates are possible here");
5027 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
5028 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
5032 TemplateParameterList *Params = Param->getTemplateParameters();
5033 if (Param->isExpandedParameterPack())
5034 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
5036 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
5039 TPL_TemplateTemplateArgumentMatch,
5043 /// \brief Given a non-type template argument that refers to a
5044 /// declaration and the type of its corresponding non-type template
5045 /// parameter, produce an expression that properly refers to that
5048 Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5050 SourceLocation Loc) {
5051 // C++ [temp.param]p8:
5053 // A non-type template-parameter of type "array of T" or
5054 // "function returning T" is adjusted to be of type "pointer to
5055 // T" or "pointer to function returning T", respectively.
5056 if (ParamType->isArrayType())
5057 ParamType = Context.getArrayDecayedType(ParamType);
5058 else if (ParamType->isFunctionType())
5059 ParamType = Context.getPointerType(ParamType);
5061 // For a NULL non-type template argument, return nullptr casted to the
5062 // parameter's type.
5063 if (Arg.getKind() == TemplateArgument::NullPtr) {
5064 return ImpCastExprToType(
5065 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
5067 ParamType->getAs<MemberPointerType>()
5068 ? CK_NullToMemberPointer
5069 : CK_NullToPointer);
5071 assert(Arg.getKind() == TemplateArgument::Declaration &&
5072 "Only declaration template arguments permitted here");
5074 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
5076 if (VD->getDeclContext()->isRecord() &&
5077 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
5078 isa<IndirectFieldDecl>(VD))) {
5079 // If the value is a class member, we might have a pointer-to-member.
5080 // Determine whether the non-type template template parameter is of
5081 // pointer-to-member type. If so, we need to build an appropriate
5082 // expression for a pointer-to-member, since a "normal" DeclRefExpr
5083 // would refer to the member itself.
5084 if (ParamType->isMemberPointerType()) {
5086 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
5087 NestedNameSpecifier *Qualifier
5088 = NestedNameSpecifier::Create(Context, 0, false,
5089 ClassType.getTypePtr());
5091 SS.MakeTrivial(Context, Qualifier, Loc);
5093 // The actual value-ness of this is unimportant, but for
5094 // internal consistency's sake, references to instance methods
5096 ExprValueKind VK = VK_LValue;
5097 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
5100 ExprResult RefExpr = BuildDeclRefExpr(VD,
5101 VD->getType().getNonReferenceType(),
5105 if (RefExpr.isInvalid())
5108 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
5110 // We might need to perform a trailing qualification conversion, since
5111 // the element type on the parameter could be more qualified than the
5112 // element type in the expression we constructed.
5113 bool ObjCLifetimeConversion;
5114 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
5115 ParamType.getUnqualifiedType(), false,
5116 ObjCLifetimeConversion))
5117 RefExpr = ImpCastExprToType(RefExpr.take(), ParamType.getUnqualifiedType(), CK_NoOp);
5119 assert(!RefExpr.isInvalid() &&
5120 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
5121 ParamType.getUnqualifiedType()));
5126 QualType T = VD->getType().getNonReferenceType();
5128 if (ParamType->isPointerType()) {
5129 // When the non-type template parameter is a pointer, take the
5130 // address of the declaration.
5131 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
5132 if (RefExpr.isInvalid())
5135 if (T->isFunctionType() || T->isArrayType()) {
5136 // Decay functions and arrays.
5137 RefExpr = DefaultFunctionArrayConversion(RefExpr.take());
5138 if (RefExpr.isInvalid())
5144 // Take the address of everything else
5145 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
5148 ExprValueKind VK = VK_RValue;
5150 // If the non-type template parameter has reference type, qualify the
5151 // resulting declaration reference with the extra qualifiers on the
5152 // type that the reference refers to.
5153 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
5155 T = Context.getQualifiedType(T,
5156 TargetRef->getPointeeType().getQualifiers());
5157 } else if (isa<FunctionDecl>(VD)) {
5158 // References to functions are always lvalues.
5162 return BuildDeclRefExpr(VD, T, VK, Loc);
5165 /// \brief Construct a new expression that refers to the given
5166 /// integral template argument with the given source-location
5169 /// This routine takes care of the mapping from an integral template
5170 /// argument (which may have any integral type) to the appropriate
5173 Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5174 SourceLocation Loc) {
5175 assert(Arg.getKind() == TemplateArgument::Integral &&
5176 "Operation is only valid for integral template arguments");
5177 QualType OrigT = Arg.getIntegralType();
5179 // If this is an enum type that we're instantiating, we need to use an integer
5180 // type the same size as the enumerator. We don't want to build an
5181 // IntegerLiteral with enum type. The integer type of an enum type can be of
5182 // any integral type with C++11 enum classes, make sure we create the right
5183 // type of literal for it.
5185 if (const EnumType *ET = OrigT->getAs<EnumType>())
5186 T = ET->getDecl()->getIntegerType();
5189 if (T->isAnyCharacterType()) {
5190 CharacterLiteral::CharacterKind Kind;
5191 if (T->isWideCharType())
5192 Kind = CharacterLiteral::Wide;
5193 else if (T->isChar16Type())
5194 Kind = CharacterLiteral::UTF16;
5195 else if (T->isChar32Type())
5196 Kind = CharacterLiteral::UTF32;
5198 Kind = CharacterLiteral::Ascii;
5200 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
5202 } else if (T->isBooleanType()) {
5203 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
5205 } else if (T->isNullPtrType()) {
5206 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
5208 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
5211 if (OrigT->isEnumeralType()) {
5212 // FIXME: This is a hack. We need a better way to handle substituted
5213 // non-type template parameters.
5214 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E, 0,
5215 Context.getTrivialTypeSourceInfo(OrigT, Loc),
5222 /// \brief Match two template parameters within template parameter lists.
5223 static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
5225 Sema::TemplateParameterListEqualKind Kind,
5226 SourceLocation TemplateArgLoc) {
5227 // Check the actual kind (type, non-type, template).
5228 if (Old->getKind() != New->getKind()) {
5230 unsigned NextDiag = diag::err_template_param_different_kind;
5231 if (TemplateArgLoc.isValid()) {
5232 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5233 NextDiag = diag::note_template_param_different_kind;
5235 S.Diag(New->getLocation(), NextDiag)
5236 << (Kind != Sema::TPL_TemplateMatch);
5237 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
5238 << (Kind != Sema::TPL_TemplateMatch);
5244 // Check that both are parameter packs are neither are parameter packs.
5245 // However, if we are matching a template template argument to a
5246 // template template parameter, the template template parameter can have
5247 // a parameter pack where the template template argument does not.
5248 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
5249 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5250 Old->isTemplateParameterPack())) {
5252 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
5253 if (TemplateArgLoc.isValid()) {
5254 S.Diag(TemplateArgLoc,
5255 diag::err_template_arg_template_params_mismatch);
5256 NextDiag = diag::note_template_parameter_pack_non_pack;
5259 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
5260 : isa<NonTypeTemplateParmDecl>(New)? 1
5262 S.Diag(New->getLocation(), NextDiag)
5263 << ParamKind << New->isParameterPack();
5264 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
5265 << ParamKind << Old->isParameterPack();
5271 // For non-type template parameters, check the type of the parameter.
5272 if (NonTypeTemplateParmDecl *OldNTTP
5273 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
5274 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
5276 // If we are matching a template template argument to a template
5277 // template parameter and one of the non-type template parameter types
5278 // is dependent, then we must wait until template instantiation time
5279 // to actually compare the arguments.
5280 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5281 (OldNTTP->getType()->isDependentType() ||
5282 NewNTTP->getType()->isDependentType()))
5285 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
5287 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
5288 if (TemplateArgLoc.isValid()) {
5289 S.Diag(TemplateArgLoc,
5290 diag::err_template_arg_template_params_mismatch);
5291 NextDiag = diag::note_template_nontype_parm_different_type;
5293 S.Diag(NewNTTP->getLocation(), NextDiag)
5294 << NewNTTP->getType()
5295 << (Kind != Sema::TPL_TemplateMatch);
5296 S.Diag(OldNTTP->getLocation(),
5297 diag::note_template_nontype_parm_prev_declaration)
5298 << OldNTTP->getType();
5307 // For template template parameters, check the template parameter types.
5308 // The template parameter lists of template template
5309 // parameters must agree.
5310 if (TemplateTemplateParmDecl *OldTTP
5311 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
5312 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
5313 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
5314 OldTTP->getTemplateParameters(),
5316 (Kind == Sema::TPL_TemplateMatch
5317 ? Sema::TPL_TemplateTemplateParmMatch
5325 /// \brief Diagnose a known arity mismatch when comparing template argument
5328 void DiagnoseTemplateParameterListArityMismatch(Sema &S,
5329 TemplateParameterList *New,
5330 TemplateParameterList *Old,
5331 Sema::TemplateParameterListEqualKind Kind,
5332 SourceLocation TemplateArgLoc) {
5333 unsigned NextDiag = diag::err_template_param_list_different_arity;
5334 if (TemplateArgLoc.isValid()) {
5335 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5336 NextDiag = diag::note_template_param_list_different_arity;
5338 S.Diag(New->getTemplateLoc(), NextDiag)
5339 << (New->size() > Old->size())
5340 << (Kind != Sema::TPL_TemplateMatch)
5341 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
5342 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
5343 << (Kind != Sema::TPL_TemplateMatch)
5344 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
5347 /// \brief Determine whether the given template parameter lists are
5350 /// \param New The new template parameter list, typically written in the
5351 /// source code as part of a new template declaration.
5353 /// \param Old The old template parameter list, typically found via
5354 /// name lookup of the template declared with this template parameter
5357 /// \param Complain If true, this routine will produce a diagnostic if
5358 /// the template parameter lists are not equivalent.
5360 /// \param Kind describes how we are to match the template parameter lists.
5362 /// \param TemplateArgLoc If this source location is valid, then we
5363 /// are actually checking the template parameter list of a template
5364 /// argument (New) against the template parameter list of its
5365 /// corresponding template template parameter (Old). We produce
5366 /// slightly different diagnostics in this scenario.
5368 /// \returns True if the template parameter lists are equal, false
5371 Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
5372 TemplateParameterList *Old,
5374 TemplateParameterListEqualKind Kind,
5375 SourceLocation TemplateArgLoc) {
5376 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
5378 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5384 // C++0x [temp.arg.template]p3:
5385 // A template-argument matches a template template-parameter (call it P)
5386 // when each of the template parameters in the template-parameter-list of
5387 // the template-argument's corresponding class template or alias template
5388 // (call it A) matches the corresponding template parameter in the
5389 // template-parameter-list of P. [...]
5390 TemplateParameterList::iterator NewParm = New->begin();
5391 TemplateParameterList::iterator NewParmEnd = New->end();
5392 for (TemplateParameterList::iterator OldParm = Old->begin(),
5393 OldParmEnd = Old->end();
5394 OldParm != OldParmEnd; ++OldParm) {
5395 if (Kind != TPL_TemplateTemplateArgumentMatch ||
5396 !(*OldParm)->isTemplateParameterPack()) {
5397 if (NewParm == NewParmEnd) {
5399 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5405 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5406 Kind, TemplateArgLoc))
5413 // C++0x [temp.arg.template]p3:
5414 // [...] When P's template- parameter-list contains a template parameter
5415 // pack (14.5.3), the template parameter pack will match zero or more
5416 // template parameters or template parameter packs in the
5417 // template-parameter-list of A with the same type and form as the
5418 // template parameter pack in P (ignoring whether those template
5419 // parameters are template parameter packs).
5420 for (; NewParm != NewParmEnd; ++NewParm) {
5421 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5422 Kind, TemplateArgLoc))
5427 // Make sure we exhausted all of the arguments.
5428 if (NewParm != NewParmEnd) {
5430 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5439 /// \brief Check whether a template can be declared within this scope.
5441 /// If the template declaration is valid in this scope, returns
5442 /// false. Otherwise, issues a diagnostic and returns true.
5444 Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
5448 // Find the nearest enclosing declaration scope.
5449 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5450 (S->getFlags() & Scope::TemplateParamScope) != 0)
5454 // A template-declaration can appear only as a namespace scope or
5455 // class scope declaration.
5456 DeclContext *Ctx = S->getEntity();
5457 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
5458 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
5459 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
5460 << TemplateParams->getSourceRange();
5462 while (Ctx && isa<LinkageSpecDecl>(Ctx))
5463 Ctx = Ctx->getParent();
5466 if (Ctx->isFileContext())
5468 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
5469 // C++ [temp.mem]p2:
5470 // A local class shall not have member templates.
5471 if (RD->isLocalClass())
5472 return Diag(TemplateParams->getTemplateLoc(),
5473 diag::err_template_inside_local_class)
5474 << TemplateParams->getSourceRange();
5480 return Diag(TemplateParams->getTemplateLoc(),
5481 diag::err_template_outside_namespace_or_class_scope)
5482 << TemplateParams->getSourceRange();
5485 /// \brief Determine what kind of template specialization the given declaration
5487 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
5489 return TSK_Undeclared;
5491 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
5492 return Record->getTemplateSpecializationKind();
5493 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
5494 return Function->getTemplateSpecializationKind();
5495 if (VarDecl *Var = dyn_cast<VarDecl>(D))
5496 return Var->getTemplateSpecializationKind();
5498 return TSK_Undeclared;
5501 /// \brief Check whether a specialization is well-formed in the current
5504 /// This routine determines whether a template specialization can be declared
5505 /// in the current context (C++ [temp.expl.spec]p2).
5507 /// \param S the semantic analysis object for which this check is being
5510 /// \param Specialized the entity being specialized or instantiated, which
5511 /// may be a kind of template (class template, function template, etc.) or
5512 /// a member of a class template (member function, static data member,
5515 /// \param PrevDecl the previous declaration of this entity, if any.
5517 /// \param Loc the location of the explicit specialization or instantiation of
5520 /// \param IsPartialSpecialization whether this is a partial specialization of
5521 /// a class template.
5523 /// \returns true if there was an error that we cannot recover from, false
5525 static bool CheckTemplateSpecializationScope(Sema &S,
5526 NamedDecl *Specialized,
5527 NamedDecl *PrevDecl,
5529 bool IsPartialSpecialization) {
5530 // Keep these "kind" numbers in sync with the %select statements in the
5531 // various diagnostics emitted by this routine.
5533 if (isa<ClassTemplateDecl>(Specialized))
5534 EntityKind = IsPartialSpecialization? 1 : 0;
5535 else if (isa<VarTemplateDecl>(Specialized))
5536 EntityKind = IsPartialSpecialization ? 3 : 2;
5537 else if (isa<FunctionTemplateDecl>(Specialized))
5539 else if (isa<CXXMethodDecl>(Specialized))
5541 else if (isa<VarDecl>(Specialized))
5543 else if (isa<RecordDecl>(Specialized))
5545 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
5548 S.Diag(Loc, diag::err_template_spec_unknown_kind)
5549 << S.getLangOpts().CPlusPlus11;
5550 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5554 // C++ [temp.expl.spec]p2:
5555 // An explicit specialization shall be declared in the namespace
5556 // of which the template is a member, or, for member templates, in
5557 // the namespace of which the enclosing class or enclosing class
5558 // template is a member. An explicit specialization of a member
5559 // function, member class or static data member of a class
5560 // template shall be declared in the namespace of which the class
5561 // template is a member. Such a declaration may also be a
5562 // definition. If the declaration is not a definition, the
5563 // specialization may be defined later in the name- space in which
5564 // the explicit specialization was declared, or in a namespace
5565 // that encloses the one in which the explicit specialization was
5567 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
5568 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
5573 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
5574 if (S.getLangOpts().MicrosoftExt) {
5575 // Do not warn for class scope explicit specialization during
5576 // instantiation, warning was already emitted during pattern
5577 // semantic analysis.
5578 if (!S.ActiveTemplateInstantiations.size())
5579 S.Diag(Loc, diag::ext_function_specialization_in_class)
5582 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5588 if (S.CurContext->isRecord() &&
5589 !S.CurContext->Equals(Specialized->getDeclContext())) {
5590 // Make sure that we're specializing in the right record context.
5591 // Otherwise, things can go horribly wrong.
5592 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5597 // C++ [temp.class.spec]p6:
5598 // A class template partial specialization may be declared or redeclared
5599 // in any namespace scope in which its definition may be defined (14.5.1
5601 bool ComplainedAboutScope = false;
5602 DeclContext *SpecializedContext
5603 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
5604 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
5606 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
5607 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
5608 // C++ [temp.exp.spec]p2:
5609 // An explicit specialization shall be declared in the namespace of which
5610 // the template is a member, or, for member templates, in the namespace
5611 // of which the enclosing class or enclosing class template is a member.
5612 // An explicit specialization of a member function, member class or
5613 // static data member of a class template shall be declared in the
5614 // namespace of which the class template is a member.
5616 // C++0x [temp.expl.spec]p2:
5617 // An explicit specialization shall be declared in a namespace enclosing
5618 // the specialized template.
5619 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
5620 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
5621 if (isa<TranslationUnitDecl>(SpecializedContext)) {
5622 assert(!IsCPlusPlus11Extension &&
5623 "DC encloses TU but isn't in enclosing namespace set");
5624 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
5625 << EntityKind << Specialized;
5626 } else if (isa<NamespaceDecl>(SpecializedContext)) {
5628 if (!IsCPlusPlus11Extension)
5629 Diag = diag::err_template_spec_decl_out_of_scope;
5630 else if (!S.getLangOpts().CPlusPlus11)
5631 Diag = diag::ext_template_spec_decl_out_of_scope;
5633 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
5635 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
5638 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5639 ComplainedAboutScope =
5640 !(IsCPlusPlus11Extension && S.getLangOpts().CPlusPlus11);
5644 // Make sure that this redeclaration (or definition) occurs in an enclosing
5646 // Note that HandleDeclarator() performs this check for explicit
5647 // specializations of function templates, static data members, and member
5648 // functions, so we skip the check here for those kinds of entities.
5649 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
5650 // Should we refactor that check, so that it occurs later?
5651 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
5652 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
5653 isa<FunctionDecl>(Specialized))) {
5654 if (isa<TranslationUnitDecl>(SpecializedContext))
5655 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
5656 << EntityKind << Specialized;
5657 else if (isa<NamespaceDecl>(SpecializedContext))
5658 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
5659 << EntityKind << Specialized
5660 << cast<NamedDecl>(SpecializedContext);
5662 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5665 // FIXME: check for specialization-after-instantiation errors and such.
5670 /// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
5671 /// that checks non-type template partial specialization arguments.
5672 static bool CheckNonTypeTemplatePartialSpecializationArgs(
5673 Sema &S, NonTypeTemplateParmDecl *Param, const TemplateArgument *Args,
5675 for (unsigned I = 0; I != NumArgs; ++I) {
5676 if (Args[I].getKind() == TemplateArgument::Pack) {
5677 if (CheckNonTypeTemplatePartialSpecializationArgs(
5678 S, Param, Args[I].pack_begin(), Args[I].pack_size()))
5684 if (Args[I].getKind() != TemplateArgument::Expression)
5687 Expr *ArgExpr = Args[I].getAsExpr();
5689 // We can have a pack expansion of any of the bullets below.
5690 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
5691 ArgExpr = Expansion->getPattern();
5693 // Strip off any implicit casts we added as part of type checking.
5694 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
5695 ArgExpr = ICE->getSubExpr();
5697 // C++ [temp.class.spec]p8:
5698 // A non-type argument is non-specialized if it is the name of a
5699 // non-type parameter. All other non-type arguments are
5702 // Below, we check the two conditions that only apply to
5703 // specialized non-type arguments, so skip any non-specialized
5705 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
5706 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
5709 // C++ [temp.class.spec]p9:
5710 // Within the argument list of a class template partial
5711 // specialization, the following restrictions apply:
5712 // -- A partially specialized non-type argument expression
5713 // shall not involve a template parameter of the partial
5714 // specialization except when the argument expression is a
5715 // simple identifier.
5716 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
5717 S.Diag(ArgExpr->getLocStart(),
5718 diag::err_dependent_non_type_arg_in_partial_spec)
5719 << ArgExpr->getSourceRange();
5723 // -- The type of a template parameter corresponding to a
5724 // specialized non-type argument shall not be dependent on a
5725 // parameter of the specialization.
5726 if (Param->getType()->isDependentType()) {
5727 S.Diag(ArgExpr->getLocStart(),
5728 diag::err_dependent_typed_non_type_arg_in_partial_spec)
5730 << ArgExpr->getSourceRange();
5731 S.Diag(Param->getLocation(), diag::note_template_param_here);
5739 /// \brief Check the non-type template arguments of a class template
5740 /// partial specialization according to C++ [temp.class.spec]p9.
5742 /// \param TemplateParams the template parameters of the primary class
5745 /// \param TemplateArgs the template arguments of the class template
5746 /// partial specialization.
5748 /// \returns true if there was an error, false otherwise.
5749 static bool CheckTemplatePartialSpecializationArgs(
5750 Sema &S, TemplateParameterList *TemplateParams,
5751 SmallVectorImpl<TemplateArgument> &TemplateArgs) {
5752 const TemplateArgument *ArgList = TemplateArgs.data();
5754 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
5755 NonTypeTemplateParmDecl *Param
5756 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
5760 if (CheckNonTypeTemplatePartialSpecializationArgs(S, Param, &ArgList[I], 1))
5768 Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
5770 SourceLocation KWLoc,
5771 SourceLocation ModulePrivateLoc,
5773 TemplateTy TemplateD,
5774 SourceLocation TemplateNameLoc,
5775 SourceLocation LAngleLoc,
5776 ASTTemplateArgsPtr TemplateArgsIn,
5777 SourceLocation RAngleLoc,
5778 AttributeList *Attr,
5779 MultiTemplateParamsArg TemplateParameterLists) {
5780 assert(TUK != TUK_Reference && "References are not specializations");
5782 // NOTE: KWLoc is the location of the tag keyword. This will instead
5783 // store the location of the outermost template keyword in the declaration.
5784 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
5785 ? TemplateParameterLists[0]->getTemplateLoc() : SourceLocation();
5787 // Find the class template we're specializing
5788 TemplateName Name = TemplateD.get();
5789 ClassTemplateDecl *ClassTemplate
5790 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
5792 if (!ClassTemplate) {
5793 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
5794 << (Name.getAsTemplateDecl() &&
5795 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
5799 bool isExplicitSpecialization = false;
5800 bool isPartialSpecialization = false;
5802 // Check the validity of the template headers that introduce this
5804 // FIXME: We probably shouldn't complain about these headers for
5805 // friend declarations.
5806 bool Invalid = false;
5807 TemplateParameterList *TemplateParams =
5808 MatchTemplateParametersToScopeSpecifier(
5809 TemplateNameLoc, TemplateNameLoc, SS, TemplateParameterLists,
5810 TUK == TUK_Friend, isExplicitSpecialization, Invalid);
5814 if (TemplateParams && TemplateParams->size() > 0) {
5815 isPartialSpecialization = true;
5817 if (TUK == TUK_Friend) {
5818 Diag(KWLoc, diag::err_partial_specialization_friend)
5819 << SourceRange(LAngleLoc, RAngleLoc);
5823 // C++ [temp.class.spec]p10:
5824 // The template parameter list of a specialization shall not
5825 // contain default template argument values.
5826 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
5827 Decl *Param = TemplateParams->getParam(I);
5828 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
5829 if (TTP->hasDefaultArgument()) {
5830 Diag(TTP->getDefaultArgumentLoc(),
5831 diag::err_default_arg_in_partial_spec);
5832 TTP->removeDefaultArgument();
5834 } else if (NonTypeTemplateParmDecl *NTTP
5835 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5836 if (Expr *DefArg = NTTP->getDefaultArgument()) {
5837 Diag(NTTP->getDefaultArgumentLoc(),
5838 diag::err_default_arg_in_partial_spec)
5839 << DefArg->getSourceRange();
5840 NTTP->removeDefaultArgument();
5843 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
5844 if (TTP->hasDefaultArgument()) {
5845 Diag(TTP->getDefaultArgument().getLocation(),
5846 diag::err_default_arg_in_partial_spec)
5847 << TTP->getDefaultArgument().getSourceRange();
5848 TTP->removeDefaultArgument();
5852 } else if (TemplateParams) {
5853 if (TUK == TUK_Friend)
5854 Diag(KWLoc, diag::err_template_spec_friend)
5855 << FixItHint::CreateRemoval(
5856 SourceRange(TemplateParams->getTemplateLoc(),
5857 TemplateParams->getRAngleLoc()))
5858 << SourceRange(LAngleLoc, RAngleLoc);
5860 isExplicitSpecialization = true;
5861 } else if (TUK != TUK_Friend) {
5862 Diag(KWLoc, diag::err_template_spec_needs_header)
5863 << FixItHint::CreateInsertion(KWLoc, "template<> ");
5864 TemplateKWLoc = KWLoc;
5865 isExplicitSpecialization = true;
5868 // Check that the specialization uses the same tag kind as the
5869 // original template.
5870 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
5871 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
5872 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
5873 Kind, TUK == TUK_Definition, KWLoc,
5874 *ClassTemplate->getIdentifier())) {
5875 Diag(KWLoc, diag::err_use_with_wrong_tag)
5877 << FixItHint::CreateReplacement(KWLoc,
5878 ClassTemplate->getTemplatedDecl()->getKindName());
5879 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
5880 diag::note_previous_use);
5881 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
5884 // Translate the parser's template argument list in our AST format.
5885 TemplateArgumentListInfo TemplateArgs;
5886 TemplateArgs.setLAngleLoc(LAngleLoc);
5887 TemplateArgs.setRAngleLoc(RAngleLoc);
5888 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
5890 // Check for unexpanded parameter packs in any of the template arguments.
5891 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
5892 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
5893 UPPC_PartialSpecialization))
5896 // Check that the template argument list is well-formed for this
5898 SmallVector<TemplateArgument, 4> Converted;
5899 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
5900 TemplateArgs, false, Converted))
5903 // Find the class template (partial) specialization declaration that
5904 // corresponds to these arguments.
5905 if (isPartialSpecialization) {
5906 if (CheckTemplatePartialSpecializationArgs(
5907 *this, ClassTemplate->getTemplateParameters(), Converted))
5910 bool InstantiationDependent;
5911 if (!Name.isDependent() &&
5912 !TemplateSpecializationType::anyDependentTemplateArguments(
5913 TemplateArgs.getArgumentArray(),
5914 TemplateArgs.size(),
5915 InstantiationDependent)) {
5916 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
5917 << ClassTemplate->getDeclName();
5918 isPartialSpecialization = false;
5922 void *InsertPos = 0;
5923 ClassTemplateSpecializationDecl *PrevDecl = 0;
5925 if (isPartialSpecialization)
5926 // FIXME: Template parameter list matters, too
5928 = ClassTemplate->findPartialSpecialization(Converted.data(),
5933 = ClassTemplate->findSpecialization(Converted.data(),
5934 Converted.size(), InsertPos);
5936 ClassTemplateSpecializationDecl *Specialization = 0;
5938 // Check whether we can declare a class template specialization in
5939 // the current scope.
5940 if (TUK != TUK_Friend &&
5941 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
5943 isPartialSpecialization))
5946 // The canonical type
5949 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
5950 TUK == TUK_Friend)) {
5951 // Since the only prior class template specialization with these
5952 // arguments was referenced but not declared, or we're only
5953 // referencing this specialization as a friend, reuse that
5954 // declaration node as our own, updating its source location and
5955 // the list of outer template parameters to reflect our new declaration.
5956 Specialization = PrevDecl;
5957 Specialization->setLocation(TemplateNameLoc);
5958 if (TemplateParameterLists.size() > 0) {
5959 Specialization->setTemplateParameterListsInfo(Context,
5960 TemplateParameterLists.size(),
5961 TemplateParameterLists.data());
5964 CanonType = Context.getTypeDeclType(Specialization);
5965 } else if (isPartialSpecialization) {
5966 // Build the canonical type that describes the converted template
5967 // arguments of the class template partial specialization.
5968 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
5969 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
5973 if (Context.hasSameType(CanonType,
5974 ClassTemplate->getInjectedClassNameSpecialization())) {
5975 // C++ [temp.class.spec]p9b3:
5977 // -- The argument list of the specialization shall not be identical
5978 // to the implicit argument list of the primary template.
5979 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
5980 << /*class template*/0 << (TUK == TUK_Definition)
5981 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
5982 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
5983 ClassTemplate->getIdentifier(),
5987 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
5988 TemplateParameterLists.size() - 1,
5989 TemplateParameterLists.data());
5992 // Create a new class template partial specialization declaration node.
5993 ClassTemplatePartialSpecializationDecl *PrevPartial
5994 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
5995 ClassTemplatePartialSpecializationDecl *Partial
5996 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
5997 ClassTemplate->getDeclContext(),
5998 KWLoc, TemplateNameLoc,
6006 SetNestedNameSpecifier(Partial, SS);
6007 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
6008 Partial->setTemplateParameterListsInfo(Context,
6009 TemplateParameterLists.size() - 1,
6010 TemplateParameterLists.data());
6014 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
6015 Specialization = Partial;
6017 // If we are providing an explicit specialization of a member class
6018 // template specialization, make a note of that.
6019 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
6020 PrevPartial->setMemberSpecialization();
6022 // Check that all of the template parameters of the class template
6023 // partial specialization are deducible from the template
6024 // arguments. If not, this class template partial specialization
6025 // will never be used.
6026 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
6027 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
6028 TemplateParams->getDepth(),
6031 if (!DeducibleParams.all()) {
6032 unsigned NumNonDeducible = DeducibleParams.size()-DeducibleParams.count();
6033 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
6034 << /*class template*/0 << (NumNonDeducible > 1)
6035 << SourceRange(TemplateNameLoc, RAngleLoc);
6036 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
6037 if (!DeducibleParams[I]) {
6038 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
6039 if (Param->getDeclName())
6040 Diag(Param->getLocation(),
6041 diag::note_partial_spec_unused_parameter)
6042 << Param->getDeclName();
6044 Diag(Param->getLocation(),
6045 diag::note_partial_spec_unused_parameter)
6051 // Create a new class template specialization declaration node for
6052 // this explicit specialization or friend declaration.
6054 = ClassTemplateSpecializationDecl::Create(Context, Kind,
6055 ClassTemplate->getDeclContext(),
6056 KWLoc, TemplateNameLoc,
6061 SetNestedNameSpecifier(Specialization, SS);
6062 if (TemplateParameterLists.size() > 0) {
6063 Specialization->setTemplateParameterListsInfo(Context,
6064 TemplateParameterLists.size(),
6065 TemplateParameterLists.data());
6069 ClassTemplate->AddSpecialization(Specialization, InsertPos);
6071 CanonType = Context.getTypeDeclType(Specialization);
6074 // C++ [temp.expl.spec]p6:
6075 // If a template, a member template or the member of a class template is
6076 // explicitly specialized then that specialization shall be declared
6077 // before the first use of that specialization that would cause an implicit
6078 // instantiation to take place, in every translation unit in which such a
6079 // use occurs; no diagnostic is required.
6080 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
6082 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
6083 // Is there any previous explicit specialization declaration?
6084 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6091 SourceRange Range(TemplateNameLoc, RAngleLoc);
6092 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
6093 << Context.getTypeDeclType(Specialization) << Range;
6095 Diag(PrevDecl->getPointOfInstantiation(),
6096 diag::note_instantiation_required_here)
6097 << (PrevDecl->getTemplateSpecializationKind()
6098 != TSK_ImplicitInstantiation);
6103 // If this is not a friend, note that this is an explicit specialization.
6104 if (TUK != TUK_Friend)
6105 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
6107 // Check that this isn't a redefinition of this specialization.
6108 if (TUK == TUK_Definition) {
6109 if (RecordDecl *Def = Specialization->getDefinition()) {
6110 SourceRange Range(TemplateNameLoc, RAngleLoc);
6111 Diag(TemplateNameLoc, diag::err_redefinition)
6112 << Context.getTypeDeclType(Specialization) << Range;
6113 Diag(Def->getLocation(), diag::note_previous_definition);
6114 Specialization->setInvalidDecl();
6120 ProcessDeclAttributeList(S, Specialization, Attr);
6122 // Add alignment attributes if necessary; these attributes are checked when
6123 // the ASTContext lays out the structure.
6124 if (TUK == TUK_Definition) {
6125 AddAlignmentAttributesForRecord(Specialization);
6126 AddMsStructLayoutForRecord(Specialization);
6129 if (ModulePrivateLoc.isValid())
6130 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
6131 << (isPartialSpecialization? 1 : 0)
6132 << FixItHint::CreateRemoval(ModulePrivateLoc);
6134 // Build the fully-sugared type for this class template
6135 // specialization as the user wrote in the specialization
6136 // itself. This means that we'll pretty-print the type retrieved
6137 // from the specialization's declaration the way that the user
6138 // actually wrote the specialization, rather than formatting the
6139 // name based on the "canonical" representation used to store the
6140 // template arguments in the specialization.
6141 TypeSourceInfo *WrittenTy
6142 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
6143 TemplateArgs, CanonType);
6144 if (TUK != TUK_Friend) {
6145 Specialization->setTypeAsWritten(WrittenTy);
6146 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
6149 // C++ [temp.expl.spec]p9:
6150 // A template explicit specialization is in the scope of the
6151 // namespace in which the template was defined.
6153 // We actually implement this paragraph where we set the semantic
6154 // context (in the creation of the ClassTemplateSpecializationDecl),
6155 // but we also maintain the lexical context where the actual
6156 // definition occurs.
6157 Specialization->setLexicalDeclContext(CurContext);
6159 // We may be starting the definition of this specialization.
6160 if (TUK == TUK_Definition)
6161 Specialization->startDefinition();
6163 if (TUK == TUK_Friend) {
6164 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
6168 Friend->setAccess(AS_public);
6169 CurContext->addDecl(Friend);
6171 // Add the specialization into its lexical context, so that it can
6172 // be seen when iterating through the list of declarations in that
6173 // context. However, specializations are not found by name lookup.
6174 CurContext->addDecl(Specialization);
6176 return Specialization;
6179 Decl *Sema::ActOnTemplateDeclarator(Scope *S,
6180 MultiTemplateParamsArg TemplateParameterLists,
6182 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
6183 ActOnDocumentableDecl(NewDecl);
6187 Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
6188 MultiTemplateParamsArg TemplateParameterLists,
6190 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
6191 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6193 if (FTI.hasPrototype) {
6194 // FIXME: Diagnose arguments without names in C.
6197 Scope *ParentScope = FnBodyScope->getParent();
6199 D.setFunctionDefinitionKind(FDK_Definition);
6200 Decl *DP = HandleDeclarator(ParentScope, D,
6201 TemplateParameterLists);
6202 return ActOnStartOfFunctionDef(FnBodyScope, DP);
6205 /// \brief Strips various properties off an implicit instantiation
6206 /// that has just been explicitly specialized.
6207 static void StripImplicitInstantiation(NamedDecl *D) {
6210 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6211 FD->setInlineSpecified(false);
6213 for (FunctionDecl::param_iterator I = FD->param_begin(),
6214 E = FD->param_end();
6220 /// \brief Compute the diagnostic location for an explicit instantiation
6221 // declaration or definition.
6222 static SourceLocation DiagLocForExplicitInstantiation(
6223 NamedDecl* D, SourceLocation PointOfInstantiation) {
6224 // Explicit instantiations following a specialization have no effect and
6225 // hence no PointOfInstantiation. In that case, walk decl backwards
6226 // until a valid name loc is found.
6227 SourceLocation PrevDiagLoc = PointOfInstantiation;
6228 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
6229 Prev = Prev->getPreviousDecl()) {
6230 PrevDiagLoc = Prev->getLocation();
6232 assert(PrevDiagLoc.isValid() &&
6233 "Explicit instantiation without point of instantiation?");
6237 /// \brief Diagnose cases where we have an explicit template specialization
6238 /// before/after an explicit template instantiation, producing diagnostics
6239 /// for those cases where they are required and determining whether the
6240 /// new specialization/instantiation will have any effect.
6242 /// \param NewLoc the location of the new explicit specialization or
6245 /// \param NewTSK the kind of the new explicit specialization or instantiation.
6247 /// \param PrevDecl the previous declaration of the entity.
6249 /// \param PrevTSK the kind of the old explicit specialization or instantiatin.
6251 /// \param PrevPointOfInstantiation if valid, indicates where the previus
6252 /// declaration was instantiated (either implicitly or explicitly).
6254 /// \param HasNoEffect will be set to true to indicate that the new
6255 /// specialization or instantiation has no effect and should be ignored.
6257 /// \returns true if there was an error that should prevent the introduction of
6258 /// the new declaration into the AST, false otherwise.
6260 Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6261 TemplateSpecializationKind NewTSK,
6262 NamedDecl *PrevDecl,
6263 TemplateSpecializationKind PrevTSK,
6264 SourceLocation PrevPointOfInstantiation,
6265 bool &HasNoEffect) {
6266 HasNoEffect = false;
6269 case TSK_Undeclared:
6270 case TSK_ImplicitInstantiation:
6272 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
6273 "previous declaration must be implicit!");
6276 case TSK_ExplicitSpecialization:
6278 case TSK_Undeclared:
6279 case TSK_ExplicitSpecialization:
6280 // Okay, we're just specializing something that is either already
6281 // explicitly specialized or has merely been mentioned without any
6285 case TSK_ImplicitInstantiation:
6286 if (PrevPointOfInstantiation.isInvalid()) {
6287 // The declaration itself has not actually been instantiated, so it is
6288 // still okay to specialize it.
6289 StripImplicitInstantiation(PrevDecl);
6294 case TSK_ExplicitInstantiationDeclaration:
6295 case TSK_ExplicitInstantiationDefinition:
6296 assert((PrevTSK == TSK_ImplicitInstantiation ||
6297 PrevPointOfInstantiation.isValid()) &&
6298 "Explicit instantiation without point of instantiation?");
6300 // C++ [temp.expl.spec]p6:
6301 // If a template, a member template or the member of a class template
6302 // is explicitly specialized then that specialization shall be declared
6303 // before the first use of that specialization that would cause an
6304 // implicit instantiation to take place, in every translation unit in
6305 // which such a use occurs; no diagnostic is required.
6306 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
6307 // Is there any previous explicit specialization declaration?
6308 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
6312 Diag(NewLoc, diag::err_specialization_after_instantiation)
6314 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
6315 << (PrevTSK != TSK_ImplicitInstantiation);
6320 case TSK_ExplicitInstantiationDeclaration:
6322 case TSK_ExplicitInstantiationDeclaration:
6323 // This explicit instantiation declaration is redundant (that's okay).
6327 case TSK_Undeclared:
6328 case TSK_ImplicitInstantiation:
6329 // We're explicitly instantiating something that may have already been
6330 // implicitly instantiated; that's fine.
6333 case TSK_ExplicitSpecialization:
6334 // C++0x [temp.explicit]p4:
6335 // For a given set of template parameters, if an explicit instantiation
6336 // of a template appears after a declaration of an explicit
6337 // specialization for that template, the explicit instantiation has no
6342 case TSK_ExplicitInstantiationDefinition:
6343 // C++0x [temp.explicit]p10:
6344 // If an entity is the subject of both an explicit instantiation
6345 // declaration and an explicit instantiation definition in the same
6346 // translation unit, the definition shall follow the declaration.
6348 diag::err_explicit_instantiation_declaration_after_definition);
6350 // Explicit instantiations following a specialization have no effect and
6351 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
6352 // until a valid name loc is found.
6353 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6354 diag::note_explicit_instantiation_definition_here);
6359 case TSK_ExplicitInstantiationDefinition:
6361 case TSK_Undeclared:
6362 case TSK_ImplicitInstantiation:
6363 // We're explicitly instantiating something that may have already been
6364 // implicitly instantiated; that's fine.
6367 case TSK_ExplicitSpecialization:
6368 // C++ DR 259, C++0x [temp.explicit]p4:
6369 // For a given set of template parameters, if an explicit
6370 // instantiation of a template appears after a declaration of
6371 // an explicit specialization for that template, the explicit
6372 // instantiation has no effect.
6374 // In C++98/03 mode, we only give an extension warning here, because it
6375 // is not harmful to try to explicitly instantiate something that
6376 // has been explicitly specialized.
6377 Diag(NewLoc, getLangOpts().CPlusPlus11 ?
6378 diag::warn_cxx98_compat_explicit_instantiation_after_specialization :
6379 diag::ext_explicit_instantiation_after_specialization)
6381 Diag(PrevDecl->getLocation(),
6382 diag::note_previous_template_specialization);
6386 case TSK_ExplicitInstantiationDeclaration:
6387 // We're explicity instantiating a definition for something for which we
6388 // were previously asked to suppress instantiations. That's fine.
6390 // C++0x [temp.explicit]p4:
6391 // For a given set of template parameters, if an explicit instantiation
6392 // of a template appears after a declaration of an explicit
6393 // specialization for that template, the explicit instantiation has no
6395 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
6396 // Is there any previous explicit specialization declaration?
6397 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6405 case TSK_ExplicitInstantiationDefinition:
6406 // C++0x [temp.spec]p5:
6407 // For a given template and a given set of template-arguments,
6408 // - an explicit instantiation definition shall appear at most once
6410 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
6412 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6413 diag::note_previous_explicit_instantiation);
6419 llvm_unreachable("Missing specialization/instantiation case?");
6422 /// \brief Perform semantic analysis for the given dependent function
6423 /// template specialization.
6425 /// The only possible way to get a dependent function template specialization
6426 /// is with a friend declaration, like so:
6429 /// template \<class T> void foo(T);
6430 /// template \<class T> class A {
6431 /// friend void foo<>(T);
6435 /// There really isn't any useful analysis we can do here, so we
6436 /// just store the information.
6438 Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6439 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6440 LookupResult &Previous) {
6441 // Remove anything from Previous that isn't a function template in
6442 // the correct context.
6443 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
6444 LookupResult::Filter F = Previous.makeFilter();
6445 while (F.hasNext()) {
6446 NamedDecl *D = F.next()->getUnderlyingDecl();
6447 if (!isa<FunctionTemplateDecl>(D) ||
6448 !FDLookupContext->InEnclosingNamespaceSetOf(
6449 D->getDeclContext()->getRedeclContext()))
6454 // Should this be diagnosed here?
6455 if (Previous.empty()) return true;
6457 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
6458 ExplicitTemplateArgs);
6462 /// \brief Perform semantic analysis for the given function template
6465 /// This routine performs all of the semantic analysis required for an
6466 /// explicit function template specialization. On successful completion,
6467 /// the function declaration \p FD will become a function template
6470 /// \param FD the function declaration, which will be updated to become a
6471 /// function template specialization.
6473 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
6474 /// if any. Note that this may be valid info even when 0 arguments are
6475 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
6476 /// as it anyway contains info on the angle brackets locations.
6478 /// \param Previous the set of declarations that may be specialized by
6479 /// this function specialization.
6480 bool Sema::CheckFunctionTemplateSpecialization(
6481 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
6482 LookupResult &Previous) {
6483 // The set of function template specializations that could match this
6484 // explicit function template specialization.
6485 UnresolvedSet<8> Candidates;
6486 TemplateSpecCandidateSet FailedCandidates(FD->getLocation());
6488 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
6489 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6491 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
6492 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
6493 // Only consider templates found within the same semantic lookup scope as
6495 if (!FDLookupContext->InEnclosingNamespaceSetOf(
6496 Ovl->getDeclContext()->getRedeclContext()))
6499 // When matching a constexpr member function template specialization
6500 // against the primary template, we don't yet know whether the
6501 // specialization has an implicit 'const' (because we don't know whether
6502 // it will be a static member function until we know which template it
6503 // specializes), so adjust it now assuming it specializes this template.
6504 QualType FT = FD->getType();
6505 if (FD->isConstexpr()) {
6506 CXXMethodDecl *OldMD =
6507 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
6508 if (OldMD && OldMD->isConst()) {
6509 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
6510 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6511 EPI.TypeQuals |= Qualifiers::Const;
6512 FT = Context.getFunctionType(FPT->getResultType(), FPT->getArgTypes(),
6517 // C++ [temp.expl.spec]p11:
6518 // A trailing template-argument can be left unspecified in the
6519 // template-id naming an explicit function template specialization
6520 // provided it can be deduced from the function argument type.
6521 // Perform template argument deduction to determine whether we may be
6522 // specializing this template.
6523 // FIXME: It is somewhat wasteful to build
6524 TemplateDeductionInfo Info(FailedCandidates.getLocation());
6525 FunctionDecl *Specialization = 0;
6526 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
6527 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
6528 ExplicitTemplateArgs, FT, Specialization, Info)) {
6529 // Template argument deduction failed; record why it failed, so
6530 // that we can provide nifty diagnostics.
6531 FailedCandidates.addCandidate()
6532 .set(FunTmpl->getTemplatedDecl(),
6533 MakeDeductionFailureInfo(Context, TDK, Info));
6538 // Record this candidate.
6539 Candidates.addDecl(Specialization, I.getAccess());
6543 // Find the most specialized function template.
6544 UnresolvedSetIterator Result = getMostSpecialized(
6545 Candidates.begin(), Candidates.end(), FailedCandidates,
6547 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
6548 PDiag(diag::err_function_template_spec_ambiguous)
6549 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
6550 PDiag(diag::note_function_template_spec_matched));
6552 if (Result == Candidates.end())
6555 // Ignore access information; it doesn't figure into redeclaration checking.
6556 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
6558 FunctionTemplateSpecializationInfo *SpecInfo
6559 = Specialization->getTemplateSpecializationInfo();
6560 assert(SpecInfo && "Function template specialization info missing?");
6562 // Note: do not overwrite location info if previous template
6563 // specialization kind was explicit.
6564 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
6565 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
6566 Specialization->setLocation(FD->getLocation());
6567 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
6568 // function can differ from the template declaration with respect to
6569 // the constexpr specifier.
6570 Specialization->setConstexpr(FD->isConstexpr());
6573 // FIXME: Check if the prior specialization has a point of instantiation.
6574 // If so, we have run afoul of .
6576 // If this is a friend declaration, then we're not really declaring
6577 // an explicit specialization.
6578 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
6580 // Check the scope of this explicit specialization.
6582 CheckTemplateSpecializationScope(*this,
6583 Specialization->getPrimaryTemplate(),
6584 Specialization, FD->getLocation(),
6588 // C++ [temp.expl.spec]p6:
6589 // If a template, a member template or the member of a class template is
6590 // explicitly specialized then that specialization shall be declared
6591 // before the first use of that specialization that would cause an implicit
6592 // instantiation to take place, in every translation unit in which such a
6593 // use occurs; no diagnostic is required.
6594 bool HasNoEffect = false;
6596 CheckSpecializationInstantiationRedecl(FD->getLocation(),
6597 TSK_ExplicitSpecialization,
6599 SpecInfo->getTemplateSpecializationKind(),
6600 SpecInfo->getPointOfInstantiation(),
6604 // Mark the prior declaration as an explicit specialization, so that later
6605 // clients know that this is an explicit specialization.
6607 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
6608 MarkUnusedFileScopedDecl(Specialization);
6611 // Turn the given function declaration into a function template
6612 // specialization, with the template arguments from the previous
6614 // Take copies of (semantic and syntactic) template argument lists.
6615 const TemplateArgumentList* TemplArgs = new (Context)
6616 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
6617 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
6618 TemplArgs, /*InsertPos=*/0,
6619 SpecInfo->getTemplateSpecializationKind(),
6620 ExplicitTemplateArgs);
6622 // The "previous declaration" for this function template specialization is
6623 // the prior function template specialization.
6625 Previous.addDecl(Specialization);
6629 /// \brief Perform semantic analysis for the given non-template member
6632 /// This routine performs all of the semantic analysis required for an
6633 /// explicit member function specialization. On successful completion,
6634 /// the function declaration \p FD will become a member function
6637 /// \param Member the member declaration, which will be updated to become a
6640 /// \param Previous the set of declarations, one of which may be specialized
6641 /// by this function specialization; the set will be modified to contain the
6642 /// redeclared member.
6644 Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
6645 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
6647 // Try to find the member we are instantiating.
6648 NamedDecl *Instantiation = 0;
6649 NamedDecl *InstantiatedFrom = 0;
6650 MemberSpecializationInfo *MSInfo = 0;
6652 if (Previous.empty()) {
6653 // Nowhere to look anyway.
6654 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
6655 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6657 NamedDecl *D = (*I)->getUnderlyingDecl();
6658 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
6659 if (Context.hasSameType(Function->getType(), Method->getType())) {
6660 Instantiation = Method;
6661 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
6662 MSInfo = Method->getMemberSpecializationInfo();
6667 } else if (isa<VarDecl>(Member)) {
6669 if (Previous.isSingleResult() &&
6670 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
6671 if (PrevVar->isStaticDataMember()) {
6672 Instantiation = PrevVar;
6673 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
6674 MSInfo = PrevVar->getMemberSpecializationInfo();
6676 } else if (isa<RecordDecl>(Member)) {
6677 CXXRecordDecl *PrevRecord;
6678 if (Previous.isSingleResult() &&
6679 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
6680 Instantiation = PrevRecord;
6681 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
6682 MSInfo = PrevRecord->getMemberSpecializationInfo();
6684 } else if (isa<EnumDecl>(Member)) {
6686 if (Previous.isSingleResult() &&
6687 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
6688 Instantiation = PrevEnum;
6689 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
6690 MSInfo = PrevEnum->getMemberSpecializationInfo();
6694 if (!Instantiation) {
6695 // There is no previous declaration that matches. Since member
6696 // specializations are always out-of-line, the caller will complain about
6697 // this mismatch later.
6701 // If this is a friend, just bail out here before we start turning
6702 // things into explicit specializations.
6703 if (Member->getFriendObjectKind() != Decl::FOK_None) {
6704 // Preserve instantiation information.
6705 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
6706 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
6707 cast<CXXMethodDecl>(InstantiatedFrom),
6708 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
6709 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
6710 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
6711 cast<CXXRecordDecl>(InstantiatedFrom),
6712 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
6716 Previous.addDecl(Instantiation);
6720 // Make sure that this is a specialization of a member.
6721 if (!InstantiatedFrom) {
6722 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
6724 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
6728 // C++ [temp.expl.spec]p6:
6729 // If a template, a member template or the member of a class template is
6730 // explicitly specialized then that specialization shall be declared
6731 // before the first use of that specialization that would cause an implicit
6732 // instantiation to take place, in every translation unit in which such a
6733 // use occurs; no diagnostic is required.
6734 assert(MSInfo && "Member specialization info missing?");
6736 bool HasNoEffect = false;
6737 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
6738 TSK_ExplicitSpecialization,
6740 MSInfo->getTemplateSpecializationKind(),
6741 MSInfo->getPointOfInstantiation(),
6745 // Check the scope of this explicit specialization.
6746 if (CheckTemplateSpecializationScope(*this,
6748 Instantiation, Member->getLocation(),
6752 // Note that this is an explicit instantiation of a member.
6753 // the original declaration to note that it is an explicit specialization
6754 // (if it was previously an implicit instantiation). This latter step
6755 // makes bookkeeping easier.
6756 if (isa<FunctionDecl>(Member)) {
6757 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
6758 if (InstantiationFunction->getTemplateSpecializationKind() ==
6759 TSK_ImplicitInstantiation) {
6760 InstantiationFunction->setTemplateSpecializationKind(
6761 TSK_ExplicitSpecialization);
6762 InstantiationFunction->setLocation(Member->getLocation());
6765 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
6766 cast<CXXMethodDecl>(InstantiatedFrom),
6767 TSK_ExplicitSpecialization);
6768 MarkUnusedFileScopedDecl(InstantiationFunction);
6769 } else if (isa<VarDecl>(Member)) {
6770 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
6771 if (InstantiationVar->getTemplateSpecializationKind() ==
6772 TSK_ImplicitInstantiation) {
6773 InstantiationVar->setTemplateSpecializationKind(
6774 TSK_ExplicitSpecialization);
6775 InstantiationVar->setLocation(Member->getLocation());
6778 cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
6779 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
6780 MarkUnusedFileScopedDecl(InstantiationVar);
6781 } else if (isa<CXXRecordDecl>(Member)) {
6782 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
6783 if (InstantiationClass->getTemplateSpecializationKind() ==
6784 TSK_ImplicitInstantiation) {
6785 InstantiationClass->setTemplateSpecializationKind(
6786 TSK_ExplicitSpecialization);
6787 InstantiationClass->setLocation(Member->getLocation());
6790 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
6791 cast<CXXRecordDecl>(InstantiatedFrom),
6792 TSK_ExplicitSpecialization);
6794 assert(isa<EnumDecl>(Member) && "Only member enums remain");
6795 EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
6796 if (InstantiationEnum->getTemplateSpecializationKind() ==
6797 TSK_ImplicitInstantiation) {
6798 InstantiationEnum->setTemplateSpecializationKind(
6799 TSK_ExplicitSpecialization);
6800 InstantiationEnum->setLocation(Member->getLocation());
6803 cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
6804 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
6807 // Save the caller the trouble of having to figure out which declaration
6808 // this specialization matches.
6810 Previous.addDecl(Instantiation);
6814 /// \brief Check the scope of an explicit instantiation.
6816 /// \returns true if a serious error occurs, false otherwise.
6817 static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
6818 SourceLocation InstLoc,
6819 bool WasQualifiedName) {
6820 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
6821 DeclContext *CurContext = S.CurContext->getRedeclContext();
6823 if (CurContext->isRecord()) {
6824 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
6829 // C++11 [temp.explicit]p3:
6830 // An explicit instantiation shall appear in an enclosing namespace of its
6831 // template. If the name declared in the explicit instantiation is an
6832 // unqualified name, the explicit instantiation shall appear in the
6833 // namespace where its template is declared or, if that namespace is inline
6834 // (7.3.1), any namespace from its enclosing namespace set.
6836 // This is DR275, which we do not retroactively apply to C++98/03.
6837 if (WasQualifiedName) {
6838 if (CurContext->Encloses(OrigContext))
6841 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
6845 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
6846 if (WasQualifiedName)
6848 S.getLangOpts().CPlusPlus11?
6849 diag::err_explicit_instantiation_out_of_scope :
6850 diag::warn_explicit_instantiation_out_of_scope_0x)
6854 S.getLangOpts().CPlusPlus11?
6855 diag::err_explicit_instantiation_unqualified_wrong_namespace :
6856 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
6860 S.getLangOpts().CPlusPlus11?
6861 diag::err_explicit_instantiation_must_be_global :
6862 diag::warn_explicit_instantiation_must_be_global_0x)
6864 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
6868 /// \brief Determine whether the given scope specifier has a template-id in it.
6869 static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
6873 // C++11 [temp.explicit]p3:
6874 // If the explicit instantiation is for a member function, a member class
6875 // or a static data member of a class template specialization, the name of
6876 // the class template specialization in the qualified-id for the member
6877 // name shall be a simple-template-id.
6879 // C++98 has the same restriction, just worded differently.
6880 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
6881 NNS; NNS = NNS->getPrefix())
6882 if (const Type *T = NNS->getAsType())
6883 if (isa<TemplateSpecializationType>(T))
6889 // Explicit instantiation of a class template specialization
6891 Sema::ActOnExplicitInstantiation(Scope *S,
6892 SourceLocation ExternLoc,
6893 SourceLocation TemplateLoc,
6895 SourceLocation KWLoc,
6896 const CXXScopeSpec &SS,
6897 TemplateTy TemplateD,
6898 SourceLocation TemplateNameLoc,
6899 SourceLocation LAngleLoc,
6900 ASTTemplateArgsPtr TemplateArgsIn,
6901 SourceLocation RAngleLoc,
6902 AttributeList *Attr) {
6903 // Find the class template we're specializing
6904 TemplateName Name = TemplateD.get();
6905 TemplateDecl *TD = Name.getAsTemplateDecl();
6906 // Check that the specialization uses the same tag kind as the
6907 // original template.
6908 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6909 assert(Kind != TTK_Enum &&
6910 "Invalid enum tag in class template explicit instantiation!");
6912 if (isa<TypeAliasTemplateDecl>(TD)) {
6913 Diag(KWLoc, diag::err_tag_reference_non_tag) << Kind;
6914 Diag(TD->getTemplatedDecl()->getLocation(),
6915 diag::note_previous_use);
6919 ClassTemplateDecl *ClassTemplate = cast<ClassTemplateDecl>(TD);
6921 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
6922 Kind, /*isDefinition*/false, KWLoc,
6923 *ClassTemplate->getIdentifier())) {
6924 Diag(KWLoc, diag::err_use_with_wrong_tag)
6926 << FixItHint::CreateReplacement(KWLoc,
6927 ClassTemplate->getTemplatedDecl()->getKindName());
6928 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
6929 diag::note_previous_use);
6930 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
6933 // C++0x [temp.explicit]p2:
6934 // There are two forms of explicit instantiation: an explicit instantiation
6935 // definition and an explicit instantiation declaration. An explicit
6936 // instantiation declaration begins with the extern keyword. [...]
6937 TemplateSpecializationKind TSK
6938 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
6939 : TSK_ExplicitInstantiationDeclaration;
6941 // Translate the parser's template argument list in our AST format.
6942 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
6943 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
6945 // Check that the template argument list is well-formed for this
6947 SmallVector<TemplateArgument, 4> Converted;
6948 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
6949 TemplateArgs, false, Converted))
6952 // Find the class template specialization declaration that
6953 // corresponds to these arguments.
6954 void *InsertPos = 0;
6955 ClassTemplateSpecializationDecl *PrevDecl
6956 = ClassTemplate->findSpecialization(Converted.data(),
6957 Converted.size(), InsertPos);
6959 TemplateSpecializationKind PrevDecl_TSK
6960 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
6962 // C++0x [temp.explicit]p2:
6963 // [...] An explicit instantiation shall appear in an enclosing
6964 // namespace of its template. [...]
6966 // This is C++ DR 275.
6967 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
6971 ClassTemplateSpecializationDecl *Specialization = 0;
6973 bool HasNoEffect = false;
6975 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
6976 PrevDecl, PrevDecl_TSK,
6977 PrevDecl->getPointOfInstantiation(),
6981 // Even though HasNoEffect == true means that this explicit instantiation
6982 // has no effect on semantics, we go on to put its syntax in the AST.
6984 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
6985 PrevDecl_TSK == TSK_Undeclared) {
6986 // Since the only prior class template specialization with these
6987 // arguments was referenced but not declared, reuse that
6988 // declaration node as our own, updating the source location
6989 // for the template name to reflect our new declaration.
6990 // (Other source locations will be updated later.)
6991 Specialization = PrevDecl;
6992 Specialization->setLocation(TemplateNameLoc);
6997 if (!Specialization) {
6998 // Create a new class template specialization declaration node for
6999 // this explicit specialization.
7001 = ClassTemplateSpecializationDecl::Create(Context, Kind,
7002 ClassTemplate->getDeclContext(),
7003 KWLoc, TemplateNameLoc,
7008 SetNestedNameSpecifier(Specialization, SS);
7010 if (!HasNoEffect && !PrevDecl) {
7011 // Insert the new specialization.
7012 ClassTemplate->AddSpecialization(Specialization, InsertPos);
7016 // Build the fully-sugared type for this explicit instantiation as
7017 // the user wrote in the explicit instantiation itself. This means
7018 // that we'll pretty-print the type retrieved from the
7019 // specialization's declaration the way that the user actually wrote
7020 // the explicit instantiation, rather than formatting the name based
7021 // on the "canonical" representation used to store the template
7022 // arguments in the specialization.
7023 TypeSourceInfo *WrittenTy
7024 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7026 Context.getTypeDeclType(Specialization));
7027 Specialization->setTypeAsWritten(WrittenTy);
7029 // Set source locations for keywords.
7030 Specialization->setExternLoc(ExternLoc);
7031 Specialization->setTemplateKeywordLoc(TemplateLoc);
7032 Specialization->setRBraceLoc(SourceLocation());
7035 ProcessDeclAttributeList(S, Specialization, Attr);
7037 // Add the explicit instantiation into its lexical context. However,
7038 // since explicit instantiations are never found by name lookup, we
7039 // just put it into the declaration context directly.
7040 Specialization->setLexicalDeclContext(CurContext);
7041 CurContext->addDecl(Specialization);
7043 // Syntax is now OK, so return if it has no other effect on semantics.
7045 // Set the template specialization kind.
7046 Specialization->setTemplateSpecializationKind(TSK);
7047 return Specialization;
7050 // C++ [temp.explicit]p3:
7051 // A definition of a class template or class member template
7052 // shall be in scope at the point of the explicit instantiation of
7053 // the class template or class member template.
7055 // This check comes when we actually try to perform the
7057 ClassTemplateSpecializationDecl *Def
7058 = cast_or_null<ClassTemplateSpecializationDecl>(
7059 Specialization->getDefinition());
7061 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
7062 else if (TSK == TSK_ExplicitInstantiationDefinition) {
7063 MarkVTableUsed(TemplateNameLoc, Specialization, true);
7064 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
7067 // Instantiate the members of this class template specialization.
7068 Def = cast_or_null<ClassTemplateSpecializationDecl>(
7069 Specialization->getDefinition());
7071 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
7073 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
7074 // TSK_ExplicitInstantiationDefinition
7075 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
7076 TSK == TSK_ExplicitInstantiationDefinition)
7077 Def->setTemplateSpecializationKind(TSK);
7079 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
7082 // Set the template specialization kind.
7083 Specialization->setTemplateSpecializationKind(TSK);
7084 return Specialization;
7087 // Explicit instantiation of a member class of a class template.
7089 Sema::ActOnExplicitInstantiation(Scope *S,
7090 SourceLocation ExternLoc,
7091 SourceLocation TemplateLoc,
7093 SourceLocation KWLoc,
7095 IdentifierInfo *Name,
7096 SourceLocation NameLoc,
7097 AttributeList *Attr) {
7100 bool IsDependent = false;
7101 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
7102 KWLoc, SS, Name, NameLoc, Attr, AS_none,
7103 /*ModulePrivateLoc=*/SourceLocation(),
7104 MultiTemplateParamsArg(), Owned, IsDependent,
7105 SourceLocation(), false, TypeResult());
7106 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
7111 TagDecl *Tag = cast<TagDecl>(TagD);
7112 assert(!Tag->isEnum() && "shouldn't see enumerations here");
7114 if (Tag->isInvalidDecl())
7117 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
7118 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
7120 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
7121 << Context.getTypeDeclType(Record);
7122 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
7126 // C++0x [temp.explicit]p2:
7127 // If the explicit instantiation is for a class or member class, the
7128 // elaborated-type-specifier in the declaration shall include a
7129 // simple-template-id.
7131 // C++98 has the same restriction, just worded differently.
7132 if (!ScopeSpecifierHasTemplateId(SS))
7133 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
7134 << Record << SS.getRange();
7136 // C++0x [temp.explicit]p2:
7137 // There are two forms of explicit instantiation: an explicit instantiation
7138 // definition and an explicit instantiation declaration. An explicit
7139 // instantiation declaration begins with the extern keyword. [...]
7140 TemplateSpecializationKind TSK
7141 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7142 : TSK_ExplicitInstantiationDeclaration;
7144 // C++0x [temp.explicit]p2:
7145 // [...] An explicit instantiation shall appear in an enclosing
7146 // namespace of its template. [...]
7148 // This is C++ DR 275.
7149 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
7151 // Verify that it is okay to explicitly instantiate here.
7152 CXXRecordDecl *PrevDecl
7153 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
7154 if (!PrevDecl && Record->getDefinition())
7157 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
7158 bool HasNoEffect = false;
7159 assert(MSInfo && "No member specialization information?");
7160 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
7162 MSInfo->getTemplateSpecializationKind(),
7163 MSInfo->getPointOfInstantiation(),
7170 CXXRecordDecl *RecordDef
7171 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
7173 // C++ [temp.explicit]p3:
7174 // A definition of a member class of a class template shall be in scope
7175 // at the point of an explicit instantiation of the member class.
7177 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
7179 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
7180 << 0 << Record->getDeclName() << Record->getDeclContext();
7181 Diag(Pattern->getLocation(), diag::note_forward_declaration)
7185 if (InstantiateClass(NameLoc, Record, Def,
7186 getTemplateInstantiationArgs(Record),
7190 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
7196 // Instantiate all of the members of the class.
7197 InstantiateClassMembers(NameLoc, RecordDef,
7198 getTemplateInstantiationArgs(Record), TSK);
7200 if (TSK == TSK_ExplicitInstantiationDefinition)
7201 MarkVTableUsed(NameLoc, RecordDef, true);
7203 // FIXME: We don't have any representation for explicit instantiations of
7204 // member classes. Such a representation is not needed for compilation, but it
7205 // should be available for clients that want to see all of the declarations in
7210 DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
7211 SourceLocation ExternLoc,
7212 SourceLocation TemplateLoc,
7214 // Explicit instantiations always require a name.
7215 // TODO: check if/when DNInfo should replace Name.
7216 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7217 DeclarationName Name = NameInfo.getName();
7219 if (!D.isInvalidType())
7220 Diag(D.getDeclSpec().getLocStart(),
7221 diag::err_explicit_instantiation_requires_name)
7222 << D.getDeclSpec().getSourceRange()
7223 << D.getSourceRange();
7228 // The scope passed in may not be a decl scope. Zip up the scope tree until
7229 // we find one that is.
7230 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7231 (S->getFlags() & Scope::TemplateParamScope) != 0)
7234 // Determine the type of the declaration.
7235 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
7236 QualType R = T->getType();
7241 // A storage-class-specifier shall not be specified in [...] an explicit
7242 // instantiation (14.7.2) directive.
7243 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
7244 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
7247 } else if (D.getDeclSpec().getStorageClassSpec()
7248 != DeclSpec::SCS_unspecified) {
7249 // Complain about then remove the storage class specifier.
7250 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
7251 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7253 D.getMutableDeclSpec().ClearStorageClassSpecs();
7256 // C++0x [temp.explicit]p1:
7257 // [...] An explicit instantiation of a function template shall not use the
7258 // inline or constexpr specifiers.
7259 // Presumably, this also applies to member functions of class templates as
7261 if (D.getDeclSpec().isInlineSpecified())
7262 Diag(D.getDeclSpec().getInlineSpecLoc(),
7263 getLangOpts().CPlusPlus11 ?
7264 diag::err_explicit_instantiation_inline :
7265 diag::warn_explicit_instantiation_inline_0x)
7266 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7267 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
7268 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
7269 // not already specified.
7270 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7271 diag::err_explicit_instantiation_constexpr);
7273 // C++0x [temp.explicit]p2:
7274 // There are two forms of explicit instantiation: an explicit instantiation
7275 // definition and an explicit instantiation declaration. An explicit
7276 // instantiation declaration begins with the extern keyword. [...]
7277 TemplateSpecializationKind TSK
7278 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7279 : TSK_ExplicitInstantiationDeclaration;
7281 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
7282 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
7284 if (!R->isFunctionType()) {
7285 // C++ [temp.explicit]p1:
7286 // A [...] static data member of a class template can be explicitly
7287 // instantiated from the member definition associated with its class
7289 // C++1y [temp.explicit]p1:
7290 // A [...] variable [...] template specialization can be explicitly
7291 // instantiated from its template.
7292 if (Previous.isAmbiguous())
7295 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
7296 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
7298 if (!PrevTemplate) {
7299 if (!Prev || !Prev->isStaticDataMember()) {
7300 // We expect to see a data data member here.
7301 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
7303 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7305 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
7309 if (!Prev->getInstantiatedFromStaticDataMember()) {
7310 // FIXME: Check for explicit specialization?
7311 Diag(D.getIdentifierLoc(),
7312 diag::err_explicit_instantiation_data_member_not_instantiated)
7314 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
7315 // FIXME: Can we provide a note showing where this was declared?
7319 // Explicitly instantiate a variable template.
7321 // C++1y [dcl.spec.auto]p6:
7322 // ... A program that uses auto or decltype(auto) in a context not
7323 // explicitly allowed in this section is ill-formed.
7325 // This includes auto-typed variable template instantiations.
7326 if (R->isUndeducedType()) {
7327 Diag(T->getTypeLoc().getLocStart(),
7328 diag::err_auto_not_allowed_var_inst);
7332 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7333 // C++1y [temp.explicit]p3:
7334 // If the explicit instantiation is for a variable, the unqualified-id
7335 // in the declaration shall be a template-id.
7336 Diag(D.getIdentifierLoc(),
7337 diag::err_explicit_instantiation_without_template_id)
7339 Diag(PrevTemplate->getLocation(),
7340 diag::note_explicit_instantiation_here);
7344 // Translate the parser's template argument list into our AST format.
7345 TemplateArgumentListInfo TemplateArgs;
7346 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7347 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7348 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
7349 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7350 TemplateId->NumArgs);
7351 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
7353 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
7354 D.getIdentifierLoc(), TemplateArgs);
7355 if (Res.isInvalid())
7358 // Ignore access control bits, we don't need them for redeclaration
7360 Prev = cast<VarDecl>(Res.get());
7363 // C++0x [temp.explicit]p2:
7364 // If the explicit instantiation is for a member function, a member class
7365 // or a static data member of a class template specialization, the name of
7366 // the class template specialization in the qualified-id for the member
7367 // name shall be a simple-template-id.
7369 // C++98 has the same restriction, just worded differently.
7371 // This does not apply to variable template specializations, where the
7372 // template-id is in the unqualified-id instead.
7373 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
7374 Diag(D.getIdentifierLoc(),
7375 diag::ext_explicit_instantiation_without_qualified_id)
7376 << Prev << D.getCXXScopeSpec().getRange();
7378 // Check the scope of this explicit instantiation.
7379 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
7381 // Verify that it is okay to explicitly instantiate here.
7382 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
7383 SourceLocation POI = Prev->getPointOfInstantiation();
7384 bool HasNoEffect = false;
7385 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
7386 PrevTSK, POI, HasNoEffect))
7390 // Instantiate static data member or variable template.
7392 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
7394 // Merge attributes.
7395 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
7396 ProcessDeclAttributeList(S, Prev, Attr);
7398 if (TSK == TSK_ExplicitInstantiationDefinition)
7399 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
7402 // Check the new variable specialization against the parsed input.
7403 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
7404 Diag(T->getTypeLoc().getLocStart(),
7405 diag::err_invalid_var_template_spec_type)
7406 << 0 << PrevTemplate << R << Prev->getType();
7407 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
7408 << 2 << PrevTemplate->getDeclName();
7412 // FIXME: Create an ExplicitInstantiation node?
7416 // If the declarator is a template-id, translate the parser's template
7417 // argument list into our AST format.
7418 bool HasExplicitTemplateArgs = false;
7419 TemplateArgumentListInfo TemplateArgs;
7420 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7421 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7422 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7423 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
7424 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7425 TemplateId->NumArgs);
7426 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
7427 HasExplicitTemplateArgs = true;
7430 // C++ [temp.explicit]p1:
7431 // A [...] function [...] can be explicitly instantiated from its template.
7432 // A member function [...] of a class template can be explicitly
7433 // instantiated from the member definition associated with its class
7435 UnresolvedSet<8> Matches;
7436 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
7437 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7439 NamedDecl *Prev = *P;
7440 if (!HasExplicitTemplateArgs) {
7441 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
7442 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType());
7443 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
7446 Matches.addDecl(Method, P.getAccess());
7447 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
7453 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
7457 TemplateDeductionInfo Info(FailedCandidates.getLocation());
7458 FunctionDecl *Specialization = 0;
7459 if (TemplateDeductionResult TDK
7460 = DeduceTemplateArguments(FunTmpl,
7461 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
7462 R, Specialization, Info)) {
7463 // Keep track of almost-matches.
7464 FailedCandidates.addCandidate()
7465 .set(FunTmpl->getTemplatedDecl(),
7466 MakeDeductionFailureInfo(Context, TDK, Info));
7471 Matches.addDecl(Specialization, P.getAccess());
7474 // Find the most specialized function template specialization.
7475 UnresolvedSetIterator Result = getMostSpecialized(
7476 Matches.begin(), Matches.end(), FailedCandidates,
7477 D.getIdentifierLoc(),
7478 PDiag(diag::err_explicit_instantiation_not_known) << Name,
7479 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
7480 PDiag(diag::note_explicit_instantiation_candidate));
7482 if (Result == Matches.end())
7485 // Ignore access control bits, we don't need them for redeclaration checking.
7486 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
7488 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
7489 Diag(D.getIdentifierLoc(),
7490 diag::err_explicit_instantiation_member_function_not_instantiated)
7492 << (Specialization->getTemplateSpecializationKind() ==
7493 TSK_ExplicitSpecialization);
7494 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
7498 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
7499 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
7500 PrevDecl = Specialization;
7503 bool HasNoEffect = false;
7504 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
7506 PrevDecl->getTemplateSpecializationKind(),
7507 PrevDecl->getPointOfInstantiation(),
7511 // FIXME: We may still want to build some representation of this
7512 // explicit specialization.
7517 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
7518 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
7520 ProcessDeclAttributeList(S, Specialization, Attr);
7522 if (TSK == TSK_ExplicitInstantiationDefinition)
7523 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
7525 // C++0x [temp.explicit]p2:
7526 // If the explicit instantiation is for a member function, a member class
7527 // or a static data member of a class template specialization, the name of
7528 // the class template specialization in the qualified-id for the member
7529 // name shall be a simple-template-id.
7531 // C++98 has the same restriction, just worded differently.
7532 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
7533 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
7534 D.getCXXScopeSpec().isSet() &&
7535 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
7536 Diag(D.getIdentifierLoc(),
7537 diag::ext_explicit_instantiation_without_qualified_id)
7538 << Specialization << D.getCXXScopeSpec().getRange();
7540 CheckExplicitInstantiationScope(*this,
7541 FunTmpl? (NamedDecl *)FunTmpl
7542 : Specialization->getInstantiatedFromMemberFunction(),
7543 D.getIdentifierLoc(),
7544 D.getCXXScopeSpec().isSet());
7546 // FIXME: Create some kind of ExplicitInstantiationDecl here.
7551 Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
7552 const CXXScopeSpec &SS, IdentifierInfo *Name,
7553 SourceLocation TagLoc, SourceLocation NameLoc) {
7554 // This has to hold, because SS is expected to be defined.
7555 assert(Name && "Expected a name in a dependent tag");
7557 NestedNameSpecifier *NNS
7558 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
7562 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7564 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
7565 Diag(NameLoc, diag::err_dependent_tag_decl)
7566 << (TUK == TUK_Definition) << Kind << SS.getRange();
7570 // Create the resulting type.
7571 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
7572 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
7574 // Create type-source location information for this type.
7576 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
7577 TL.setElaboratedKeywordLoc(TagLoc);
7578 TL.setQualifierLoc(SS.getWithLocInContext(Context));
7579 TL.setNameLoc(NameLoc);
7580 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
7584 Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
7585 const CXXScopeSpec &SS, const IdentifierInfo &II,
7586 SourceLocation IdLoc) {
7590 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
7592 getLangOpts().CPlusPlus11 ?
7593 diag::warn_cxx98_compat_typename_outside_of_template :
7594 diag::ext_typename_outside_of_template)
7595 << FixItHint::CreateRemoval(TypenameLoc);
7597 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
7598 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
7599 TypenameLoc, QualifierLoc, II, IdLoc);
7603 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
7604 if (isa<DependentNameType>(T)) {
7605 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
7606 TL.setElaboratedKeywordLoc(TypenameLoc);
7607 TL.setQualifierLoc(QualifierLoc);
7608 TL.setNameLoc(IdLoc);
7610 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
7611 TL.setElaboratedKeywordLoc(TypenameLoc);
7612 TL.setQualifierLoc(QualifierLoc);
7613 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
7616 return CreateParsedType(T, TSI);
7620 Sema::ActOnTypenameType(Scope *S,
7621 SourceLocation TypenameLoc,
7622 const CXXScopeSpec &SS,
7623 SourceLocation TemplateKWLoc,
7624 TemplateTy TemplateIn,
7625 SourceLocation TemplateNameLoc,
7626 SourceLocation LAngleLoc,
7627 ASTTemplateArgsPtr TemplateArgsIn,
7628 SourceLocation RAngleLoc) {
7629 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
7631 getLangOpts().CPlusPlus11 ?
7632 diag::warn_cxx98_compat_typename_outside_of_template :
7633 diag::ext_typename_outside_of_template)
7634 << FixItHint::CreateRemoval(TypenameLoc);
7636 // Translate the parser's template argument list in our AST format.
7637 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
7638 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
7640 TemplateName Template = TemplateIn.get();
7641 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
7642 // Construct a dependent template specialization type.
7643 assert(DTN && "dependent template has non-dependent name?");
7644 assert(DTN->getQualifier()
7645 == static_cast<NestedNameSpecifier*>(SS.getScopeRep()));
7646 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
7647 DTN->getQualifier(),
7648 DTN->getIdentifier(),
7651 // Create source-location information for this type.
7652 TypeLocBuilder Builder;
7653 DependentTemplateSpecializationTypeLoc SpecTL
7654 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
7655 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
7656 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
7657 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
7658 SpecTL.setTemplateNameLoc(TemplateNameLoc);
7659 SpecTL.setLAngleLoc(LAngleLoc);
7660 SpecTL.setRAngleLoc(RAngleLoc);
7661 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7662 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
7663 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
7666 QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
7670 // Provide source-location information for the template specialization type.
7671 TypeLocBuilder Builder;
7672 TemplateSpecializationTypeLoc SpecTL
7673 = Builder.push<TemplateSpecializationTypeLoc>(T);
7674 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
7675 SpecTL.setTemplateNameLoc(TemplateNameLoc);
7676 SpecTL.setLAngleLoc(LAngleLoc);
7677 SpecTL.setRAngleLoc(RAngleLoc);
7678 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7679 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
7681 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
7682 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
7683 TL.setElaboratedKeywordLoc(TypenameLoc);
7684 TL.setQualifierLoc(SS.getWithLocInContext(Context));
7686 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
7687 return CreateParsedType(T, TSI);
7691 /// Determine whether this failed name lookup should be treated as being
7692 /// disabled by a usage of std::enable_if.
7693 static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
7694 SourceRange &CondRange) {
7695 // We must be looking for a ::type...
7696 if (!II.isStr("type"))
7699 // ... within an explicitly-written template specialization...
7700 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
7702 TypeLoc EnableIfTy = NNS.getTypeLoc();
7703 TemplateSpecializationTypeLoc EnableIfTSTLoc =
7704 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
7705 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
7707 const TemplateSpecializationType *EnableIfTST =
7708 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
7710 // ... which names a complete class template declaration...
7711 const TemplateDecl *EnableIfDecl =
7712 EnableIfTST->getTemplateName().getAsTemplateDecl();
7713 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
7716 // ... called "enable_if".
7717 const IdentifierInfo *EnableIfII =
7718 EnableIfDecl->getDeclName().getAsIdentifierInfo();
7719 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
7722 // Assume the first template argument is the condition.
7723 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
7727 /// \brief Build the type that describes a C++ typename specifier,
7728 /// e.g., "typename T::type".
7730 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
7731 SourceLocation KeywordLoc,
7732 NestedNameSpecifierLoc QualifierLoc,
7733 const IdentifierInfo &II,
7734 SourceLocation IILoc) {
7736 SS.Adopt(QualifierLoc);
7738 DeclContext *Ctx = computeDeclContext(SS);
7740 // If the nested-name-specifier is dependent and couldn't be
7741 // resolved to a type, build a typename type.
7742 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
7743 return Context.getDependentNameType(Keyword,
7744 QualifierLoc.getNestedNameSpecifier(),
7748 // If the nested-name-specifier refers to the current instantiation,
7749 // the "typename" keyword itself is superfluous. In C++03, the
7750 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
7751 // allows such extraneous "typename" keywords, and we retroactively
7752 // apply this DR to C++03 code with only a warning. In any case we continue.
7754 if (RequireCompleteDeclContext(SS, Ctx))
7757 DeclarationName Name(&II);
7758 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
7759 LookupQualifiedName(Result, Ctx);
7760 unsigned DiagID = 0;
7761 Decl *Referenced = 0;
7762 switch (Result.getResultKind()) {
7763 case LookupResult::NotFound: {
7764 // If we're looking up 'type' within a template named 'enable_if', produce
7765 // a more specific diagnostic.
7766 SourceRange CondRange;
7767 if (isEnableIf(QualifierLoc, II, CondRange)) {
7768 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
7769 << Ctx << CondRange;
7773 DiagID = diag::err_typename_nested_not_found;
7777 case LookupResult::FoundUnresolvedValue: {
7778 // We found a using declaration that is a value. Most likely, the using
7779 // declaration itself is meant to have the 'typename' keyword.
7780 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
7782 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
7783 << Name << Ctx << FullRange;
7784 if (UnresolvedUsingValueDecl *Using
7785 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
7786 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
7787 Diag(Loc, diag::note_using_value_decl_missing_typename)
7788 << FixItHint::CreateInsertion(Loc, "typename ");
7791 // Fall through to create a dependent typename type, from which we can recover
7794 case LookupResult::NotFoundInCurrentInstantiation:
7795 // Okay, it's a member of an unknown instantiation.
7796 return Context.getDependentNameType(Keyword,
7797 QualifierLoc.getNestedNameSpecifier(),
7800 case LookupResult::Found:
7801 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
7802 // We found a type. Build an ElaboratedType, since the
7803 // typename-specifier was just sugar.
7804 return Context.getElaboratedType(ETK_Typename,
7805 QualifierLoc.getNestedNameSpecifier(),
7806 Context.getTypeDeclType(Type));
7809 DiagID = diag::err_typename_nested_not_type;
7810 Referenced = Result.getFoundDecl();
7813 case LookupResult::FoundOverloaded:
7814 DiagID = diag::err_typename_nested_not_type;
7815 Referenced = *Result.begin();
7818 case LookupResult::Ambiguous:
7822 // If we get here, it's because name lookup did not find a
7823 // type. Emit an appropriate diagnostic and return an error.
7824 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
7826 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
7828 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
7834 // See Sema::RebuildTypeInCurrentInstantiation
7835 class CurrentInstantiationRebuilder
7836 : public TreeTransform<CurrentInstantiationRebuilder> {
7838 DeclarationName Entity;
7841 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
7843 CurrentInstantiationRebuilder(Sema &SemaRef,
7845 DeclarationName Entity)
7846 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
7847 Loc(Loc), Entity(Entity) { }
7849 /// \brief Determine whether the given type \p T has already been
7852 /// For the purposes of type reconstruction, a type has already been
7853 /// transformed if it is NULL or if it is not dependent.
7854 bool AlreadyTransformed(QualType T) {
7855 return T.isNull() || !T->isDependentType();
7858 /// \brief Returns the location of the entity whose type is being
7860 SourceLocation getBaseLocation() { return Loc; }
7862 /// \brief Returns the name of the entity whose type is being rebuilt.
7863 DeclarationName getBaseEntity() { return Entity; }
7865 /// \brief Sets the "base" location and entity when that
7866 /// information is known based on another transformation.
7867 void setBase(SourceLocation Loc, DeclarationName Entity) {
7869 this->Entity = Entity;
7872 ExprResult TransformLambdaExpr(LambdaExpr *E) {
7873 // Lambdas never need to be transformed.
7879 /// \brief Rebuilds a type within the context of the current instantiation.
7881 /// The type \p T is part of the type of an out-of-line member definition of
7882 /// a class template (or class template partial specialization) that was parsed
7883 /// and constructed before we entered the scope of the class template (or
7884 /// partial specialization thereof). This routine will rebuild that type now
7885 /// that we have entered the declarator's scope, which may produce different
7886 /// canonical types, e.g.,
7889 /// template<typename T>
7891 /// typedef T* pointer;
7895 /// template<typename T>
7896 /// typename X<T>::pointer X<T>::data() { ... }
7899 /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
7900 /// since we do not know that we can look into X<T> when we parsed the type.
7901 /// This function will rebuild the type, performing the lookup of "pointer"
7902 /// in X<T> and returning an ElaboratedType whose canonical type is the same
7903 /// as the canonical type of T*, allowing the return types of the out-of-line
7904 /// definition and the declaration to match.
7905 TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
7907 DeclarationName Name) {
7908 if (!T || !T->getType()->isDependentType())
7911 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
7912 return Rebuilder.TransformType(T);
7915 ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
7916 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
7918 return Rebuilder.TransformExpr(E);
7921 bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
7925 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
7926 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
7928 NestedNameSpecifierLoc Rebuilt
7929 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
7937 /// \brief Rebuild the template parameters now that we know we're in a current
7939 bool Sema::RebuildTemplateParamsInCurrentInstantiation(
7940 TemplateParameterList *Params) {
7941 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
7942 Decl *Param = Params->getParam(I);
7944 // There is nothing to rebuild in a type parameter.
7945 if (isa<TemplateTypeParmDecl>(Param))
7948 // Rebuild the template parameter list of a template template parameter.
7949 if (TemplateTemplateParmDecl *TTP
7950 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
7951 if (RebuildTemplateParamsInCurrentInstantiation(
7952 TTP->getTemplateParameters()))
7958 // Rebuild the type of a non-type template parameter.
7959 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
7960 TypeSourceInfo *NewTSI
7961 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
7962 NTTP->getLocation(),
7963 NTTP->getDeclName());
7967 if (NewTSI != NTTP->getTypeSourceInfo()) {
7968 NTTP->setTypeSourceInfo(NewTSI);
7969 NTTP->setType(NewTSI->getType());
7976 /// \brief Produces a formatted string that describes the binding of
7977 /// template parameters to template arguments.
7979 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
7980 const TemplateArgumentList &Args) {
7981 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
7985 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
7986 const TemplateArgument *Args,
7988 SmallString<128> Str;
7989 llvm::raw_svector_ostream Out(Str);
7991 if (!Params || Params->size() == 0 || NumArgs == 0)
7992 return std::string();
7994 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8003 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
8004 Out << Id->getName();
8010 Args[I].print(getPrintingPolicy(), Out);
8017 void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
8018 CachedTokens &Toks) {
8022 LateParsedTemplate *LPT = new LateParsedTemplate;
8024 // Take tokens to avoid allocations
8025 LPT->Toks.swap(Toks);
8027 LateParsedTemplateMap[FD] = LPT;
8029 FD->setLateTemplateParsed(true);
8032 void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
8035 FD->setLateTemplateParsed(false);
8038 bool Sema::IsInsideALocalClassWithinATemplateFunction() {
8039 DeclContext *DC = CurContext;
8042 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
8043 const FunctionDecl *FD = RD->isLocalClass();
8044 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
8045 } else if (DC->isTranslationUnit() || DC->isNamespace())
8048 DC = DC->getParent();