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 "clang/Sema/SemaInternal.h"
13 #include "clang/Sema/Lookup.h"
14 #include "clang/Sema/Scope.h"
15 #include "clang/Sema/Template.h"
16 #include "clang/Sema/TemplateDeduction.h"
17 #include "TreeTransform.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/DeclFriend.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/RecursiveASTVisitor.h"
24 #include "clang/AST/TypeVisitor.h"
25 #include "clang/Sema/DeclSpec.h"
26 #include "clang/Sema/ParsedTemplate.h"
27 #include "clang/Basic/LangOptions.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "llvm/ADT/SmallBitVector.h"
30 #include "llvm/ADT/SmallString.h"
31 #include "llvm/ADT/StringExtras.h"
32 using namespace clang;
35 // Exported for use by Parser.
37 clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
39 if (!N) return SourceRange();
40 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
43 /// \brief Determine whether the declaration found is acceptable as the name
44 /// of a template and, if so, return that template declaration. Otherwise,
46 static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
48 bool AllowFunctionTemplates) {
49 NamedDecl *D = Orig->getUnderlyingDecl();
51 if (isa<TemplateDecl>(D)) {
52 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
58 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
59 // C++ [temp.local]p1:
60 // Like normal (non-template) classes, class templates have an
61 // injected-class-name (Clause 9). The injected-class-name
62 // can be used with or without a template-argument-list. When
63 // it is used without a template-argument-list, it is
64 // equivalent to the injected-class-name followed by the
65 // template-parameters of the class template enclosed in
66 // <>. When it is used with a template-argument-list, it
67 // refers to the specified class template specialization,
68 // which could be the current specialization or another
70 if (Record->isInjectedClassName()) {
71 Record = cast<CXXRecordDecl>(Record->getDeclContext());
72 if (Record->getDescribedClassTemplate())
73 return Record->getDescribedClassTemplate();
75 if (ClassTemplateSpecializationDecl *Spec
76 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
77 return Spec->getSpecializedTemplate();
86 void Sema::FilterAcceptableTemplateNames(LookupResult &R,
87 bool AllowFunctionTemplates) {
88 // The set of class templates we've already seen.
89 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
90 LookupResult::Filter filter = R.makeFilter();
91 while (filter.hasNext()) {
92 NamedDecl *Orig = filter.next();
93 NamedDecl *Repl = isAcceptableTemplateName(Context, Orig,
94 AllowFunctionTemplates);
97 else if (Repl != Orig) {
99 // C++ [temp.local]p3:
100 // A lookup that finds an injected-class-name (10.2) can result in an
101 // ambiguity in certain cases (for example, if it is found in more than
102 // one base class). If all of the injected-class-names that are found
103 // refer to specializations of the same class template, and if the name
104 // is used as a template-name, the reference refers to the class
105 // template itself and not a specialization thereof, and is not
107 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
108 if (!ClassTemplates.insert(ClassTmpl)) {
113 // FIXME: we promote access to public here as a workaround to
114 // the fact that LookupResult doesn't let us remember that we
115 // found this template through a particular injected class name,
116 // which means we end up doing nasty things to the invariants.
117 // Pretending that access is public is *much* safer.
118 filter.replace(Repl, AS_public);
124 bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
125 bool AllowFunctionTemplates) {
126 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
127 if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
133 TemplateNameKind Sema::isTemplateName(Scope *S,
135 bool hasTemplateKeyword,
137 ParsedType ObjectTypePtr,
138 bool EnteringContext,
139 TemplateTy &TemplateResult,
140 bool &MemberOfUnknownSpecialization) {
141 assert(getLangOpts().CPlusPlus && "No template names in C!");
143 DeclarationName TName;
144 MemberOfUnknownSpecialization = false;
146 switch (Name.getKind()) {
147 case UnqualifiedId::IK_Identifier:
148 TName = DeclarationName(Name.Identifier);
151 case UnqualifiedId::IK_OperatorFunctionId:
152 TName = Context.DeclarationNames.getCXXOperatorName(
153 Name.OperatorFunctionId.Operator);
156 case UnqualifiedId::IK_LiteralOperatorId:
157 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
161 return TNK_Non_template;
164 QualType ObjectType = ObjectTypePtr.get();
166 LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
167 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
168 MemberOfUnknownSpecialization);
169 if (R.empty()) return TNK_Non_template;
170 if (R.isAmbiguous()) {
171 // Suppress diagnostics; we'll redo this lookup later.
172 R.suppressDiagnostics();
174 // FIXME: we might have ambiguous templates, in which case we
175 // should at least parse them properly!
176 return TNK_Non_template;
179 TemplateName Template;
180 TemplateNameKind TemplateKind;
182 unsigned ResultCount = R.end() - R.begin();
183 if (ResultCount > 1) {
184 // We assume that we'll preserve the qualifier from a function
185 // template name in other ways.
186 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
187 TemplateKind = TNK_Function_template;
189 // We'll do this lookup again later.
190 R.suppressDiagnostics();
192 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
194 if (SS.isSet() && !SS.isInvalid()) {
195 NestedNameSpecifier *Qualifier
196 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
197 Template = Context.getQualifiedTemplateName(Qualifier,
198 hasTemplateKeyword, TD);
200 Template = TemplateName(TD);
203 if (isa<FunctionTemplateDecl>(TD)) {
204 TemplateKind = TNK_Function_template;
206 // We'll do this lookup again later.
207 R.suppressDiagnostics();
209 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
210 isa<TypeAliasTemplateDecl>(TD));
211 TemplateKind = TNK_Type_template;
215 TemplateResult = TemplateTy::make(Template);
219 bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
220 SourceLocation IILoc,
222 const CXXScopeSpec *SS,
223 TemplateTy &SuggestedTemplate,
224 TemplateNameKind &SuggestedKind) {
225 // We can't recover unless there's a dependent scope specifier preceding the
227 // FIXME: Typo correction?
228 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
229 computeDeclContext(*SS))
232 // The code is missing a 'template' keyword prior to the dependent template
234 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
235 Diag(IILoc, diag::err_template_kw_missing)
236 << Qualifier << II.getName()
237 << FixItHint::CreateInsertion(IILoc, "template ");
239 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
240 SuggestedKind = TNK_Dependent_template_name;
244 void Sema::LookupTemplateName(LookupResult &Found,
245 Scope *S, CXXScopeSpec &SS,
247 bool EnteringContext,
248 bool &MemberOfUnknownSpecialization) {
249 // Determine where to perform name lookup
250 MemberOfUnknownSpecialization = false;
251 DeclContext *LookupCtx = 0;
252 bool isDependent = false;
253 if (!ObjectType.isNull()) {
254 // This nested-name-specifier occurs in a member access expression, e.g.,
255 // x->B::f, and we are looking into the type of the object.
256 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
257 LookupCtx = computeDeclContext(ObjectType);
258 isDependent = ObjectType->isDependentType();
259 assert((isDependent || !ObjectType->isIncompleteType()) &&
260 "Caller should have completed object type");
262 // Template names cannot appear inside an Objective-C class or object type.
263 if (ObjectType->isObjCObjectOrInterfaceType()) {
267 } else if (SS.isSet()) {
268 // This nested-name-specifier occurs after another nested-name-specifier,
269 // so long into the context associated with the prior nested-name-specifier.
270 LookupCtx = computeDeclContext(SS, EnteringContext);
271 isDependent = isDependentScopeSpecifier(SS);
273 // The declaration context must be complete.
274 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
278 bool ObjectTypeSearchedInScope = false;
279 bool AllowFunctionTemplatesInLookup = true;
281 // Perform "qualified" name lookup into the declaration context we
282 // computed, which is either the type of the base of a member access
283 // expression or the declaration context associated with a prior
284 // nested-name-specifier.
285 LookupQualifiedName(Found, LookupCtx);
286 if (!ObjectType.isNull() && Found.empty()) {
287 // C++ [basic.lookup.classref]p1:
288 // In a class member access expression (5.2.5), if the . or -> token is
289 // immediately followed by an identifier followed by a <, the
290 // identifier must be looked up to determine whether the < is the
291 // beginning of a template argument list (14.2) or a less-than operator.
292 // The identifier is first looked up in the class of the object
293 // expression. If the identifier is not found, it is then looked up in
294 // the context of the entire postfix-expression and shall name a class
295 // or function template.
296 if (S) LookupName(Found, S);
297 ObjectTypeSearchedInScope = true;
298 AllowFunctionTemplatesInLookup = false;
300 } else if (isDependent && (!S || ObjectType.isNull())) {
301 // We cannot look into a dependent object type or nested nme
303 MemberOfUnknownSpecialization = true;
306 // Perform unqualified name lookup in the current scope.
307 LookupName(Found, S);
309 if (!ObjectType.isNull())
310 AllowFunctionTemplatesInLookup = false;
313 if (Found.empty() && !isDependent) {
314 // If we did not find any names, attempt to correct any typos.
315 DeclarationName Name = Found.getLookupName();
317 // Simple filter callback that, for keywords, only accepts the C++ *_cast
318 CorrectionCandidateCallback FilterCCC;
319 FilterCCC.WantTypeSpecifiers = false;
320 FilterCCC.WantExpressionKeywords = false;
321 FilterCCC.WantRemainingKeywords = false;
322 FilterCCC.WantCXXNamedCasts = true;
323 if (TypoCorrection Corrected = CorrectTypo(Found.getLookupNameInfo(),
324 Found.getLookupKind(), S, &SS,
325 FilterCCC, LookupCtx)) {
326 Found.setLookupName(Corrected.getCorrection());
327 if (Corrected.getCorrectionDecl())
328 Found.addDecl(Corrected.getCorrectionDecl());
329 FilterAcceptableTemplateNames(Found);
330 if (!Found.empty()) {
331 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
332 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
334 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
335 << Name << LookupCtx << CorrectedQuotedStr << SS.getRange()
336 << FixItHint::CreateReplacement(Found.getNameLoc(), CorrectedStr);
338 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
339 << Name << CorrectedQuotedStr
340 << FixItHint::CreateReplacement(Found.getNameLoc(), CorrectedStr);
341 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
342 Diag(Template->getLocation(), diag::note_previous_decl)
343 << CorrectedQuotedStr;
346 Found.setLookupName(Name);
350 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
353 MemberOfUnknownSpecialization = true;
357 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
358 // C++ [basic.lookup.classref]p1:
359 // [...] If the lookup in the class of the object expression finds a
360 // template, the name is also looked up in the context of the entire
361 // postfix-expression and [...]
363 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
365 LookupName(FoundOuter, S);
366 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
368 if (FoundOuter.empty()) {
369 // - if the name is not found, the name found in the class of the
370 // object expression is used, otherwise
371 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
372 FoundOuter.isAmbiguous()) {
373 // - if the name is found in the context of the entire
374 // postfix-expression and does not name a class template, the name
375 // found in the class of the object expression is used, otherwise
377 } else if (!Found.isSuppressingDiagnostics()) {
378 // - if the name found is a class template, it must refer to the same
379 // entity as the one found in the class of the object expression,
380 // otherwise the program is ill-formed.
381 if (!Found.isSingleResult() ||
382 Found.getFoundDecl()->getCanonicalDecl()
383 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
384 Diag(Found.getNameLoc(),
385 diag::ext_nested_name_member_ref_lookup_ambiguous)
386 << Found.getLookupName()
388 Diag(Found.getRepresentativeDecl()->getLocation(),
389 diag::note_ambig_member_ref_object_type)
391 Diag(FoundOuter.getFoundDecl()->getLocation(),
392 diag::note_ambig_member_ref_scope);
394 // Recover by taking the template that we found in the object
395 // expression's type.
401 /// ActOnDependentIdExpression - Handle a dependent id-expression that
402 /// was just parsed. This is only possible with an explicit scope
403 /// specifier naming a dependent type.
405 Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
406 SourceLocation TemplateKWLoc,
407 const DeclarationNameInfo &NameInfo,
408 bool isAddressOfOperand,
409 const TemplateArgumentListInfo *TemplateArgs) {
410 DeclContext *DC = getFunctionLevelDeclContext();
412 if (!isAddressOfOperand &&
413 isa<CXXMethodDecl>(DC) &&
414 cast<CXXMethodDecl>(DC)->isInstance()) {
415 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
417 // Since the 'this' expression is synthesized, we don't need to
418 // perform the double-lookup check.
419 NamedDecl *FirstQualifierInScope = 0;
421 return Owned(CXXDependentScopeMemberExpr::Create(Context,
422 /*This*/ 0, ThisType,
424 /*Op*/ SourceLocation(),
425 SS.getWithLocInContext(Context),
427 FirstQualifierInScope,
432 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
436 Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
437 SourceLocation TemplateKWLoc,
438 const DeclarationNameInfo &NameInfo,
439 const TemplateArgumentListInfo *TemplateArgs) {
440 return Owned(DependentScopeDeclRefExpr::Create(Context,
441 SS.getWithLocInContext(Context),
447 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
448 /// that the template parameter 'PrevDecl' is being shadowed by a new
449 /// declaration at location Loc. Returns true to indicate that this is
450 /// an error, and false otherwise.
451 void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
452 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
454 // Microsoft Visual C++ permits template parameters to be shadowed.
455 if (getLangOpts().MicrosoftExt)
458 // C++ [temp.local]p4:
459 // A template-parameter shall not be redeclared within its
460 // scope (including nested scopes).
461 Diag(Loc, diag::err_template_param_shadow)
462 << cast<NamedDecl>(PrevDecl)->getDeclName();
463 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
467 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
468 /// the parameter D to reference the templated declaration and return a pointer
469 /// to the template declaration. Otherwise, do nothing to D and return null.
470 TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
471 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
472 D = Temp->getTemplatedDecl();
478 ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
479 SourceLocation EllipsisLoc) const {
480 assert(Kind == Template &&
481 "Only template template arguments can be pack expansions here");
482 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
483 "Template template argument pack expansion without packs");
484 ParsedTemplateArgument Result(*this);
485 Result.EllipsisLoc = EllipsisLoc;
489 static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
490 const ParsedTemplateArgument &Arg) {
492 switch (Arg.getKind()) {
493 case ParsedTemplateArgument::Type: {
495 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
497 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
498 return TemplateArgumentLoc(TemplateArgument(T), DI);
501 case ParsedTemplateArgument::NonType: {
502 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
503 return TemplateArgumentLoc(TemplateArgument(E), E);
506 case ParsedTemplateArgument::Template: {
507 TemplateName Template = Arg.getAsTemplate().get();
508 TemplateArgument TArg;
509 if (Arg.getEllipsisLoc().isValid())
510 TArg = TemplateArgument(Template, llvm::Optional<unsigned int>());
513 return TemplateArgumentLoc(TArg,
514 Arg.getScopeSpec().getWithLocInContext(
517 Arg.getEllipsisLoc());
521 llvm_unreachable("Unhandled parsed template argument");
524 /// \brief Translates template arguments as provided by the parser
525 /// into template arguments used by semantic analysis.
526 void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
527 TemplateArgumentListInfo &TemplateArgs) {
528 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
529 TemplateArgs.addArgument(translateTemplateArgument(*this,
533 /// ActOnTypeParameter - Called when a C++ template type parameter
534 /// (e.g., "typename T") has been parsed. Typename specifies whether
535 /// the keyword "typename" was used to declare the type parameter
536 /// (otherwise, "class" was used), and KeyLoc is the location of the
537 /// "class" or "typename" keyword. ParamName is the name of the
538 /// parameter (NULL indicates an unnamed template parameter) and
539 /// ParamNameLoc is the location of the parameter name (if any).
540 /// If the type parameter has a default argument, it will be added
541 /// later via ActOnTypeParameterDefault.
542 Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
543 SourceLocation EllipsisLoc,
544 SourceLocation KeyLoc,
545 IdentifierInfo *ParamName,
546 SourceLocation ParamNameLoc,
547 unsigned Depth, unsigned Position,
548 SourceLocation EqualLoc,
549 ParsedType DefaultArg) {
550 assert(S->isTemplateParamScope() &&
551 "Template type parameter not in template parameter scope!");
552 bool Invalid = false;
555 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
558 if (PrevDecl && PrevDecl->isTemplateParameter()) {
559 DiagnoseTemplateParameterShadow(ParamNameLoc, PrevDecl);
564 SourceLocation Loc = ParamNameLoc;
568 TemplateTypeParmDecl *Param
569 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
570 KeyLoc, Loc, Depth, Position, ParamName,
572 Param->setAccess(AS_public);
574 Param->setInvalidDecl();
577 // Add the template parameter into the current scope.
579 IdResolver.AddDecl(Param);
582 // C++0x [temp.param]p9:
583 // A default template-argument may be specified for any kind of
584 // template-parameter that is not a template parameter pack.
585 if (DefaultArg && Ellipsis) {
586 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
587 DefaultArg = ParsedType();
590 // Handle the default argument, if provided.
592 TypeSourceInfo *DefaultTInfo;
593 GetTypeFromParser(DefaultArg, &DefaultTInfo);
595 assert(DefaultTInfo && "expected source information for type");
597 // Check for unexpanded parameter packs.
598 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
599 UPPC_DefaultArgument))
602 // Check the template argument itself.
603 if (CheckTemplateArgument(Param, DefaultTInfo)) {
604 Param->setInvalidDecl();
608 Param->setDefaultArgument(DefaultTInfo, false);
614 /// \brief Check that the type of a non-type template parameter is
617 /// \returns the (possibly-promoted) parameter type if valid;
618 /// otherwise, produces a diagnostic and returns a NULL type.
620 Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
621 // We don't allow variably-modified types as the type of non-type template
623 if (T->isVariablyModifiedType()) {
624 Diag(Loc, diag::err_variably_modified_nontype_template_param)
629 // C++ [temp.param]p4:
631 // A non-type template-parameter shall have one of the following
632 // (optionally cv-qualified) types:
634 // -- integral or enumeration type,
635 if (T->isIntegralOrEnumerationType() ||
636 // -- pointer to object or pointer to function,
637 T->isPointerType() ||
638 // -- reference to object or reference to function,
639 T->isReferenceType() ||
640 // -- pointer to member,
641 T->isMemberPointerType() ||
642 // -- std::nullptr_t.
643 T->isNullPtrType() ||
644 // If T is a dependent type, we can't do the check now, so we
645 // assume that it is well-formed.
646 T->isDependentType()) {
647 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
648 // are ignored when determining its type.
649 return T.getUnqualifiedType();
652 // C++ [temp.param]p8:
654 // A non-type template-parameter of type "array of T" or
655 // "function returning T" is adjusted to be of type "pointer to
656 // T" or "pointer to function returning T", respectively.
657 else if (T->isArrayType())
658 // FIXME: Keep the type prior to promotion?
659 return Context.getArrayDecayedType(T);
660 else if (T->isFunctionType())
661 // FIXME: Keep the type prior to promotion?
662 return Context.getPointerType(T);
664 Diag(Loc, diag::err_template_nontype_parm_bad_type)
670 Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
673 SourceLocation EqualLoc,
675 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
676 QualType T = TInfo->getType();
678 assert(S->isTemplateParamScope() &&
679 "Non-type template parameter not in template parameter scope!");
680 bool Invalid = false;
682 IdentifierInfo *ParamName = D.getIdentifier();
684 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
687 if (PrevDecl && PrevDecl->isTemplateParameter()) {
688 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
693 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
695 T = Context.IntTy; // Recover with an 'int' type.
699 bool IsParameterPack = D.hasEllipsis();
700 NonTypeTemplateParmDecl *Param
701 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
703 D.getIdentifierLoc(),
704 Depth, Position, ParamName, T,
705 IsParameterPack, TInfo);
706 Param->setAccess(AS_public);
709 Param->setInvalidDecl();
711 if (D.getIdentifier()) {
712 // Add the template parameter into the current scope.
714 IdResolver.AddDecl(Param);
717 // C++0x [temp.param]p9:
718 // A default template-argument may be specified for any kind of
719 // template-parameter that is not a template parameter pack.
720 if (Default && IsParameterPack) {
721 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
725 // Check the well-formedness of the default template argument, if provided.
727 // Check for unexpanded parameter packs.
728 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
731 TemplateArgument Converted;
732 ExprResult DefaultRes = CheckTemplateArgument(Param, Param->getType(), Default, Converted);
733 if (DefaultRes.isInvalid()) {
734 Param->setInvalidDecl();
737 Default = DefaultRes.take();
739 Param->setDefaultArgument(Default, false);
745 /// ActOnTemplateTemplateParameter - Called when a C++ template template
746 /// parameter (e.g. T in template <template <typename> class T> class array)
747 /// has been parsed. S is the current scope.
748 Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
749 SourceLocation TmpLoc,
750 TemplateParameterList *Params,
751 SourceLocation EllipsisLoc,
752 IdentifierInfo *Name,
753 SourceLocation NameLoc,
756 SourceLocation EqualLoc,
757 ParsedTemplateArgument Default) {
758 assert(S->isTemplateParamScope() &&
759 "Template template parameter not in template parameter scope!");
761 // Construct the parameter object.
762 bool IsParameterPack = EllipsisLoc.isValid();
763 TemplateTemplateParmDecl *Param =
764 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
765 NameLoc.isInvalid()? TmpLoc : NameLoc,
766 Depth, Position, IsParameterPack,
768 Param->setAccess(AS_public);
770 // If the template template parameter has a name, then link the identifier
771 // into the scope and lookup mechanisms.
774 IdResolver.AddDecl(Param);
777 if (Params->size() == 0) {
778 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
779 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
780 Param->setInvalidDecl();
783 // C++0x [temp.param]p9:
784 // A default template-argument may be specified for any kind of
785 // template-parameter that is not a template parameter pack.
786 if (IsParameterPack && !Default.isInvalid()) {
787 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
788 Default = ParsedTemplateArgument();
791 if (!Default.isInvalid()) {
792 // Check only that we have a template template argument. We don't want to
793 // try to check well-formedness now, because our template template parameter
794 // might have dependent types in its template parameters, which we wouldn't
795 // be able to match now.
797 // If none of the template template parameter's template arguments mention
798 // other template parameters, we could actually perform more checking here.
799 // However, it isn't worth doing.
800 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
801 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
802 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
803 << DefaultArg.getSourceRange();
807 // Check for unexpanded parameter packs.
808 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
809 DefaultArg.getArgument().getAsTemplate(),
810 UPPC_DefaultArgument))
813 Param->setDefaultArgument(DefaultArg, false);
819 /// ActOnTemplateParameterList - Builds a TemplateParameterList that
820 /// contains the template parameters in Params/NumParams.
821 TemplateParameterList *
822 Sema::ActOnTemplateParameterList(unsigned Depth,
823 SourceLocation ExportLoc,
824 SourceLocation TemplateLoc,
825 SourceLocation LAngleLoc,
826 Decl **Params, unsigned NumParams,
827 SourceLocation RAngleLoc) {
828 if (ExportLoc.isValid())
829 Diag(ExportLoc, diag::warn_template_export_unsupported);
831 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
832 (NamedDecl**)Params, NumParams,
836 static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
838 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
842 Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
843 SourceLocation KWLoc, CXXScopeSpec &SS,
844 IdentifierInfo *Name, SourceLocation NameLoc,
846 TemplateParameterList *TemplateParams,
847 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
848 unsigned NumOuterTemplateParamLists,
849 TemplateParameterList** OuterTemplateParamLists) {
850 assert(TemplateParams && TemplateParams->size() > 0 &&
851 "No template parameters");
852 assert(TUK != TUK_Reference && "Can only declare or define class templates");
853 bool Invalid = false;
855 // Check that we can declare a template here.
856 if (CheckTemplateDeclScope(S, TemplateParams))
859 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
860 assert(Kind != TTK_Enum && "can't build template of enumerated type");
862 // There is no such thing as an unnamed class template.
864 Diag(KWLoc, diag::err_template_unnamed_class);
868 // Find any previous declaration with this name.
869 DeclContext *SemanticContext;
870 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
872 if (SS.isNotEmpty() && !SS.isInvalid()) {
873 SemanticContext = computeDeclContext(SS, true);
874 if (!SemanticContext) {
875 // FIXME: Horrible, horrible hack! We can't currently represent this
876 // in the AST, and historically we have just ignored such friend
877 // class templates, so don't complain here.
878 if (TUK != TUK_Friend)
879 Diag(NameLoc, diag::err_template_qualified_declarator_no_match)
880 << SS.getScopeRep() << SS.getRange();
884 if (RequireCompleteDeclContext(SS, SemanticContext))
887 // If we're adding a template to a dependent context, we may need to
888 // rebuilding some of the types used within the template parameter list,
889 // now that we know what the current instantiation is.
890 if (SemanticContext->isDependentContext()) {
891 ContextRAII SavedContext(*this, SemanticContext);
892 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
894 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
895 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
897 LookupQualifiedName(Previous, SemanticContext);
899 SemanticContext = CurContext;
900 LookupName(Previous, S);
903 if (Previous.isAmbiguous())
906 NamedDecl *PrevDecl = 0;
907 if (Previous.begin() != Previous.end())
908 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
910 // If there is a previous declaration with the same name, check
911 // whether this is a valid redeclaration.
912 ClassTemplateDecl *PrevClassTemplate
913 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
915 // We may have found the injected-class-name of a class template,
916 // class template partial specialization, or class template specialization.
917 // In these cases, grab the template that is being defined or specialized.
918 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
919 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
920 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
922 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
923 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
925 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
926 ->getSpecializedTemplate();
930 if (TUK == TUK_Friend) {
931 // C++ [namespace.memdef]p3:
932 // [...] When looking for a prior declaration of a class or a function
933 // declared as a friend, and when the name of the friend class or
934 // function is neither a qualified name nor a template-id, scopes outside
935 // the innermost enclosing namespace scope are not considered.
937 DeclContext *OutermostContext = CurContext;
938 while (!OutermostContext->isFileContext())
939 OutermostContext = OutermostContext->getLookupParent();
942 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
943 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
944 SemanticContext = PrevDecl->getDeclContext();
946 // Declarations in outer scopes don't matter. However, the outermost
947 // context we computed is the semantic context for our new
949 PrevDecl = PrevClassTemplate = 0;
950 SemanticContext = OutermostContext;
954 if (CurContext->isDependentContext()) {
955 // If this is a dependent context, we don't want to link the friend
956 // class template to the template in scope, because that would perform
957 // checking of the template parameter lists that can't be performed
958 // until the outer context is instantiated.
959 PrevDecl = PrevClassTemplate = 0;
961 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
962 PrevDecl = PrevClassTemplate = 0;
964 if (PrevClassTemplate) {
965 // Ensure that the template parameter lists are compatible.
966 if (!TemplateParameterListsAreEqual(TemplateParams,
967 PrevClassTemplate->getTemplateParameters(),
972 // C++ [temp.class]p4:
973 // In a redeclaration, partial specialization, explicit
974 // specialization or explicit instantiation of a class template,
975 // the class-key shall agree in kind with the original class
976 // template declaration (7.1.5.3).
977 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
978 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
979 TUK == TUK_Definition, KWLoc, *Name)) {
980 Diag(KWLoc, diag::err_use_with_wrong_tag)
982 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
983 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
984 Kind = PrevRecordDecl->getTagKind();
987 // Check for redefinition of this class template.
988 if (TUK == TUK_Definition) {
989 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
990 Diag(NameLoc, diag::err_redefinition) << Name;
991 Diag(Def->getLocation(), diag::note_previous_definition);
992 // FIXME: Would it make sense to try to "forget" the previous
993 // definition, as part of error recovery?
997 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
998 // Maybe we will complain about the shadowed template parameter.
999 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1000 // Just pretend that we didn't see the previous declaration.
1002 } else if (PrevDecl) {
1004 // A class template shall not have the same name as any other
1005 // template, class, function, object, enumeration, enumerator,
1006 // namespace, or type in the same scope (3.3), except as specified
1008 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1009 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1013 // Check the template parameter list of this declaration, possibly
1014 // merging in the template parameter list from the previous class
1015 // template declaration.
1016 if (CheckTemplateParameterList(TemplateParams,
1017 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
1018 (SS.isSet() && SemanticContext &&
1019 SemanticContext->isRecord() &&
1020 SemanticContext->isDependentContext())
1021 ? TPC_ClassTemplateMember
1022 : TPC_ClassTemplate))
1026 // If the name of the template was qualified, we must be defining the
1027 // template out-of-line.
1028 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
1029 !(TUK == TUK_Friend && CurContext->isDependentContext())) {
1030 Diag(NameLoc, diag::err_member_def_does_not_match)
1031 << Name << SemanticContext << SS.getRange();
1036 CXXRecordDecl *NewClass =
1037 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
1039 PrevClassTemplate->getTemplatedDecl() : 0,
1040 /*DelayTypeCreation=*/true);
1041 SetNestedNameSpecifier(NewClass, SS);
1042 if (NumOuterTemplateParamLists > 0)
1043 NewClass->setTemplateParameterListsInfo(Context,
1044 NumOuterTemplateParamLists,
1045 OuterTemplateParamLists);
1047 // Add alignment attributes if necessary; these attributes are checked when
1048 // the ASTContext lays out the structure.
1049 AddAlignmentAttributesForRecord(NewClass);
1050 AddMsStructLayoutForRecord(NewClass);
1052 ClassTemplateDecl *NewTemplate
1053 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1054 DeclarationName(Name), TemplateParams,
1055 NewClass, PrevClassTemplate);
1056 NewClass->setDescribedClassTemplate(NewTemplate);
1058 if (ModulePrivateLoc.isValid())
1059 NewTemplate->setModulePrivate();
1061 // Build the type for the class template declaration now.
1062 QualType T = NewTemplate->getInjectedClassNameSpecialization();
1063 T = Context.getInjectedClassNameType(NewClass, T);
1064 assert(T->isDependentType() && "Class template type is not dependent?");
1067 // If we are providing an explicit specialization of a member that is a
1068 // class template, make a note of that.
1069 if (PrevClassTemplate &&
1070 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1071 PrevClassTemplate->setMemberSpecialization();
1073 // Set the access specifier.
1074 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
1075 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
1077 // Set the lexical context of these templates
1078 NewClass->setLexicalDeclContext(CurContext);
1079 NewTemplate->setLexicalDeclContext(CurContext);
1081 if (TUK == TUK_Definition)
1082 NewClass->startDefinition();
1085 ProcessDeclAttributeList(S, NewClass, Attr);
1087 if (TUK != TUK_Friend)
1088 PushOnScopeChains(NewTemplate, S);
1090 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
1091 NewTemplate->setAccess(PrevClassTemplate->getAccess());
1092 NewClass->setAccess(PrevClassTemplate->getAccess());
1095 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
1096 PrevClassTemplate != NULL);
1098 // Friend templates are visible in fairly strange ways.
1099 if (!CurContext->isDependentContext()) {
1100 DeclContext *DC = SemanticContext->getRedeclContext();
1101 DC->makeDeclVisibleInContext(NewTemplate);
1102 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1103 PushOnScopeChains(NewTemplate, EnclosingScope,
1104 /* AddToContext = */ false);
1107 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
1108 NewClass->getLocation(),
1110 /*FIXME:*/NewClass->getLocation());
1111 Friend->setAccess(AS_public);
1112 CurContext->addDecl(Friend);
1116 NewTemplate->setInvalidDecl();
1117 NewClass->setInvalidDecl();
1122 /// \brief Diagnose the presence of a default template argument on a
1123 /// template parameter, which is ill-formed in certain contexts.
1125 /// \returns true if the default template argument should be dropped.
1126 static bool DiagnoseDefaultTemplateArgument(Sema &S,
1127 Sema::TemplateParamListContext TPC,
1128 SourceLocation ParamLoc,
1129 SourceRange DefArgRange) {
1131 case Sema::TPC_ClassTemplate:
1132 case Sema::TPC_TypeAliasTemplate:
1135 case Sema::TPC_FunctionTemplate:
1136 case Sema::TPC_FriendFunctionTemplateDefinition:
1137 // C++ [temp.param]p9:
1138 // A default template-argument shall not be specified in a
1139 // function template declaration or a function template
1141 // If a friend function template declaration specifies a default
1142 // template-argument, that declaration shall be a definition and shall be
1143 // the only declaration of the function template in the translation unit.
1144 // (C++98/03 doesn't have this wording; see DR226).
1145 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus0x ?
1146 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1147 : diag::ext_template_parameter_default_in_function_template)
1151 case Sema::TPC_ClassTemplateMember:
1152 // C++0x [temp.param]p9:
1153 // A default template-argument shall not be specified in the
1154 // template-parameter-lists of the definition of a member of a
1155 // class template that appears outside of the member's class.
1156 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1160 case Sema::TPC_FriendFunctionTemplate:
1161 // C++ [temp.param]p9:
1162 // A default template-argument shall not be specified in a
1163 // friend template declaration.
1164 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1168 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1169 // for friend function templates if there is only a single
1170 // declaration (and it is a definition). Strange!
1173 llvm_unreachable("Invalid TemplateParamListContext!");
1176 /// \brief Check for unexpanded parameter packs within the template parameters
1177 /// of a template template parameter, recursively.
1178 static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1179 TemplateTemplateParmDecl *TTP) {
1180 TemplateParameterList *Params = TTP->getTemplateParameters();
1181 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1182 NamedDecl *P = Params->getParam(I);
1183 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
1184 if (S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
1185 NTTP->getTypeSourceInfo(),
1186 Sema::UPPC_NonTypeTemplateParameterType))
1192 if (TemplateTemplateParmDecl *InnerTTP
1193 = dyn_cast<TemplateTemplateParmDecl>(P))
1194 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1201 /// \brief Checks the validity of a template parameter list, possibly
1202 /// considering the template parameter list from a previous
1205 /// If an "old" template parameter list is provided, it must be
1206 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
1207 /// template parameter list.
1209 /// \param NewParams Template parameter list for a new template
1210 /// declaration. This template parameter list will be updated with any
1211 /// default arguments that are carried through from the previous
1212 /// template parameter list.
1214 /// \param OldParams If provided, template parameter list from a
1215 /// previous declaration of the same template. Default template
1216 /// arguments will be merged from the old template parameter list to
1217 /// the new template parameter list.
1219 /// \param TPC Describes the context in which we are checking the given
1220 /// template parameter list.
1222 /// \returns true if an error occurred, false otherwise.
1223 bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
1224 TemplateParameterList *OldParams,
1225 TemplateParamListContext TPC) {
1226 bool Invalid = false;
1228 // C++ [temp.param]p10:
1229 // The set of default template-arguments available for use with a
1230 // template declaration or definition is obtained by merging the
1231 // default arguments from the definition (if in scope) and all
1232 // declarations in scope in the same way default function
1233 // arguments are (8.3.6).
1234 bool SawDefaultArgument = false;
1235 SourceLocation PreviousDefaultArgLoc;
1237 // Dummy initialization to avoid warnings.
1238 TemplateParameterList::iterator OldParam = NewParams->end();
1240 OldParam = OldParams->begin();
1242 bool RemoveDefaultArguments = false;
1243 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1244 NewParamEnd = NewParams->end();
1245 NewParam != NewParamEnd; ++NewParam) {
1246 // Variables used to diagnose redundant default arguments
1247 bool RedundantDefaultArg = false;
1248 SourceLocation OldDefaultLoc;
1249 SourceLocation NewDefaultLoc;
1251 // Variable used to diagnose missing default arguments
1252 bool MissingDefaultArg = false;
1254 // Variable used to diagnose non-final parameter packs
1255 bool SawParameterPack = false;
1257 if (TemplateTypeParmDecl *NewTypeParm
1258 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
1259 // Check the presence of a default argument here.
1260 if (NewTypeParm->hasDefaultArgument() &&
1261 DiagnoseDefaultTemplateArgument(*this, TPC,
1262 NewTypeParm->getLocation(),
1263 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1265 NewTypeParm->removeDefaultArgument();
1267 // Merge default arguments for template type parameters.
1268 TemplateTypeParmDecl *OldTypeParm
1269 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
1271 if (NewTypeParm->isParameterPack()) {
1272 assert(!NewTypeParm->hasDefaultArgument() &&
1273 "Parameter packs can't have a default argument!");
1274 SawParameterPack = true;
1275 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
1276 NewTypeParm->hasDefaultArgument()) {
1277 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1278 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1279 SawDefaultArgument = true;
1280 RedundantDefaultArg = true;
1281 PreviousDefaultArgLoc = NewDefaultLoc;
1282 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1283 // Merge the default argument from the old declaration to the
1285 SawDefaultArgument = true;
1286 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
1288 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1289 } else if (NewTypeParm->hasDefaultArgument()) {
1290 SawDefaultArgument = true;
1291 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1292 } else if (SawDefaultArgument)
1293 MissingDefaultArg = true;
1294 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
1295 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
1296 // Check for unexpanded parameter packs.
1297 if (DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
1298 NewNonTypeParm->getTypeSourceInfo(),
1299 UPPC_NonTypeTemplateParameterType)) {
1304 // Check the presence of a default argument here.
1305 if (NewNonTypeParm->hasDefaultArgument() &&
1306 DiagnoseDefaultTemplateArgument(*this, TPC,
1307 NewNonTypeParm->getLocation(),
1308 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1309 NewNonTypeParm->removeDefaultArgument();
1312 // Merge default arguments for non-type template parameters
1313 NonTypeTemplateParmDecl *OldNonTypeParm
1314 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
1315 if (NewNonTypeParm->isParameterPack()) {
1316 assert(!NewNonTypeParm->hasDefaultArgument() &&
1317 "Parameter packs can't have a default argument!");
1318 SawParameterPack = true;
1319 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
1320 NewNonTypeParm->hasDefaultArgument()) {
1321 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1322 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1323 SawDefaultArgument = true;
1324 RedundantDefaultArg = true;
1325 PreviousDefaultArgLoc = NewDefaultLoc;
1326 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1327 // Merge the default argument from the old declaration to the
1329 SawDefaultArgument = true;
1330 // FIXME: We need to create a new kind of "default argument"
1331 // expression that points to a previous non-type template
1333 NewNonTypeParm->setDefaultArgument(
1334 OldNonTypeParm->getDefaultArgument(),
1335 /*Inherited=*/ true);
1336 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1337 } else if (NewNonTypeParm->hasDefaultArgument()) {
1338 SawDefaultArgument = true;
1339 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1340 } else if (SawDefaultArgument)
1341 MissingDefaultArg = true;
1343 TemplateTemplateParmDecl *NewTemplateParm
1344 = cast<TemplateTemplateParmDecl>(*NewParam);
1346 // Check for unexpanded parameter packs, recursively.
1347 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
1352 // Check the presence of a default argument here.
1353 if (NewTemplateParm->hasDefaultArgument() &&
1354 DiagnoseDefaultTemplateArgument(*this, TPC,
1355 NewTemplateParm->getLocation(),
1356 NewTemplateParm->getDefaultArgument().getSourceRange()))
1357 NewTemplateParm->removeDefaultArgument();
1359 // Merge default arguments for template template parameters
1360 TemplateTemplateParmDecl *OldTemplateParm
1361 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
1362 if (NewTemplateParm->isParameterPack()) {
1363 assert(!NewTemplateParm->hasDefaultArgument() &&
1364 "Parameter packs can't have a default argument!");
1365 SawParameterPack = true;
1366 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
1367 NewTemplateParm->hasDefaultArgument()) {
1368 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1369 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
1370 SawDefaultArgument = true;
1371 RedundantDefaultArg = true;
1372 PreviousDefaultArgLoc = NewDefaultLoc;
1373 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1374 // Merge the default argument from the old declaration to the
1376 SawDefaultArgument = true;
1377 // FIXME: We need to create a new kind of "default argument" expression
1378 // that points to a previous template template parameter.
1379 NewTemplateParm->setDefaultArgument(
1380 OldTemplateParm->getDefaultArgument(),
1381 /*Inherited=*/ true);
1382 PreviousDefaultArgLoc
1383 = OldTemplateParm->getDefaultArgument().getLocation();
1384 } else if (NewTemplateParm->hasDefaultArgument()) {
1385 SawDefaultArgument = true;
1386 PreviousDefaultArgLoc
1387 = NewTemplateParm->getDefaultArgument().getLocation();
1388 } else if (SawDefaultArgument)
1389 MissingDefaultArg = true;
1392 // C++0x [temp.param]p11:
1393 // If a template parameter of a primary class template or alias template
1394 // is a template parameter pack, it shall be the last template parameter.
1395 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
1396 (TPC == TPC_ClassTemplate || TPC == TPC_TypeAliasTemplate)) {
1397 Diag((*NewParam)->getLocation(),
1398 diag::err_template_param_pack_must_be_last_template_parameter);
1402 if (RedundantDefaultArg) {
1403 // C++ [temp.param]p12:
1404 // A template-parameter shall not be given default arguments
1405 // by two different declarations in the same scope.
1406 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1407 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1409 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
1410 // C++ [temp.param]p11:
1411 // If a template-parameter of a class template has a default
1412 // template-argument, each subsequent template-parameter shall either
1413 // have a default template-argument supplied or be a template parameter
1415 Diag((*NewParam)->getLocation(),
1416 diag::err_template_param_default_arg_missing);
1417 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1419 RemoveDefaultArguments = true;
1422 // If we have an old template parameter list that we're merging
1423 // in, move on to the next parameter.
1428 // We were missing some default arguments at the end of the list, so remove
1429 // all of the default arguments.
1430 if (RemoveDefaultArguments) {
1431 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1432 NewParamEnd = NewParams->end();
1433 NewParam != NewParamEnd; ++NewParam) {
1434 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1435 TTP->removeDefaultArgument();
1436 else if (NonTypeTemplateParmDecl *NTTP
1437 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1438 NTTP->removeDefaultArgument();
1440 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1449 /// A class which looks for a use of a certain level of template
1451 struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1452 typedef RecursiveASTVisitor<DependencyChecker> super;
1457 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1458 NamedDecl *ND = Params->getParam(0);
1459 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1460 Depth = PD->getDepth();
1461 } else if (NonTypeTemplateParmDecl *PD =
1462 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1463 Depth = PD->getDepth();
1465 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1469 bool Matches(unsigned ParmDepth) {
1470 if (ParmDepth >= Depth) {
1477 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1478 return !Matches(T->getDepth());
1481 bool TraverseTemplateName(TemplateName N) {
1482 if (TemplateTemplateParmDecl *PD =
1483 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
1484 if (Matches(PD->getDepth())) return false;
1485 return super::TraverseTemplateName(N);
1488 bool VisitDeclRefExpr(DeclRefExpr *E) {
1489 if (NonTypeTemplateParmDecl *PD =
1490 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl())) {
1491 if (PD->getDepth() == Depth) {
1496 return super::VisitDeclRefExpr(E);
1499 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1500 return TraverseType(T->getInjectedSpecializationType());
1505 /// Determines whether a given type depends on the given parameter
1508 DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
1509 DependencyChecker Checker(Params);
1510 Checker.TraverseType(T);
1511 return Checker.Match;
1514 // Find the source range corresponding to the named type in the given
1515 // nested-name-specifier, if any.
1516 static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
1518 const CXXScopeSpec &SS) {
1519 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
1520 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1521 if (const Type *CurType = NNS->getAsType()) {
1522 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1523 return NNSLoc.getTypeLoc().getSourceRange();
1527 NNSLoc = NNSLoc.getPrefix();
1530 return SourceRange();
1533 /// \brief Match the given template parameter lists to the given scope
1534 /// specifier, returning the template parameter list that applies to the
1537 /// \param DeclStartLoc the start of the declaration that has a scope
1538 /// specifier or a template parameter list.
1540 /// \param DeclLoc The location of the declaration itself.
1542 /// \param SS the scope specifier that will be matched to the given template
1543 /// parameter lists. This scope specifier precedes a qualified name that is
1546 /// \param ParamLists the template parameter lists, from the outermost to the
1547 /// innermost template parameter lists.
1549 /// \param NumParamLists the number of template parameter lists in ParamLists.
1551 /// \param IsFriend Whether to apply the slightly different rules for
1552 /// matching template parameters to scope specifiers in friend
1555 /// \param IsExplicitSpecialization will be set true if the entity being
1556 /// declared is an explicit specialization, false otherwise.
1558 /// \returns the template parameter list, if any, that corresponds to the
1559 /// name that is preceded by the scope specifier @p SS. This template
1560 /// parameter list may have template parameters (if we're declaring a
1561 /// template) or may have no template parameters (if we're declaring a
1562 /// template specialization), or may be NULL (if what we're declaring isn't
1563 /// itself a template).
1564 TemplateParameterList *
1565 Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1566 SourceLocation DeclLoc,
1567 const CXXScopeSpec &SS,
1568 TemplateParameterList **ParamLists,
1569 unsigned NumParamLists,
1571 bool &IsExplicitSpecialization,
1573 IsExplicitSpecialization = false;
1576 // The sequence of nested types to which we will match up the template
1577 // parameter lists. We first build this list by starting with the type named
1578 // by the nested-name-specifier and walking out until we run out of types.
1579 SmallVector<QualType, 4> NestedTypes;
1581 if (SS.getScopeRep()) {
1582 if (CXXRecordDecl *Record
1583 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1584 T = Context.getTypeDeclType(Record);
1586 T = QualType(SS.getScopeRep()->getAsType(), 0);
1589 // If we found an explicit specialization that prevents us from needing
1590 // 'template<>' headers, this will be set to the location of that
1591 // explicit specialization.
1592 SourceLocation ExplicitSpecLoc;
1594 while (!T.isNull()) {
1595 NestedTypes.push_back(T);
1597 // Retrieve the parent of a record type.
1598 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1599 // If this type is an explicit specialization, we're done.
1600 if (ClassTemplateSpecializationDecl *Spec
1601 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1602 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
1603 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1604 ExplicitSpecLoc = Spec->getLocation();
1607 } else if (Record->getTemplateSpecializationKind()
1608 == TSK_ExplicitSpecialization) {
1609 ExplicitSpecLoc = Record->getLocation();
1613 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1614 T = Context.getTypeDeclType(Parent);
1620 if (const TemplateSpecializationType *TST
1621 = T->getAs<TemplateSpecializationType>()) {
1622 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1623 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1624 T = Context.getTypeDeclType(Parent);
1631 // Look one step prior in a dependent template specialization type.
1632 if (const DependentTemplateSpecializationType *DependentTST
1633 = T->getAs<DependentTemplateSpecializationType>()) {
1634 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1635 T = QualType(NNS->getAsType(), 0);
1641 // Look one step prior in a dependent name type.
1642 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1643 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1644 T = QualType(NNS->getAsType(), 0);
1650 // Retrieve the parent of an enumeration type.
1651 if (const EnumType *EnumT = T->getAs<EnumType>()) {
1652 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1654 EnumDecl *Enum = EnumT->getDecl();
1656 // Get to the parent type.
1657 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1658 T = Context.getTypeDeclType(Parent);
1666 // Reverse the nested types list, since we want to traverse from the outermost
1667 // to the innermost while checking template-parameter-lists.
1668 std::reverse(NestedTypes.begin(), NestedTypes.end());
1670 // C++0x [temp.expl.spec]p17:
1671 // A member or a member template may be nested within many
1672 // enclosing class templates. In an explicit specialization for
1673 // such a member, the member declaration shall be preceded by a
1674 // template<> for each enclosing class template that is
1675 // explicitly specialized.
1676 bool SawNonEmptyTemplateParameterList = false;
1677 unsigned ParamIdx = 0;
1678 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
1680 T = NestedTypes[TypeIdx];
1682 // Whether we expect a 'template<>' header.
1683 bool NeedEmptyTemplateHeader = false;
1685 // Whether we expect a template header with parameters.
1686 bool NeedNonemptyTemplateHeader = false;
1688 // For a dependent type, the set of template parameters that we
1690 TemplateParameterList *ExpectedTemplateParams = 0;
1692 // C++0x [temp.expl.spec]p15:
1693 // A member or a member template may be nested within many enclosing
1694 // class templates. In an explicit specialization for such a member, the
1695 // member declaration shall be preceded by a template<> for each
1696 // enclosing class template that is explicitly specialized.
1697 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1698 if (ClassTemplatePartialSpecializationDecl *Partial
1699 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1700 ExpectedTemplateParams = Partial->getTemplateParameters();
1701 NeedNonemptyTemplateHeader = true;
1702 } else if (Record->isDependentType()) {
1703 if (Record->getDescribedClassTemplate()) {
1704 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1705 ->getTemplateParameters();
1706 NeedNonemptyTemplateHeader = true;
1708 } else if (ClassTemplateSpecializationDecl *Spec
1709 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1710 // C++0x [temp.expl.spec]p4:
1711 // Members of an explicitly specialized class template are defined
1712 // in the same manner as members of normal classes, and not using
1713 // the template<> syntax.
1714 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
1715 NeedEmptyTemplateHeader = true;
1718 } else if (Record->getTemplateSpecializationKind()) {
1719 if (Record->getTemplateSpecializationKind()
1720 != TSK_ExplicitSpecialization &&
1721 TypeIdx == NumTypes - 1)
1722 IsExplicitSpecialization = true;
1726 } else if (const TemplateSpecializationType *TST
1727 = T->getAs<TemplateSpecializationType>()) {
1728 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1729 ExpectedTemplateParams = Template->getTemplateParameters();
1730 NeedNonemptyTemplateHeader = true;
1732 } else if (T->getAs<DependentTemplateSpecializationType>()) {
1733 // FIXME: We actually could/should check the template arguments here
1734 // against the corresponding template parameter list.
1735 NeedNonemptyTemplateHeader = false;
1738 // C++ [temp.expl.spec]p16:
1739 // In an explicit specialization declaration for a member of a class
1740 // template or a member template that ap- pears in namespace scope, the
1741 // member template and some of its enclosing class templates may remain
1742 // unspecialized, except that the declaration shall not explicitly
1743 // specialize a class member template if its en- closing class templates
1744 // are not explicitly specialized as well.
1745 if (ParamIdx < NumParamLists) {
1746 if (ParamLists[ParamIdx]->size() == 0) {
1747 if (SawNonEmptyTemplateParameterList) {
1748 Diag(DeclLoc, diag::err_specialize_member_of_template)
1749 << ParamLists[ParamIdx]->getSourceRange();
1751 IsExplicitSpecialization = false;
1755 SawNonEmptyTemplateParameterList = true;
1758 if (NeedEmptyTemplateHeader) {
1759 // If we're on the last of the types, and we need a 'template<>' header
1760 // here, then it's an explicit specialization.
1761 if (TypeIdx == NumTypes - 1)
1762 IsExplicitSpecialization = true;
1764 if (ParamIdx < NumParamLists) {
1765 if (ParamLists[ParamIdx]->size() > 0) {
1766 // The header has template parameters when it shouldn't. Complain.
1767 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1768 diag::err_template_param_list_matches_nontemplate)
1770 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
1771 ParamLists[ParamIdx]->getRAngleLoc())
1772 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1777 // Consume this template header.
1783 // We don't have a template header, but we should.
1784 SourceLocation ExpectedTemplateLoc;
1785 if (NumParamLists > 0)
1786 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
1788 ExpectedTemplateLoc = DeclStartLoc;
1790 Diag(DeclLoc, diag::err_template_spec_needs_header)
1791 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS)
1792 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
1798 if (NeedNonemptyTemplateHeader) {
1799 // In friend declarations we can have template-ids which don't
1800 // depend on the corresponding template parameter lists. But
1801 // assume that empty parameter lists are supposed to match this
1803 if (IsFriend && T->isDependentType()) {
1804 if (ParamIdx < NumParamLists &&
1805 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
1806 ExpectedTemplateParams = 0;
1811 if (ParamIdx < NumParamLists) {
1812 // Check the template parameter list, if we can.
1813 if (ExpectedTemplateParams &&
1814 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
1815 ExpectedTemplateParams,
1816 true, TPL_TemplateMatch))
1820 CheckTemplateParameterList(ParamLists[ParamIdx], 0,
1821 TPC_ClassTemplateMember))
1828 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
1830 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1836 // If there were at least as many template-ids as there were template
1837 // parameter lists, then there are no template parameter lists remaining for
1838 // the declaration itself.
1839 if (ParamIdx >= NumParamLists)
1842 // If there were too many template parameter lists, complain about that now.
1843 if (ParamIdx < NumParamLists - 1) {
1844 bool HasAnyExplicitSpecHeader = false;
1845 bool AllExplicitSpecHeaders = true;
1846 for (unsigned I = ParamIdx; I != NumParamLists - 1; ++I) {
1847 if (ParamLists[I]->size() == 0)
1848 HasAnyExplicitSpecHeader = true;
1850 AllExplicitSpecHeaders = false;
1853 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1854 AllExplicitSpecHeaders? diag::warn_template_spec_extra_headers
1855 : diag::err_template_spec_extra_headers)
1856 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1857 ParamLists[NumParamLists - 2]->getRAngleLoc());
1859 // If there was a specialization somewhere, such that 'template<>' is
1860 // not required, and there were any 'template<>' headers, note where the
1861 // specialization occurred.
1862 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
1863 Diag(ExplicitSpecLoc,
1864 diag::note_explicit_template_spec_does_not_need_header)
1865 << NestedTypes.back();
1867 // We have a template parameter list with no corresponding scope, which
1868 // means that the resulting template declaration can't be instantiated
1869 // properly (we'll end up with dependent nodes when we shouldn't).
1870 if (!AllExplicitSpecHeaders)
1874 // C++ [temp.expl.spec]p16:
1875 // In an explicit specialization declaration for a member of a class
1876 // template or a member template that ap- pears in namespace scope, the
1877 // member template and some of its enclosing class templates may remain
1878 // unspecialized, except that the declaration shall not explicitly
1879 // specialize a class member template if its en- closing class templates
1880 // are not explicitly specialized as well.
1881 if (ParamLists[NumParamLists - 1]->size() == 0 &&
1882 SawNonEmptyTemplateParameterList) {
1883 Diag(DeclLoc, diag::err_specialize_member_of_template)
1884 << ParamLists[ParamIdx]->getSourceRange();
1886 IsExplicitSpecialization = false;
1890 // Return the last template parameter list, which corresponds to the
1891 // entity being declared.
1892 return ParamLists[NumParamLists - 1];
1895 void Sema::NoteAllFoundTemplates(TemplateName Name) {
1896 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
1897 Diag(Template->getLocation(), diag::note_template_declared_here)
1898 << (isa<FunctionTemplateDecl>(Template)? 0
1899 : isa<ClassTemplateDecl>(Template)? 1
1900 : isa<TypeAliasTemplateDecl>(Template)? 2
1902 << Template->getDeclName();
1906 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
1907 for (OverloadedTemplateStorage::iterator I = OST->begin(),
1910 Diag((*I)->getLocation(), diag::note_template_declared_here)
1911 << 0 << (*I)->getDeclName();
1917 QualType Sema::CheckTemplateIdType(TemplateName Name,
1918 SourceLocation TemplateLoc,
1919 TemplateArgumentListInfo &TemplateArgs) {
1920 DependentTemplateName *DTN
1921 = Name.getUnderlying().getAsDependentTemplateName();
1922 if (DTN && DTN->isIdentifier())
1923 // When building a template-id where the template-name is dependent,
1924 // assume the template is a type template. Either our assumption is
1925 // correct, or the code is ill-formed and will be diagnosed when the
1926 // dependent name is substituted.
1927 return Context.getDependentTemplateSpecializationType(ETK_None,
1928 DTN->getQualifier(),
1929 DTN->getIdentifier(),
1932 TemplateDecl *Template = Name.getAsTemplateDecl();
1933 if (!Template || isa<FunctionTemplateDecl>(Template)) {
1934 // We might have a substituted template template parameter pack. If so,
1935 // build a template specialization type for it.
1936 if (Name.getAsSubstTemplateTemplateParmPack())
1937 return Context.getTemplateSpecializationType(Name, TemplateArgs);
1939 Diag(TemplateLoc, diag::err_template_id_not_a_type)
1941 NoteAllFoundTemplates(Name);
1945 // Check that the template argument list is well-formed for this
1947 SmallVector<TemplateArgument, 4> Converted;
1948 bool ExpansionIntoFixedList = false;
1949 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
1950 false, Converted, &ExpansionIntoFixedList))
1955 bool InstantiationDependent = false;
1956 TypeAliasTemplateDecl *AliasTemplate = 0;
1957 if (!ExpansionIntoFixedList &&
1958 (AliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Template))) {
1959 // Find the canonical type for this type alias template specialization.
1960 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
1961 if (Pattern->isInvalidDecl())
1964 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
1965 Converted.data(), Converted.size());
1967 // Only substitute for the innermost template argument list.
1968 MultiLevelTemplateArgumentList TemplateArgLists;
1969 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
1970 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
1971 for (unsigned I = 0; I < Depth; ++I)
1972 TemplateArgLists.addOuterTemplateArguments(0, 0);
1974 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
1975 CanonType = SubstType(Pattern->getUnderlyingType(),
1976 TemplateArgLists, AliasTemplate->getLocation(),
1977 AliasTemplate->getDeclName());
1978 if (CanonType.isNull())
1980 } else if (Name.isDependent() ||
1981 TemplateSpecializationType::anyDependentTemplateArguments(
1982 TemplateArgs, InstantiationDependent)) {
1983 // This class template specialization is a dependent
1984 // type. Therefore, its canonical type is another class template
1985 // specialization type that contains all of the converted
1986 // arguments in canonical form. This ensures that, e.g., A<T> and
1987 // A<T, T> have identical types when A is declared as:
1989 // template<typename T, typename U = T> struct A;
1990 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
1991 CanonType = Context.getTemplateSpecializationType(CanonName,
1995 // FIXME: CanonType is not actually the canonical type, and unfortunately
1996 // it is a TemplateSpecializationType that we will never use again.
1997 // In the future, we need to teach getTemplateSpecializationType to only
1998 // build the canonical type and return that to us.
1999 CanonType = Context.getCanonicalType(CanonType);
2001 // This might work out to be a current instantiation, in which
2002 // case the canonical type needs to be the InjectedClassNameType.
2004 // TODO: in theory this could be a simple hashtable lookup; most
2005 // changes to CurContext don't change the set of current
2007 if (isa<ClassTemplateDecl>(Template)) {
2008 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2009 // If we get out to a namespace, we're done.
2010 if (Ctx->isFileContext()) break;
2012 // If this isn't a record, keep looking.
2013 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2014 if (!Record) continue;
2016 // Look for one of the two cases with InjectedClassNameTypes
2017 // and check whether it's the same template.
2018 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2019 !Record->getDescribedClassTemplate())
2022 // Fetch the injected class name type and check whether its
2023 // injected type is equal to the type we just built.
2024 QualType ICNT = Context.getTypeDeclType(Record);
2025 QualType Injected = cast<InjectedClassNameType>(ICNT)
2026 ->getInjectedSpecializationType();
2028 if (CanonType != Injected->getCanonicalTypeInternal())
2031 // If so, the canonical type of this TST is the injected
2032 // class name type of the record we just found.
2033 assert(ICNT.isCanonical());
2038 } else if (ClassTemplateDecl *ClassTemplate
2039 = dyn_cast<ClassTemplateDecl>(Template)) {
2040 // Find the class template specialization declaration that
2041 // corresponds to these arguments.
2042 void *InsertPos = 0;
2043 ClassTemplateSpecializationDecl *Decl
2044 = ClassTemplate->findSpecialization(Converted.data(), Converted.size(),
2047 // This is the first time we have referenced this class template
2048 // specialization. Create the canonical declaration and add it to
2049 // the set of specializations.
2050 Decl = ClassTemplateSpecializationDecl::Create(Context,
2051 ClassTemplate->getTemplatedDecl()->getTagKind(),
2052 ClassTemplate->getDeclContext(),
2053 ClassTemplate->getTemplatedDecl()->getLocStart(),
2054 ClassTemplate->getLocation(),
2057 Converted.size(), 0);
2058 ClassTemplate->AddSpecialization(Decl, InsertPos);
2059 Decl->setLexicalDeclContext(CurContext);
2062 CanonType = Context.getTypeDeclType(Decl);
2063 assert(isa<RecordType>(CanonType) &&
2064 "type of non-dependent specialization is not a RecordType");
2067 // Build the fully-sugared type for this class template
2068 // specialization, which refers back to the class template
2069 // specialization we created or found.
2070 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
2074 Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
2075 TemplateTy TemplateD, SourceLocation TemplateLoc,
2076 SourceLocation LAngleLoc,
2077 ASTTemplateArgsPtr TemplateArgsIn,
2078 SourceLocation RAngleLoc,
2079 bool IsCtorOrDtorName) {
2083 TemplateName Template = TemplateD.getAsVal<TemplateName>();
2085 // Translate the parser's template argument list in our AST format.
2086 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2087 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2089 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2091 = Context.getDependentTemplateSpecializationType(ETK_None,
2092 DTN->getQualifier(),
2093 DTN->getIdentifier(),
2095 // Build type-source information.
2097 DependentTemplateSpecializationTypeLoc SpecTL
2098 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2099 SpecTL.setElaboratedKeywordLoc(SourceLocation());
2100 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
2101 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2102 SpecTL.setTemplateNameLoc(TemplateLoc);
2103 SpecTL.setLAngleLoc(LAngleLoc);
2104 SpecTL.setRAngleLoc(RAngleLoc);
2105 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2106 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2107 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2110 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2111 TemplateArgsIn.release();
2113 if (Result.isNull())
2116 // Build type-source information.
2118 TemplateSpecializationTypeLoc SpecTL
2119 = TLB.push<TemplateSpecializationTypeLoc>(Result);
2120 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2121 SpecTL.setTemplateNameLoc(TemplateLoc);
2122 SpecTL.setLAngleLoc(LAngleLoc);
2123 SpecTL.setRAngleLoc(RAngleLoc);
2124 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2125 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
2127 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2128 // constructor or destructor name (in such a case, the scope specifier
2129 // will be attached to the enclosing Decl or Expr node).
2130 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
2131 // Create an elaborated-type-specifier containing the nested-name-specifier.
2132 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2133 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
2134 ElabTL.setElaboratedKeywordLoc(SourceLocation());
2135 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2138 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
2141 TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
2142 TypeSpecifierType TagSpec,
2143 SourceLocation TagLoc,
2145 SourceLocation TemplateKWLoc,
2146 TemplateTy TemplateD,
2147 SourceLocation TemplateLoc,
2148 SourceLocation LAngleLoc,
2149 ASTTemplateArgsPtr TemplateArgsIn,
2150 SourceLocation RAngleLoc) {
2151 TemplateName Template = TemplateD.getAsVal<TemplateName>();
2153 // Translate the parser's template argument list in our AST format.
2154 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2155 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2157 // Determine the tag kind
2158 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
2159 ElaboratedTypeKeyword Keyword
2160 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
2162 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2163 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
2164 DTN->getQualifier(),
2165 DTN->getIdentifier(),
2168 // Build type-source information.
2170 DependentTemplateSpecializationTypeLoc SpecTL
2171 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2172 SpecTL.setElaboratedKeywordLoc(TagLoc);
2173 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
2174 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2175 SpecTL.setTemplateNameLoc(TemplateLoc);
2176 SpecTL.setLAngleLoc(LAngleLoc);
2177 SpecTL.setRAngleLoc(RAngleLoc);
2178 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2179 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2180 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2183 if (TypeAliasTemplateDecl *TAT =
2184 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2185 // C++0x [dcl.type.elab]p2:
2186 // If the identifier resolves to a typedef-name or the simple-template-id
2187 // resolves to an alias template specialization, the
2188 // elaborated-type-specifier is ill-formed.
2189 Diag(TemplateLoc, diag::err_tag_reference_non_tag) << 4;
2190 Diag(TAT->getLocation(), diag::note_declared_at);
2193 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2194 if (Result.isNull())
2195 return TypeResult(true);
2197 // Check the tag kind
2198 if (const RecordType *RT = Result->getAs<RecordType>()) {
2199 RecordDecl *D = RT->getDecl();
2201 IdentifierInfo *Id = D->getIdentifier();
2202 assert(Id && "templated class must have an identifier");
2204 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
2206 Diag(TagLoc, diag::err_use_with_wrong_tag)
2208 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
2209 Diag(D->getLocation(), diag::note_previous_use);
2213 // Provide source-location information for the template specialization.
2215 TemplateSpecializationTypeLoc SpecTL
2216 = TLB.push<TemplateSpecializationTypeLoc>(Result);
2217 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2218 SpecTL.setTemplateNameLoc(TemplateLoc);
2219 SpecTL.setLAngleLoc(LAngleLoc);
2220 SpecTL.setRAngleLoc(RAngleLoc);
2221 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2222 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
2224 // Construct an elaborated type containing the nested-name-specifier (if any)
2226 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2227 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
2228 ElabTL.setElaboratedKeywordLoc(TagLoc);
2229 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2230 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
2233 ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
2234 SourceLocation TemplateKWLoc,
2237 const TemplateArgumentListInfo *TemplateArgs) {
2238 // FIXME: Can we do any checking at this point? I guess we could check the
2239 // template arguments that we have against the template name, if the template
2240 // name refers to a single template. That's not a terribly common case,
2242 // foo<int> could identify a single function unambiguously
2243 // This approach does NOT work, since f<int>(1);
2244 // gets resolved prior to resorting to overload resolution
2245 // i.e., template<class T> void f(double);
2246 // vs template<class T, class U> void f(U);
2248 // These should be filtered out by our callers.
2249 assert(!R.empty() && "empty lookup results when building templateid");
2250 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
2252 // We don't want lookup warnings at this point.
2253 R.suppressDiagnostics();
2255 UnresolvedLookupExpr *ULE
2256 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2257 SS.getWithLocInContext(Context),
2259 R.getLookupNameInfo(),
2260 RequiresADL, TemplateArgs,
2261 R.begin(), R.end());
2266 // We actually only call this from template instantiation.
2268 Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
2269 SourceLocation TemplateKWLoc,
2270 const DeclarationNameInfo &NameInfo,
2271 const TemplateArgumentListInfo *TemplateArgs) {
2272 assert(TemplateArgs || TemplateKWLoc.isValid());
2274 if (!(DC = computeDeclContext(SS, false)) ||
2275 DC->isDependentContext() ||
2276 RequireCompleteDeclContext(SS, DC))
2277 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
2279 bool MemberOfUnknownSpecialization;
2280 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2281 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
2282 MemberOfUnknownSpecialization);
2284 if (R.isAmbiguous())
2288 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
2289 << NameInfo.getName() << SS.getRange();
2293 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
2294 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
2295 << (NestedNameSpecifier*) SS.getScopeRep()
2296 << NameInfo.getName() << SS.getRange();
2297 Diag(Temp->getLocation(), diag::note_referenced_class_template);
2301 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
2304 /// \brief Form a dependent template name.
2306 /// This action forms a dependent template name given the template
2307 /// name and its (presumably dependent) scope specifier. For
2308 /// example, given "MetaFun::template apply", the scope specifier \p
2309 /// SS will be "MetaFun::", \p TemplateKWLoc contains the location
2310 /// of the "template" keyword, and "apply" is the \p Name.
2311 TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
2313 SourceLocation TemplateKWLoc,
2314 UnqualifiedId &Name,
2315 ParsedType ObjectType,
2316 bool EnteringContext,
2317 TemplateTy &Result) {
2318 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
2320 getLangOpts().CPlusPlus0x ?
2321 diag::warn_cxx98_compat_template_outside_of_template :
2322 diag::ext_template_outside_of_template)
2323 << FixItHint::CreateRemoval(TemplateKWLoc);
2325 DeclContext *LookupCtx = 0;
2327 LookupCtx = computeDeclContext(SS, EnteringContext);
2328 if (!LookupCtx && ObjectType)
2329 LookupCtx = computeDeclContext(ObjectType.get());
2331 // C++0x [temp.names]p5:
2332 // If a name prefixed by the keyword template is not the name of
2333 // a template, the program is ill-formed. [Note: the keyword
2334 // template may not be applied to non-template members of class
2335 // templates. -end note ] [ Note: as is the case with the
2336 // typename prefix, the template prefix is allowed in cases
2337 // where it is not strictly necessary; i.e., when the
2338 // nested-name-specifier or the expression on the left of the ->
2339 // or . is not dependent on a template-parameter, or the use
2340 // does not appear in the scope of a template. -end note]
2342 // Note: C++03 was more strict here, because it banned the use of
2343 // the "template" keyword prior to a template-name that was not a
2344 // dependent name. C++ DR468 relaxed this requirement (the
2345 // "template" keyword is now permitted). We follow the C++0x
2346 // rules, even in C++03 mode with a warning, retroactively applying the DR.
2347 bool MemberOfUnknownSpecialization;
2348 TemplateNameKind TNK = isTemplateName(0, SS, TemplateKWLoc.isValid(), Name,
2349 ObjectType, EnteringContext, Result,
2350 MemberOfUnknownSpecialization);
2351 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
2352 isa<CXXRecordDecl>(LookupCtx) &&
2353 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
2354 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
2355 // This is a dependent template. Handle it below.
2356 } else if (TNK == TNK_Non_template) {
2357 Diag(Name.getLocStart(),
2358 diag::err_template_kw_refers_to_non_template)
2359 << GetNameFromUnqualifiedId(Name).getName()
2360 << Name.getSourceRange()
2362 return TNK_Non_template;
2364 // We found something; return it.
2369 NestedNameSpecifier *Qualifier
2370 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2372 switch (Name.getKind()) {
2373 case UnqualifiedId::IK_Identifier:
2374 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
2376 return TNK_Dependent_template_name;
2378 case UnqualifiedId::IK_OperatorFunctionId:
2379 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
2380 Name.OperatorFunctionId.Operator));
2381 return TNK_Dependent_template_name;
2383 case UnqualifiedId::IK_LiteralOperatorId:
2385 "We don't support these; Parse shouldn't have allowed propagation");
2391 Diag(Name.getLocStart(),
2392 diag::err_template_kw_refers_to_non_template)
2393 << GetNameFromUnqualifiedId(Name).getName()
2394 << Name.getSourceRange()
2396 return TNK_Non_template;
2399 bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
2400 const TemplateArgumentLoc &AL,
2401 SmallVectorImpl<TemplateArgument> &Converted) {
2402 const TemplateArgument &Arg = AL.getArgument();
2404 // Check template type parameter.
2405 switch(Arg.getKind()) {
2406 case TemplateArgument::Type:
2407 // C++ [temp.arg.type]p1:
2408 // A template-argument for a template-parameter which is a
2409 // type shall be a type-id.
2411 case TemplateArgument::Template: {
2412 // We have a template type parameter but the template argument
2413 // is a template without any arguments.
2414 SourceRange SR = AL.getSourceRange();
2415 TemplateName Name = Arg.getAsTemplate();
2416 Diag(SR.getBegin(), diag::err_template_missing_args)
2418 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
2419 Diag(Decl->getLocation(), diag::note_template_decl_here);
2424 // We have a template type parameter but the template argument
2426 SourceRange SR = AL.getSourceRange();
2427 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
2428 Diag(Param->getLocation(), diag::note_template_param_here);
2434 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
2437 // Add the converted template type argument.
2438 QualType ArgType = Context.getCanonicalType(Arg.getAsType());
2441 // If an explicitly-specified template argument type is a lifetime type
2442 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
2443 if (getLangOpts().ObjCAutoRefCount &&
2444 ArgType->isObjCLifetimeType() &&
2445 !ArgType.getObjCLifetime()) {
2447 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
2448 ArgType = Context.getQualifiedType(ArgType, Qs);
2451 Converted.push_back(TemplateArgument(ArgType));
2455 /// \brief Substitute template arguments into the default template argument for
2456 /// the given template type parameter.
2458 /// \param SemaRef the semantic analysis object for which we are performing
2459 /// the substitution.
2461 /// \param Template the template that we are synthesizing template arguments
2464 /// \param TemplateLoc the location of the template name that started the
2465 /// template-id we are checking.
2467 /// \param RAngleLoc the location of the right angle bracket ('>') that
2468 /// terminates the template-id.
2470 /// \param Param the template template parameter whose default we are
2471 /// substituting into.
2473 /// \param Converted the list of template arguments provided for template
2474 /// parameters that precede \p Param in the template parameter list.
2475 /// \returns the substituted template argument, or NULL if an error occurred.
2476 static TypeSourceInfo *
2477 SubstDefaultTemplateArgument(Sema &SemaRef,
2478 TemplateDecl *Template,
2479 SourceLocation TemplateLoc,
2480 SourceLocation RAngleLoc,
2481 TemplateTypeParmDecl *Param,
2482 SmallVectorImpl<TemplateArgument> &Converted) {
2483 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
2485 // If the argument type is dependent, instantiate it now based
2486 // on the previously-computed template arguments.
2487 if (ArgType->getType()->isDependentType()) {
2488 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2489 Converted.data(), Converted.size());
2491 MultiLevelTemplateArgumentList AllTemplateArgs
2492 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2494 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
2495 Template, Converted.data(),
2497 SourceRange(TemplateLoc, RAngleLoc));
2499 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
2500 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
2501 Param->getDefaultArgumentLoc(),
2502 Param->getDeclName());
2508 /// \brief Substitute template arguments into the default template argument for
2509 /// the given non-type template parameter.
2511 /// \param SemaRef the semantic analysis object for which we are performing
2512 /// the substitution.
2514 /// \param Template the template that we are synthesizing template arguments
2517 /// \param TemplateLoc the location of the template name that started the
2518 /// template-id we are checking.
2520 /// \param RAngleLoc the location of the right angle bracket ('>') that
2521 /// terminates the template-id.
2523 /// \param Param the non-type template parameter whose default we are
2524 /// substituting into.
2526 /// \param Converted the list of template arguments provided for template
2527 /// parameters that precede \p Param in the template parameter list.
2529 /// \returns the substituted template argument, or NULL if an error occurred.
2531 SubstDefaultTemplateArgument(Sema &SemaRef,
2532 TemplateDecl *Template,
2533 SourceLocation TemplateLoc,
2534 SourceLocation RAngleLoc,
2535 NonTypeTemplateParmDecl *Param,
2536 SmallVectorImpl<TemplateArgument> &Converted) {
2537 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2538 Converted.data(), Converted.size());
2540 MultiLevelTemplateArgumentList AllTemplateArgs
2541 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2543 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
2544 Template, Converted.data(),
2546 SourceRange(TemplateLoc, RAngleLoc));
2548 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
2549 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
2550 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
2553 /// \brief Substitute template arguments into the default template argument for
2554 /// the given template template parameter.
2556 /// \param SemaRef the semantic analysis object for which we are performing
2557 /// the substitution.
2559 /// \param Template the template that we are synthesizing template arguments
2562 /// \param TemplateLoc the location of the template name that started the
2563 /// template-id we are checking.
2565 /// \param RAngleLoc the location of the right angle bracket ('>') that
2566 /// terminates the template-id.
2568 /// \param Param the template template parameter whose default we are
2569 /// substituting into.
2571 /// \param Converted the list of template arguments provided for template
2572 /// parameters that precede \p Param in the template parameter list.
2574 /// \param QualifierLoc Will be set to the nested-name-specifier (with
2575 /// source-location information) that precedes the template name.
2577 /// \returns the substituted template argument, or NULL if an error occurred.
2579 SubstDefaultTemplateArgument(Sema &SemaRef,
2580 TemplateDecl *Template,
2581 SourceLocation TemplateLoc,
2582 SourceLocation RAngleLoc,
2583 TemplateTemplateParmDecl *Param,
2584 SmallVectorImpl<TemplateArgument> &Converted,
2585 NestedNameSpecifierLoc &QualifierLoc) {
2586 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2587 Converted.data(), Converted.size());
2589 MultiLevelTemplateArgumentList AllTemplateArgs
2590 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2592 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
2593 Template, Converted.data(),
2595 SourceRange(TemplateLoc, RAngleLoc));
2597 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
2598 // Substitute into the nested-name-specifier first,
2599 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
2601 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2604 return TemplateName();
2607 return SemaRef.SubstTemplateName(QualifierLoc,
2608 Param->getDefaultArgument().getArgument().getAsTemplate(),
2609 Param->getDefaultArgument().getTemplateNameLoc(),
2613 /// \brief If the given template parameter has a default template
2614 /// argument, substitute into that default template argument and
2615 /// return the corresponding template argument.
2617 Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
2618 SourceLocation TemplateLoc,
2619 SourceLocation RAngleLoc,
2621 SmallVectorImpl<TemplateArgument> &Converted) {
2622 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
2623 if (!TypeParm->hasDefaultArgument())
2624 return TemplateArgumentLoc();
2626 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
2632 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
2634 return TemplateArgumentLoc();
2637 if (NonTypeTemplateParmDecl *NonTypeParm
2638 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2639 if (!NonTypeParm->hasDefaultArgument())
2640 return TemplateArgumentLoc();
2642 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
2647 if (Arg.isInvalid())
2648 return TemplateArgumentLoc();
2650 Expr *ArgE = Arg.takeAs<Expr>();
2651 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
2654 TemplateTemplateParmDecl *TempTempParm
2655 = cast<TemplateTemplateParmDecl>(Param);
2656 if (!TempTempParm->hasDefaultArgument())
2657 return TemplateArgumentLoc();
2660 NestedNameSpecifierLoc QualifierLoc;
2661 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
2668 return TemplateArgumentLoc();
2670 return TemplateArgumentLoc(TemplateArgument(TName),
2671 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
2672 TempTempParm->getDefaultArgument().getTemplateNameLoc());
2675 /// \brief Check that the given template argument corresponds to the given
2676 /// template parameter.
2678 /// \param Param The template parameter against which the argument will be
2681 /// \param Arg The template argument.
2683 /// \param Template The template in which the template argument resides.
2685 /// \param TemplateLoc The location of the template name for the template
2686 /// whose argument list we're matching.
2688 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
2689 /// the template argument list.
2691 /// \param ArgumentPackIndex The index into the argument pack where this
2692 /// argument will be placed. Only valid if the parameter is a parameter pack.
2694 /// \param Converted The checked, converted argument will be added to the
2695 /// end of this small vector.
2697 /// \param CTAK Describes how we arrived at this particular template argument:
2698 /// explicitly written, deduced, etc.
2700 /// \returns true on error, false otherwise.
2701 bool Sema::CheckTemplateArgument(NamedDecl *Param,
2702 const TemplateArgumentLoc &Arg,
2703 NamedDecl *Template,
2704 SourceLocation TemplateLoc,
2705 SourceLocation RAngleLoc,
2706 unsigned ArgumentPackIndex,
2707 SmallVectorImpl<TemplateArgument> &Converted,
2708 CheckTemplateArgumentKind CTAK) {
2709 // Check template type parameters.
2710 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2711 return CheckTemplateTypeArgument(TTP, Arg, Converted);
2713 // Check non-type template parameters.
2714 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2715 // Do substitution on the type of the non-type template parameter
2716 // with the template arguments we've seen thus far. But if the
2717 // template has a dependent context then we cannot substitute yet.
2718 QualType NTTPType = NTTP->getType();
2719 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
2720 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
2722 if (NTTPType->isDependentType() &&
2723 !isa<TemplateTemplateParmDecl>(Template) &&
2724 !Template->getDeclContext()->isDependentContext()) {
2725 // Do substitution on the type of the non-type template parameter.
2726 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2727 NTTP, Converted.data(), Converted.size(),
2728 SourceRange(TemplateLoc, RAngleLoc));
2730 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2731 Converted.data(), Converted.size());
2732 NTTPType = SubstType(NTTPType,
2733 MultiLevelTemplateArgumentList(TemplateArgs),
2734 NTTP->getLocation(),
2735 NTTP->getDeclName());
2736 // If that worked, check the non-type template parameter type
2738 if (!NTTPType.isNull())
2739 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2740 NTTP->getLocation());
2741 if (NTTPType.isNull())
2745 switch (Arg.getArgument().getKind()) {
2746 case TemplateArgument::Null:
2747 llvm_unreachable("Should never see a NULL template argument here");
2749 case TemplateArgument::Expression: {
2750 TemplateArgument Result;
2752 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
2754 if (Res.isInvalid())
2757 Converted.push_back(Result);
2761 case TemplateArgument::Declaration:
2762 case TemplateArgument::Integral:
2763 // We've already checked this template argument, so just copy
2764 // it to the list of converted arguments.
2765 Converted.push_back(Arg.getArgument());
2768 case TemplateArgument::Template:
2769 case TemplateArgument::TemplateExpansion:
2770 // We were given a template template argument. It may not be ill-formed;
2772 if (DependentTemplateName *DTN
2773 = Arg.getArgument().getAsTemplateOrTemplatePattern()
2774 .getAsDependentTemplateName()) {
2775 // We have a template argument such as \c T::template X, which we
2776 // parsed as a template template argument. However, since we now
2777 // know that we need a non-type template argument, convert this
2778 // template name into an expression.
2780 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
2781 Arg.getTemplateNameLoc());
2784 SS.Adopt(Arg.getTemplateQualifierLoc());
2785 // FIXME: the template-template arg was a DependentTemplateName,
2786 // so it was provided with a template keyword. However, its source
2787 // location is not stored in the template argument structure.
2788 SourceLocation TemplateKWLoc;
2789 ExprResult E = Owned(DependentScopeDeclRefExpr::Create(Context,
2790 SS.getWithLocInContext(Context),
2794 // If we parsed the template argument as a pack expansion, create a
2795 // pack expansion expression.
2796 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
2797 E = ActOnPackExpansion(E.take(), Arg.getTemplateEllipsisLoc());
2802 TemplateArgument Result;
2803 E = CheckTemplateArgument(NTTP, NTTPType, E.take(), Result);
2807 Converted.push_back(Result);
2811 // We have a template argument that actually does refer to a class
2812 // template, alias template, or template template parameter, and
2813 // therefore cannot be a non-type template argument.
2814 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2815 << Arg.getSourceRange();
2817 Diag(Param->getLocation(), diag::note_template_param_here);
2820 case TemplateArgument::Type: {
2821 // We have a non-type template parameter but the template
2822 // argument is a type.
2824 // C++ [temp.arg]p2:
2825 // In a template-argument, an ambiguity between a type-id and
2826 // an expression is resolved to a type-id, regardless of the
2827 // form of the corresponding template-parameter.
2829 // We warn specifically about this case, since it can be rather
2830 // confusing for users.
2831 QualType T = Arg.getArgument().getAsType();
2832 SourceRange SR = Arg.getSourceRange();
2833 if (T->isFunctionType())
2834 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2836 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2837 Diag(Param->getLocation(), diag::note_template_param_here);
2841 case TemplateArgument::Pack:
2842 llvm_unreachable("Caller must expand template argument packs");
2849 // Check template template parameters.
2850 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2852 // Substitute into the template parameter list of the template
2853 // template parameter, since previously-supplied template arguments
2854 // may appear within the template template parameter.
2856 // Set up a template instantiation context.
2857 LocalInstantiationScope Scope(*this);
2858 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2859 TempParm, Converted.data(), Converted.size(),
2860 SourceRange(TemplateLoc, RAngleLoc));
2862 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2863 Converted.data(), Converted.size());
2864 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2865 SubstDecl(TempParm, CurContext,
2866 MultiLevelTemplateArgumentList(TemplateArgs)));
2871 switch (Arg.getArgument().getKind()) {
2872 case TemplateArgument::Null:
2873 llvm_unreachable("Should never see a NULL template argument here");
2875 case TemplateArgument::Template:
2876 case TemplateArgument::TemplateExpansion:
2877 if (CheckTemplateArgument(TempParm, Arg))
2880 Converted.push_back(Arg.getArgument());
2883 case TemplateArgument::Expression:
2884 case TemplateArgument::Type:
2885 // We have a template template parameter but the template
2886 // argument does not refer to a template.
2887 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
2888 << getLangOpts().CPlusPlus0x;
2891 case TemplateArgument::Declaration:
2892 llvm_unreachable("Declaration argument with template template parameter");
2893 case TemplateArgument::Integral:
2894 llvm_unreachable("Integral argument with template template parameter");
2896 case TemplateArgument::Pack:
2897 llvm_unreachable("Caller must expand template argument packs");
2903 /// \brief Diagnose an arity mismatch in the
2904 static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
2905 SourceLocation TemplateLoc,
2906 TemplateArgumentListInfo &TemplateArgs) {
2907 TemplateParameterList *Params = Template->getTemplateParameters();
2908 unsigned NumParams = Params->size();
2909 unsigned NumArgs = TemplateArgs.size();
2912 if (NumArgs > NumParams)
2913 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
2914 TemplateArgs.getRAngleLoc());
2915 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2916 << (NumArgs > NumParams)
2917 << (isa<ClassTemplateDecl>(Template)? 0 :
2918 isa<FunctionTemplateDecl>(Template)? 1 :
2919 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2920 << Template << Range;
2921 S.Diag(Template->getLocation(), diag::note_template_decl_here)
2922 << Params->getSourceRange();
2926 /// \brief Check that the given template argument list is well-formed
2927 /// for specializing the given template.
2928 bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2929 SourceLocation TemplateLoc,
2930 TemplateArgumentListInfo &TemplateArgs,
2931 bool PartialTemplateArgs,
2932 SmallVectorImpl<TemplateArgument> &Converted,
2933 bool *ExpansionIntoFixedList) {
2934 if (ExpansionIntoFixedList)
2935 *ExpansionIntoFixedList = false;
2937 TemplateParameterList *Params = Template->getTemplateParameters();
2938 unsigned NumParams = Params->size();
2939 unsigned NumArgs = TemplateArgs.size();
2940 bool Invalid = false;
2942 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2944 bool HasParameterPack =
2945 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
2947 // C++ [temp.arg]p1:
2948 // [...] The type and form of each template-argument specified in
2949 // a template-id shall match the type and form specified for the
2950 // corresponding parameter declared by the template in its
2951 // template-parameter-list.
2952 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
2953 SmallVector<TemplateArgument, 2> ArgumentPack;
2954 TemplateParameterList::iterator Param = Params->begin(),
2955 ParamEnd = Params->end();
2956 unsigned ArgIdx = 0;
2957 LocalInstantiationScope InstScope(*this, true);
2958 bool SawPackExpansion = false;
2959 while (Param != ParamEnd) {
2960 if (ArgIdx < NumArgs) {
2961 // If we have an expanded parameter pack, make sure we don't have too
2963 // FIXME: This really should fall out from the normal arity checking.
2964 if (NonTypeTemplateParmDecl *NTTP
2965 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2966 if (NTTP->isExpandedParameterPack() &&
2967 ArgumentPack.size() >= NTTP->getNumExpansionTypes()) {
2968 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2970 << (isa<ClassTemplateDecl>(Template)? 0 :
2971 isa<FunctionTemplateDecl>(Template)? 1 :
2972 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2974 Diag(Template->getLocation(), diag::note_template_decl_here)
2975 << Params->getSourceRange();
2980 // Check the template argument we were given.
2981 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2982 TemplateLoc, RAngleLoc,
2983 ArgumentPack.size(), Converted))
2986 if ((*Param)->isTemplateParameterPack()) {
2987 // The template parameter was a template parameter pack, so take the
2988 // deduced argument and place it on the argument pack. Note that we
2989 // stay on the same template parameter so that we can deduce more
2991 ArgumentPack.push_back(Converted.back());
2992 Converted.pop_back();
2994 // Move to the next template parameter.
2998 // If this template argument is a pack expansion, record that fact
2999 // and break out; we can't actually check any more.
3000 if (TemplateArgs[ArgIdx].getArgument().isPackExpansion()) {
3001 SawPackExpansion = true;
3010 // If we're checking a partial template argument list, we're done.
3011 if (PartialTemplateArgs) {
3012 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
3013 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
3014 ArgumentPack.data(),
3015 ArgumentPack.size()));
3020 // If we have a template parameter pack with no more corresponding
3021 // arguments, just break out now and we'll fill in the argument pack below.
3022 if ((*Param)->isTemplateParameterPack())
3025 // Check whether we have a default argument.
3026 TemplateArgumentLoc Arg;
3028 // Retrieve the default template argument from the template
3029 // parameter. For each kind of template parameter, we substitute the
3030 // template arguments provided thus far and any "outer" template arguments
3031 // (when the template parameter was part of a nested template) into
3032 // the default argument.
3033 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
3034 if (!TTP->hasDefaultArgument())
3035 return diagnoseArityMismatch(*this, Template, TemplateLoc,
3038 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
3047 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
3049 } else if (NonTypeTemplateParmDecl *NTTP
3050 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
3051 if (!NTTP->hasDefaultArgument())
3052 return diagnoseArityMismatch(*this, Template, TemplateLoc,
3055 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
3063 Expr *Ex = E.takeAs<Expr>();
3064 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
3066 TemplateTemplateParmDecl *TempParm
3067 = cast<TemplateTemplateParmDecl>(*Param);
3069 if (!TempParm->hasDefaultArgument())
3070 return diagnoseArityMismatch(*this, Template, TemplateLoc,
3073 NestedNameSpecifierLoc QualifierLoc;
3074 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
3083 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
3084 TempParm->getDefaultArgument().getTemplateNameLoc());
3087 // Introduce an instantiation record that describes where we are using
3088 // the default template argument.
3089 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
3090 Converted.data(), Converted.size(),
3091 SourceRange(TemplateLoc, RAngleLoc));
3093 // Check the default template argument.
3094 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
3095 RAngleLoc, 0, Converted))
3098 // Core issue 150 (assumed resolution): if this is a template template
3099 // parameter, keep track of the default template arguments from the
3100 // template definition.
3101 if (isTemplateTemplateParameter)
3102 TemplateArgs.addArgument(Arg);
3104 // Move to the next template parameter and argument.
3109 // If we saw a pack expansion, then directly convert the remaining arguments,
3110 // because we don't know what parameters they'll match up with.
3111 if (SawPackExpansion) {
3112 bool AddToArgumentPack
3113 = Param != ParamEnd && (*Param)->isTemplateParameterPack();
3114 while (ArgIdx < NumArgs) {
3115 if (AddToArgumentPack)
3116 ArgumentPack.push_back(TemplateArgs[ArgIdx].getArgument());
3118 Converted.push_back(TemplateArgs[ArgIdx].getArgument());
3122 // Push the argument pack onto the list of converted arguments.
3123 if (AddToArgumentPack) {
3124 if (ArgumentPack.empty())
3125 Converted.push_back(TemplateArgument(0, 0));
3127 Converted.push_back(
3128 TemplateArgument::CreatePackCopy(Context,
3129 ArgumentPack.data(),
3130 ArgumentPack.size()));
3131 ArgumentPack.clear();
3133 } else if (ExpansionIntoFixedList) {
3134 // We have expanded a pack into a fixed list.
3135 *ExpansionIntoFixedList = true;
3141 // If we have any leftover arguments, then there were too many arguments.
3142 // Complain and fail.
3143 if (ArgIdx < NumArgs)
3144 return diagnoseArityMismatch(*this, Template, TemplateLoc, TemplateArgs);
3146 // If we have an expanded parameter pack, make sure we don't have too
3148 // FIXME: This really should fall out from the normal arity checking.
3149 if (Param != ParamEnd) {
3150 if (NonTypeTemplateParmDecl *NTTP
3151 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
3152 if (NTTP->isExpandedParameterPack() &&
3153 ArgumentPack.size() < NTTP->getNumExpansionTypes()) {
3154 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3156 << (isa<ClassTemplateDecl>(Template)? 0 :
3157 isa<FunctionTemplateDecl>(Template)? 1 :
3158 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3160 Diag(Template->getLocation(), diag::note_template_decl_here)
3161 << Params->getSourceRange();
3167 // Form argument packs for each of the parameter packs remaining.
3168 while (Param != ParamEnd) {
3169 // If we're checking a partial list of template arguments, don't fill
3170 // in arguments for non-template parameter packs.
3171 if ((*Param)->isTemplateParameterPack()) {
3172 if (!HasParameterPack)
3174 if (ArgumentPack.empty())
3175 Converted.push_back(TemplateArgument(0, 0));
3177 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
3178 ArgumentPack.data(),
3179 ArgumentPack.size()));
3180 ArgumentPack.clear();
3182 } else if (!PartialTemplateArgs)
3183 return diagnoseArityMismatch(*this, Template, TemplateLoc, TemplateArgs);
3192 class UnnamedLocalNoLinkageFinder
3193 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
3198 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
3201 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
3203 bool Visit(QualType T) {
3204 return inherited::Visit(T.getTypePtr());
3207 #define TYPE(Class, Parent) \
3208 bool Visit##Class##Type(const Class##Type *);
3209 #define ABSTRACT_TYPE(Class, Parent) \
3210 bool Visit##Class##Type(const Class##Type *) { return false; }
3211 #define NON_CANONICAL_TYPE(Class, Parent) \
3212 bool Visit##Class##Type(const Class##Type *) { return false; }
3213 #include "clang/AST/TypeNodes.def"
3215 bool VisitTagDecl(const TagDecl *Tag);
3216 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
3220 bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
3224 bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
3225 return Visit(T->getElementType());
3228 bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
3229 return Visit(T->getPointeeType());
3232 bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
3233 const BlockPointerType* T) {
3234 return Visit(T->getPointeeType());
3237 bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
3238 const LValueReferenceType* T) {
3239 return Visit(T->getPointeeType());
3242 bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
3243 const RValueReferenceType* T) {
3244 return Visit(T->getPointeeType());
3247 bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
3248 const MemberPointerType* T) {
3249 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
3252 bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
3253 const ConstantArrayType* T) {
3254 return Visit(T->getElementType());
3257 bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
3258 const IncompleteArrayType* T) {
3259 return Visit(T->getElementType());
3262 bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
3263 const VariableArrayType* T) {
3264 return Visit(T->getElementType());
3267 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
3268 const DependentSizedArrayType* T) {
3269 return Visit(T->getElementType());
3272 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
3273 const DependentSizedExtVectorType* T) {
3274 return Visit(T->getElementType());
3277 bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
3278 return Visit(T->getElementType());
3281 bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
3282 return Visit(T->getElementType());
3285 bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
3286 const FunctionProtoType* T) {
3287 for (FunctionProtoType::arg_type_iterator A = T->arg_type_begin(),
3288 AEnd = T->arg_type_end();
3294 return Visit(T->getResultType());
3297 bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
3298 const FunctionNoProtoType* T) {
3299 return Visit(T->getResultType());
3302 bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
3303 const UnresolvedUsingType*) {
3307 bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
3311 bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
3312 return Visit(T->getUnderlyingType());
3315 bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
3319 bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
3320 const UnaryTransformType*) {
3324 bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
3325 return Visit(T->getDeducedType());
3328 bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
3329 return VisitTagDecl(T->getDecl());
3332 bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
3333 return VisitTagDecl(T->getDecl());
3336 bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
3337 const TemplateTypeParmType*) {
3341 bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
3342 const SubstTemplateTypeParmPackType *) {
3346 bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
3347 const TemplateSpecializationType*) {
3351 bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
3352 const InjectedClassNameType* T) {
3353 return VisitTagDecl(T->getDecl());
3356 bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
3357 const DependentNameType* T) {
3358 return VisitNestedNameSpecifier(T->getQualifier());
3361 bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
3362 const DependentTemplateSpecializationType* T) {
3363 return VisitNestedNameSpecifier(T->getQualifier());
3366 bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
3367 const PackExpansionType* T) {
3368 return Visit(T->getPattern());
3371 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
3375 bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
3376 const ObjCInterfaceType *) {
3380 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
3381 const ObjCObjectPointerType *) {
3385 bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
3386 return Visit(T->getValueType());
3389 bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
3390 if (Tag->getDeclContext()->isFunctionOrMethod()) {
3391 S.Diag(SR.getBegin(),
3392 S.getLangOpts().CPlusPlus0x ?
3393 diag::warn_cxx98_compat_template_arg_local_type :
3394 diag::ext_template_arg_local_type)
3395 << S.Context.getTypeDeclType(Tag) << SR;
3399 if (!Tag->getDeclName() && !Tag->getTypedefNameForAnonDecl()) {
3400 S.Diag(SR.getBegin(),
3401 S.getLangOpts().CPlusPlus0x ?
3402 diag::warn_cxx98_compat_template_arg_unnamed_type :
3403 diag::ext_template_arg_unnamed_type) << SR;
3404 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
3411 bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
3412 NestedNameSpecifier *NNS) {
3413 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
3416 switch (NNS->getKind()) {
3417 case NestedNameSpecifier::Identifier:
3418 case NestedNameSpecifier::Namespace:
3419 case NestedNameSpecifier::NamespaceAlias:
3420 case NestedNameSpecifier::Global:
3423 case NestedNameSpecifier::TypeSpec:
3424 case NestedNameSpecifier::TypeSpecWithTemplate:
3425 return Visit(QualType(NNS->getAsType(), 0));
3427 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
3431 /// \brief Check a template argument against its corresponding
3432 /// template type parameter.
3434 /// This routine implements the semantics of C++ [temp.arg.type]. It
3435 /// returns true if an error occurred, and false otherwise.
3436 bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
3437 TypeSourceInfo *ArgInfo) {
3438 assert(ArgInfo && "invalid TypeSourceInfo");
3439 QualType Arg = ArgInfo->getType();
3440 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
3442 if (Arg->isVariablyModifiedType()) {
3443 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
3444 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
3445 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
3448 // C++03 [temp.arg.type]p2:
3449 // A local type, a type with no linkage, an unnamed type or a type
3450 // compounded from any of these types shall not be used as a
3451 // template-argument for a template type-parameter.
3453 // C++11 allows these, and even in C++03 we allow them as an extension with
3455 if (LangOpts.CPlusPlus0x ?
3456 Diags.getDiagnosticLevel(diag::warn_cxx98_compat_template_arg_unnamed_type,
3457 SR.getBegin()) != DiagnosticsEngine::Ignored ||
3458 Diags.getDiagnosticLevel(diag::warn_cxx98_compat_template_arg_local_type,
3459 SR.getBegin()) != DiagnosticsEngine::Ignored :
3460 Arg->hasUnnamedOrLocalType()) {
3461 UnnamedLocalNoLinkageFinder Finder(*this, SR);
3462 (void)Finder.Visit(Context.getCanonicalType(Arg));
3468 enum NullPointerValueKind {
3474 /// \brief Determine whether the given template argument is a null pointer
3475 /// value of the appropriate type.
3476 static NullPointerValueKind
3477 isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
3478 QualType ParamType, Expr *Arg) {
3479 if (Arg->isValueDependent() || Arg->isTypeDependent())
3480 return NPV_NotNullPointer;
3482 if (!S.getLangOpts().CPlusPlus0x)
3483 return NPV_NotNullPointer;
3485 // Determine whether we have a constant expression.
3486 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
3487 if (ArgRV.isInvalid())
3491 Expr::EvalResult EvalResult;
3492 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
3493 EvalResult.Diag = &Notes;
3494 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
3495 EvalResult.HasSideEffects) {
3496 SourceLocation DiagLoc = Arg->getExprLoc();
3498 // If our only note is the usual "invalid subexpression" note, just point
3499 // the caret at its location rather than producing an essentially
3501 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
3502 diag::note_invalid_subexpr_in_const_expr) {
3503 DiagLoc = Notes[0].first;
3507 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
3508 << Arg->getType() << Arg->getSourceRange();
3509 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
3510 S.Diag(Notes[I].first, Notes[I].second);
3512 S.Diag(Param->getLocation(), diag::note_template_param_here);
3516 // C++11 [temp.arg.nontype]p1:
3517 // - an address constant expression of type std::nullptr_t
3518 if (Arg->getType()->isNullPtrType())
3519 return NPV_NullPointer;
3521 // - a constant expression that evaluates to a null pointer value (4.10); or
3522 // - a constant expression that evaluates to a null member pointer value
3524 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
3525 (EvalResult.Val.isMemberPointer() &&
3526 !EvalResult.Val.getMemberPointerDecl())) {
3527 // If our expression has an appropriate type, we've succeeded.
3528 bool ObjCLifetimeConversion;
3529 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
3530 S.IsQualificationConversion(Arg->getType(), ParamType, false,
3531 ObjCLifetimeConversion))
3532 return NPV_NullPointer;
3534 // The types didn't match, but we know we got a null pointer; complain,
3535 // then recover as if the types were correct.
3536 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
3537 << Arg->getType() << ParamType << Arg->getSourceRange();
3538 S.Diag(Param->getLocation(), diag::note_template_param_here);
3539 return NPV_NullPointer;
3542 // If we don't have a null pointer value, but we do have a NULL pointer
3543 // constant, suggest a cast to the appropriate type.
3544 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
3545 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
3546 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
3548 << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
3549 << FixItHint::CreateInsertion(S.PP.getLocForEndOfToken(Arg->getLocEnd()),
3551 S.Diag(Param->getLocation(), diag::note_template_param_here);
3552 return NPV_NullPointer;
3555 // FIXME: If we ever want to support general, address-constant expressions
3556 // as non-type template arguments, we should return the ExprResult here to
3557 // be interpreted by the caller.
3558 return NPV_NotNullPointer;
3561 /// \brief Checks whether the given template argument is the address
3562 /// of an object or function according to C++ [temp.arg.nontype]p1.
3564 CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
3565 NonTypeTemplateParmDecl *Param,
3568 TemplateArgument &Converted) {
3569 bool Invalid = false;
3571 QualType ArgType = Arg->getType();
3573 // If our parameter has pointer type, check for a null template value.
3574 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
3575 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
3576 case NPV_NullPointer:
3577 Converted = TemplateArgument((Decl *)0);
3583 case NPV_NotNullPointer:
3588 // See through any implicit casts we added to fix the type.
3589 Arg = Arg->IgnoreImpCasts();
3591 // C++ [temp.arg.nontype]p1:
3593 // A template-argument for a non-type, non-template
3594 // template-parameter shall be one of: [...]
3596 // -- the address of an object or function with external
3597 // linkage, including function templates and function
3598 // template-ids but excluding non-static class members,
3599 // expressed as & id-expression where the & is optional if
3600 // the name refers to a function or array, or if the
3601 // corresponding template-parameter is a reference; or
3603 // In C++98/03 mode, give an extension warning on any extra parentheses.
3604 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
3605 bool ExtraParens = false;
3606 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
3607 if (!Invalid && !ExtraParens) {
3608 S.Diag(Arg->getLocStart(),
3609 S.getLangOpts().CPlusPlus0x ?
3610 diag::warn_cxx98_compat_template_arg_extra_parens :
3611 diag::ext_template_arg_extra_parens)
3612 << Arg->getSourceRange();
3616 Arg = Parens->getSubExpr();
3619 while (SubstNonTypeTemplateParmExpr *subst =
3620 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
3621 Arg = subst->getReplacement()->IgnoreImpCasts();
3623 bool AddressTaken = false;
3624 SourceLocation AddrOpLoc;
3625 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
3626 if (UnOp->getOpcode() == UO_AddrOf) {
3627 Arg = UnOp->getSubExpr();
3628 AddressTaken = true;
3629 AddrOpLoc = UnOp->getOperatorLoc();
3633 if (S.getLangOpts().MicrosoftExt && isa<CXXUuidofExpr>(Arg)) {
3634 Converted = TemplateArgument(ArgIn);
3638 while (SubstNonTypeTemplateParmExpr *subst =
3639 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
3640 Arg = subst->getReplacement()->IgnoreImpCasts();
3642 // Stop checking the precise nature of the argument if it is value dependent,
3643 // it should be checked when instantiated.
3644 if (Arg->isValueDependent()) {
3645 Converted = TemplateArgument(ArgIn);
3649 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
3651 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
3652 << Arg->getSourceRange();
3653 S.Diag(Param->getLocation(), diag::note_template_param_here);
3657 if (!isa<ValueDecl>(DRE->getDecl())) {
3658 S.Diag(Arg->getLocStart(),
3659 diag::err_template_arg_not_object_or_func_form)
3660 << Arg->getSourceRange();
3661 S.Diag(Param->getLocation(), diag::note_template_param_here);
3665 NamedDecl *Entity = DRE->getDecl();
3667 // Cannot refer to non-static data members
3668 if (FieldDecl *Field = dyn_cast<FieldDecl>(Entity)) {
3669 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
3670 << Field << Arg->getSourceRange();
3671 S.Diag(Param->getLocation(), diag::note_template_param_here);
3675 // Cannot refer to non-static member functions
3676 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
3677 if (!Method->isStatic()) {
3678 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
3679 << Method << Arg->getSourceRange();
3680 S.Diag(Param->getLocation(), diag::note_template_param_here);
3685 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
3686 VarDecl *Var = dyn_cast<VarDecl>(Entity);
3688 // A non-type template argument must refer to an object or function.
3689 if (!Func && !Var) {
3690 // We found something, but we don't know specifically what it is.
3691 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
3692 << Arg->getSourceRange();
3693 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
3697 // Address / reference template args must have external linkage in C++98.
3698 if (Entity->getLinkage() == InternalLinkage) {
3699 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus0x ?
3700 diag::warn_cxx98_compat_template_arg_object_internal :
3701 diag::ext_template_arg_object_internal)
3702 << !Func << Entity << Arg->getSourceRange();
3703 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
3705 } else if (Entity->getLinkage() == NoLinkage) {
3706 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
3707 << !Func << Entity << Arg->getSourceRange();
3708 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
3714 // If the template parameter has pointer type, the function decays.
3715 if (ParamType->isPointerType() && !AddressTaken)
3716 ArgType = S.Context.getPointerType(Func->getType());
3717 else if (AddressTaken && ParamType->isReferenceType()) {
3718 // If we originally had an address-of operator, but the
3719 // parameter has reference type, complain and (if things look
3720 // like they will work) drop the address-of operator.
3721 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
3722 ParamType.getNonReferenceType())) {
3723 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
3725 S.Diag(Param->getLocation(), diag::note_template_param_here);
3729 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
3731 << FixItHint::CreateRemoval(AddrOpLoc);
3732 S.Diag(Param->getLocation(), diag::note_template_param_here);
3734 ArgType = Func->getType();
3737 // A value of reference type is not an object.
3738 if (Var->getType()->isReferenceType()) {
3739 S.Diag(Arg->getLocStart(),
3740 diag::err_template_arg_reference_var)
3741 << Var->getType() << Arg->getSourceRange();
3742 S.Diag(Param->getLocation(), diag::note_template_param_here);
3746 // A template argument must have static storage duration.
3747 // FIXME: Ensure this works for thread_local as well as __thread.
3748 if (Var->isThreadSpecified()) {
3749 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
3750 << Arg->getSourceRange();
3751 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
3755 // If the template parameter has pointer type, we must have taken
3756 // the address of this object.
3757 if (ParamType->isReferenceType()) {
3759 // If we originally had an address-of operator, but the
3760 // parameter has reference type, complain and (if things look
3761 // like they will work) drop the address-of operator.
3762 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
3763 ParamType.getNonReferenceType())) {
3764 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
3766 S.Diag(Param->getLocation(), diag::note_template_param_here);
3770 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
3772 << FixItHint::CreateRemoval(AddrOpLoc);
3773 S.Diag(Param->getLocation(), diag::note_template_param_here);
3775 ArgType = Var->getType();
3777 } else if (!AddressTaken && ParamType->isPointerType()) {
3778 if (Var->getType()->isArrayType()) {
3779 // Array-to-pointer decay.
3780 ArgType = S.Context.getArrayDecayedType(Var->getType());
3782 // If the template parameter has pointer type but the address of
3783 // this object was not taken, complain and (possibly) recover by
3784 // taking the address of the entity.
3785 ArgType = S.Context.getPointerType(Var->getType());
3786 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
3787 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
3789 S.Diag(Param->getLocation(), diag::note_template_param_here);
3793 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
3795 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
3797 S.Diag(Param->getLocation(), diag::note_template_param_here);
3802 bool ObjCLifetimeConversion;
3803 if (ParamType->isPointerType() &&
3804 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
3805 S.IsQualificationConversion(ArgType, ParamType, false,
3806 ObjCLifetimeConversion)) {
3807 // For pointer-to-object types, qualification conversions are
3810 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
3811 if (!ParamRef->getPointeeType()->isFunctionType()) {
3812 // C++ [temp.arg.nontype]p5b3:
3813 // For a non-type template-parameter of type reference to
3814 // object, no conversions apply. The type referred to by the
3815 // reference may be more cv-qualified than the (otherwise
3816 // identical) type of the template- argument. The
3817 // template-parameter is bound directly to the
3818 // template-argument, which shall be an lvalue.
3820 // FIXME: Other qualifiers?
3821 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
3822 unsigned ArgQuals = ArgType.getCVRQualifiers();
3824 if ((ParamQuals | ArgQuals) != ParamQuals) {
3825 S.Diag(Arg->getLocStart(),
3826 diag::err_template_arg_ref_bind_ignores_quals)
3827 << ParamType << Arg->getType()
3828 << Arg->getSourceRange();
3829 S.Diag(Param->getLocation(), diag::note_template_param_here);
3835 // At this point, the template argument refers to an object or
3836 // function with external linkage. We now need to check whether the
3837 // argument and parameter types are compatible.
3838 if (!S.Context.hasSameUnqualifiedType(ArgType,
3839 ParamType.getNonReferenceType())) {
3840 // We can't perform this conversion or binding.
3841 if (ParamType->isReferenceType())
3842 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
3843 << ParamType << ArgIn->getType() << Arg->getSourceRange();
3845 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
3846 << ArgIn->getType() << ParamType << Arg->getSourceRange();
3847 S.Diag(Param->getLocation(), diag::note_template_param_here);
3852 // Create the template argument.
3853 Converted = TemplateArgument(Entity->getCanonicalDecl());
3854 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity);
3858 /// \brief Checks whether the given template argument is a pointer to
3859 /// member constant according to C++ [temp.arg.nontype]p1.
3860 static bool CheckTemplateArgumentPointerToMember(Sema &S,
3861 NonTypeTemplateParmDecl *Param,
3864 TemplateArgument &Converted) {
3865 bool Invalid = false;
3867 // Check for a null pointer value.
3868 Expr *Arg = ResultArg;
3869 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
3872 case NPV_NullPointer:
3873 Converted = TemplateArgument((Decl *)0);
3875 case NPV_NotNullPointer:
3879 bool ObjCLifetimeConversion;
3880 if (S.IsQualificationConversion(Arg->getType(),
3881 ParamType.getNonReferenceType(),
3882 false, ObjCLifetimeConversion)) {
3883 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
3884 Arg->getValueKind()).take();
3886 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
3887 ParamType.getNonReferenceType())) {
3888 // We can't perform this conversion.
3889 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
3890 << Arg->getType() << ParamType << Arg->getSourceRange();
3891 S.Diag(Param->getLocation(), diag::note_template_param_here);
3895 // See through any implicit casts we added to fix the type.
3896 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
3897 Arg = Cast->getSubExpr();
3899 // C++ [temp.arg.nontype]p1:
3901 // A template-argument for a non-type, non-template
3902 // template-parameter shall be one of: [...]
3904 // -- a pointer to member expressed as described in 5.3.1.
3905 DeclRefExpr *DRE = 0;
3907 // In C++98/03 mode, give an extension warning on any extra parentheses.
3908 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
3909 bool ExtraParens = false;
3910 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
3911 if (!Invalid && !ExtraParens) {
3912 S.Diag(Arg->getLocStart(),
3913 S.getLangOpts().CPlusPlus0x ?
3914 diag::warn_cxx98_compat_template_arg_extra_parens :
3915 diag::ext_template_arg_extra_parens)
3916 << Arg->getSourceRange();
3920 Arg = Parens->getSubExpr();
3923 while (SubstNonTypeTemplateParmExpr *subst =
3924 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
3925 Arg = subst->getReplacement()->IgnoreImpCasts();
3927 // A pointer-to-member constant written &Class::member.
3928 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
3929 if (UnOp->getOpcode() == UO_AddrOf) {
3930 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
3931 if (DRE && !DRE->getQualifier())
3935 // A constant of pointer-to-member type.
3936 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
3937 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
3938 if (VD->getType()->isMemberPointerType()) {
3939 if (isa<NonTypeTemplateParmDecl>(VD) ||
3940 (isa<VarDecl>(VD) &&
3941 S.Context.getCanonicalType(VD->getType()).isConstQualified())) {
3942 if (Arg->isTypeDependent() || Arg->isValueDependent())
3943 Converted = TemplateArgument(Arg);
3945 Converted = TemplateArgument(VD->getCanonicalDecl());
3955 return S.Diag(Arg->getLocStart(),
3956 diag::err_template_arg_not_pointer_to_member_form)
3957 << Arg->getSourceRange();
3959 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
3960 assert((isa<FieldDecl>(DRE->getDecl()) ||
3961 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
3962 "Only non-static member pointers can make it here");
3964 // Okay: this is the address of a non-static member, and therefore
3965 // a member pointer constant.
3966 if (Arg->isTypeDependent() || Arg->isValueDependent())
3967 Converted = TemplateArgument(Arg);
3969 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
3973 // We found something else, but we don't know specifically what it is.
3974 S.Diag(Arg->getLocStart(),
3975 diag::err_template_arg_not_pointer_to_member_form)
3976 << Arg->getSourceRange();
3977 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
3981 /// \brief Check a template argument against its corresponding
3982 /// non-type template parameter.
3984 /// This routine implements the semantics of C++ [temp.arg.nontype].
3985 /// If an error occurred, it returns ExprError(); otherwise, it
3986 /// returns the converted template argument. \p
3987 /// InstantiatedParamType is the type of the non-type template
3988 /// parameter after it has been instantiated.
3989 ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
3990 QualType InstantiatedParamType, Expr *Arg,
3991 TemplateArgument &Converted,
3992 CheckTemplateArgumentKind CTAK) {
3993 SourceLocation StartLoc = Arg->getLocStart();
3995 // If either the parameter has a dependent type or the argument is
3996 // type-dependent, there's nothing we can check now.
3997 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
3998 // FIXME: Produce a cloned, canonical expression?
3999 Converted = TemplateArgument(Arg);
4003 // C++ [temp.arg.nontype]p5:
4004 // The following conversions are performed on each expression used
4005 // as a non-type template-argument. If a non-type
4006 // template-argument cannot be converted to the type of the
4007 // corresponding template-parameter then the program is
4009 QualType ParamType = InstantiatedParamType;
4010 if (ParamType->isIntegralOrEnumerationType()) {
4012 // -- for a non-type template-parameter of integral or
4013 // enumeration type, conversions permitted in a converted
4014 // constant expression are applied.
4017 // -- for a non-type template-parameter of integral or
4018 // enumeration type, integral promotions (4.5) and integral
4019 // conversions (4.7) are applied.
4021 if (CTAK == CTAK_Deduced &&
4022 !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) {
4023 // C++ [temp.deduct.type]p17:
4024 // If, in the declaration of a function template with a non-type
4025 // template-parameter, the non-type template-parameter is used
4026 // in an expression in the function parameter-list and, if the
4027 // corresponding template-argument is deduced, the
4028 // template-argument type shall match the type of the
4029 // template-parameter exactly, except that a template-argument
4030 // deduced from an array bound may be of any integral type.
4031 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
4032 << Arg->getType().getUnqualifiedType()
4033 << ParamType.getUnqualifiedType();
4034 Diag(Param->getLocation(), diag::note_template_param_here);
4038 if (getLangOpts().CPlusPlus0x) {
4039 // We can't check arbitrary value-dependent arguments.
4040 // FIXME: If there's no viable conversion to the template parameter type,
4041 // we should be able to diagnose that prior to instantiation.
4042 if (Arg->isValueDependent()) {
4043 Converted = TemplateArgument(Arg);
4047 // C++ [temp.arg.nontype]p1:
4048 // A template-argument for a non-type, non-template template-parameter
4051 // -- for a non-type template-parameter of integral or enumeration
4052 // type, a converted constant expression of the type of the
4053 // template-parameter; or
4055 ExprResult ArgResult =
4056 CheckConvertedConstantExpression(Arg, ParamType, Value,
4058 if (ArgResult.isInvalid())
4061 // Widen the argument value to sizeof(parameter type). This is almost
4062 // always a no-op, except when the parameter type is bool. In
4063 // that case, this may extend the argument from 1 bit to 8 bits.
4064 QualType IntegerType = ParamType;
4065 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
4066 IntegerType = Enum->getDecl()->getIntegerType();
4067 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
4069 Converted = TemplateArgument(Value, Context.getCanonicalType(ParamType));
4073 ExprResult ArgResult = DefaultLvalueConversion(Arg);
4074 if (ArgResult.isInvalid())
4076 Arg = ArgResult.take();
4078 QualType ArgType = Arg->getType();
4080 // C++ [temp.arg.nontype]p1:
4081 // A template-argument for a non-type, non-template
4082 // template-parameter shall be one of:
4084 // -- an integral constant-expression of integral or enumeration
4086 // -- the name of a non-type template-parameter; or
4087 SourceLocation NonConstantLoc;
4089 if (!ArgType->isIntegralOrEnumerationType()) {
4090 Diag(Arg->getLocStart(),
4091 diag::err_template_arg_not_integral_or_enumeral)
4092 << ArgType << Arg->getSourceRange();
4093 Diag(Param->getLocation(), diag::note_template_param_here);
4095 } else if (!Arg->isValueDependent()) {
4096 Arg = VerifyIntegerConstantExpression(Arg, &Value,
4097 PDiag(diag::err_template_arg_not_ice) << ArgType, false).take();
4102 // From here on out, all we care about are the unqualified forms
4103 // of the parameter and argument types.
4104 ParamType = ParamType.getUnqualifiedType();
4105 ArgType = ArgType.getUnqualifiedType();
4107 // Try to convert the argument to the parameter's type.
4108 if (Context.hasSameType(ParamType, ArgType)) {
4109 // Okay: no conversion necessary
4110 } else if (ParamType->isBooleanType()) {
4111 // This is an integral-to-boolean conversion.
4112 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).take();
4113 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
4114 !ParamType->isEnumeralType()) {
4115 // This is an integral promotion or conversion.
4116 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).take();
4118 // We can't perform this conversion.
4119 Diag(Arg->getLocStart(),
4120 diag::err_template_arg_not_convertible)
4121 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
4122 Diag(Param->getLocation(), diag::note_template_param_here);
4126 // Add the value of this argument to the list of converted
4127 // arguments. We use the bitwidth and signedness of the template
4129 if (Arg->isValueDependent()) {
4130 // The argument is value-dependent. Create a new
4131 // TemplateArgument with the converted expression.
4132 Converted = TemplateArgument(Arg);
4136 QualType IntegerType = Context.getCanonicalType(ParamType);
4137 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
4138 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
4140 if (ParamType->isBooleanType()) {
4141 // Value must be zero or one.
4143 unsigned AllowedBits = Context.getTypeSize(IntegerType);
4144 if (Value.getBitWidth() != AllowedBits)
4145 Value = Value.extOrTrunc(AllowedBits);
4146 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
4148 llvm::APSInt OldValue = Value;
4150 // Coerce the template argument's value to the value it will have
4151 // based on the template parameter's type.
4152 unsigned AllowedBits = Context.getTypeSize(IntegerType);
4153 if (Value.getBitWidth() != AllowedBits)
4154 Value = Value.extOrTrunc(AllowedBits);
4155 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
4157 // Complain if an unsigned parameter received a negative value.
4158 if (IntegerType->isUnsignedIntegerOrEnumerationType()
4159 && (OldValue.isSigned() && OldValue.isNegative())) {
4160 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
4161 << OldValue.toString(10) << Value.toString(10) << Param->getType()
4162 << Arg->getSourceRange();
4163 Diag(Param->getLocation(), diag::note_template_param_here);
4166 // Complain if we overflowed the template parameter's type.
4167 unsigned RequiredBits;
4168 if (IntegerType->isUnsignedIntegerOrEnumerationType())
4169 RequiredBits = OldValue.getActiveBits();
4170 else if (OldValue.isUnsigned())
4171 RequiredBits = OldValue.getActiveBits() + 1;
4173 RequiredBits = OldValue.getMinSignedBits();
4174 if (RequiredBits > AllowedBits) {
4175 Diag(Arg->getLocStart(),
4176 diag::warn_template_arg_too_large)
4177 << OldValue.toString(10) << Value.toString(10) << Param->getType()
4178 << Arg->getSourceRange();
4179 Diag(Param->getLocation(), diag::note_template_param_here);
4183 Converted = TemplateArgument(Value,
4184 ParamType->isEnumeralType()
4185 ? Context.getCanonicalType(ParamType)
4190 QualType ArgType = Arg->getType();
4191 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
4193 // Handle pointer-to-function, reference-to-function, and
4194 // pointer-to-member-function all in (roughly) the same way.
4195 if (// -- For a non-type template-parameter of type pointer to
4196 // function, only the function-to-pointer conversion (4.3) is
4197 // applied. If the template-argument represents a set of
4198 // overloaded functions (or a pointer to such), the matching
4199 // function is selected from the set (13.4).
4200 (ParamType->isPointerType() &&
4201 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
4202 // -- For a non-type template-parameter of type reference to
4203 // function, no conversions apply. If the template-argument
4204 // represents a set of overloaded functions, the matching
4205 // function is selected from the set (13.4).
4206 (ParamType->isReferenceType() &&
4207 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
4208 // -- For a non-type template-parameter of type pointer to
4209 // member function, no conversions apply. If the
4210 // template-argument represents a set of overloaded member
4211 // functions, the matching member function is selected from
4213 (ParamType->isMemberPointerType() &&
4214 ParamType->getAs<MemberPointerType>()->getPointeeType()
4215 ->isFunctionType())) {
4217 if (Arg->getType() == Context.OverloadTy) {
4218 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
4221 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
4224 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
4225 ArgType = Arg->getType();
4230 if (!ParamType->isMemberPointerType()) {
4231 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
4238 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
4244 if (ParamType->isPointerType()) {
4245 // -- for a non-type template-parameter of type pointer to
4246 // object, qualification conversions (4.4) and the
4247 // array-to-pointer conversion (4.2) are applied.
4248 // C++0x also allows a value of std::nullptr_t.
4249 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
4250 "Only object pointers allowed here");
4252 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
4259 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
4260 // -- For a non-type template-parameter of type reference to
4261 // object, no conversions apply. The type referred to by the
4262 // reference may be more cv-qualified than the (otherwise
4263 // identical) type of the template-argument. The
4264 // template-parameter is bound directly to the
4265 // template-argument, which must be an lvalue.
4266 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
4267 "Only object references allowed here");
4269 if (Arg->getType() == Context.OverloadTy) {
4270 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
4271 ParamRefType->getPointeeType(),
4274 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
4277 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
4278 ArgType = Arg->getType();
4283 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
4290 // Deal with parameters of type std::nullptr_t.
4291 if (ParamType->isNullPtrType()) {
4292 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
4293 Converted = TemplateArgument(Arg);
4297 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
4298 case NPV_NotNullPointer:
4299 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
4300 << Arg->getType() << ParamType;
4301 Diag(Param->getLocation(), diag::note_template_param_here);
4307 case NPV_NullPointer:
4308 Converted = TemplateArgument((Decl *)0);
4313 // -- For a non-type template-parameter of type pointer to data
4314 // member, qualification conversions (4.4) are applied.
4315 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
4317 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
4323 /// \brief Check a template argument against its corresponding
4324 /// template template parameter.
4326 /// This routine implements the semantics of C++ [temp.arg.template].
4327 /// It returns true if an error occurred, and false otherwise.
4328 bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
4329 const TemplateArgumentLoc &Arg) {
4330 TemplateName Name = Arg.getArgument().getAsTemplate();
4331 TemplateDecl *Template = Name.getAsTemplateDecl();
4333 // Any dependent template name is fine.
4334 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
4338 // C++0x [temp.arg.template]p1:
4339 // A template-argument for a template template-parameter shall be
4340 // the name of a class template or an alias template, expressed as an
4341 // id-expression. When the template-argument names a class template, only
4342 // primary class templates are considered when matching the
4343 // template template argument with the corresponding parameter;
4344 // partial specializations are not considered even if their
4345 // parameter lists match that of the template template parameter.
4347 // Note that we also allow template template parameters here, which
4348 // will happen when we are dealing with, e.g., class template
4349 // partial specializations.
4350 if (!isa<ClassTemplateDecl>(Template) &&
4351 !isa<TemplateTemplateParmDecl>(Template) &&
4352 !isa<TypeAliasTemplateDecl>(Template)) {
4353 assert(isa<FunctionTemplateDecl>(Template) &&
4354 "Only function templates are possible here");
4355 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
4356 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
4360 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
4361 Param->getTemplateParameters(),
4363 TPL_TemplateTemplateArgumentMatch,
4367 /// \brief Given a non-type template argument that refers to a
4368 /// declaration and the type of its corresponding non-type template
4369 /// parameter, produce an expression that properly refers to that
4372 Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
4374 SourceLocation Loc) {
4375 assert(Arg.getKind() == TemplateArgument::Declaration &&
4376 "Only declaration template arguments permitted here");
4378 // For a NULL non-type template argument, return nullptr casted to the
4379 // parameter's type.
4380 if (!Arg.getAsDecl()) {
4381 return ImpCastExprToType(
4382 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
4384 ParamType->getAs<MemberPointerType>()
4385 ? CK_NullToMemberPointer
4386 : CK_NullToPointer);
4389 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
4391 if (VD->getDeclContext()->isRecord() &&
4392 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
4393 // If the value is a class member, we might have a pointer-to-member.
4394 // Determine whether the non-type template template parameter is of
4395 // pointer-to-member type. If so, we need to build an appropriate
4396 // expression for a pointer-to-member, since a "normal" DeclRefExpr
4397 // would refer to the member itself.
4398 if (ParamType->isMemberPointerType()) {
4400 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
4401 NestedNameSpecifier *Qualifier
4402 = NestedNameSpecifier::Create(Context, 0, false,
4403 ClassType.getTypePtr());
4405 SS.MakeTrivial(Context, Qualifier, Loc);
4407 // The actual value-ness of this is unimportant, but for
4408 // internal consistency's sake, references to instance methods
4410 ExprValueKind VK = VK_LValue;
4411 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
4414 ExprResult RefExpr = BuildDeclRefExpr(VD,
4415 VD->getType().getNonReferenceType(),
4419 if (RefExpr.isInvalid())
4422 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
4424 // We might need to perform a trailing qualification conversion, since
4425 // the element type on the parameter could be more qualified than the
4426 // element type in the expression we constructed.
4427 bool ObjCLifetimeConversion;
4428 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
4429 ParamType.getUnqualifiedType(), false,
4430 ObjCLifetimeConversion))
4431 RefExpr = ImpCastExprToType(RefExpr.take(), ParamType.getUnqualifiedType(), CK_NoOp);
4433 assert(!RefExpr.isInvalid() &&
4434 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
4435 ParamType.getUnqualifiedType()));
4436 return move(RefExpr);
4440 QualType T = VD->getType().getNonReferenceType();
4441 if (ParamType->isPointerType()) {
4442 // When the non-type template parameter is a pointer, take the
4443 // address of the declaration.
4444 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
4445 if (RefExpr.isInvalid())
4448 if (T->isFunctionType() || T->isArrayType()) {
4449 // Decay functions and arrays.
4450 RefExpr = DefaultFunctionArrayConversion(RefExpr.take());
4451 if (RefExpr.isInvalid())
4454 return move(RefExpr);
4457 // Take the address of everything else
4458 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
4461 ExprValueKind VK = VK_RValue;
4463 // If the non-type template parameter has reference type, qualify the
4464 // resulting declaration reference with the extra qualifiers on the
4465 // type that the reference refers to.
4466 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
4468 T = Context.getQualifiedType(T,
4469 TargetRef->getPointeeType().getQualifiers());
4472 return BuildDeclRefExpr(VD, T, VK, Loc);
4475 /// \brief Construct a new expression that refers to the given
4476 /// integral template argument with the given source-location
4479 /// This routine takes care of the mapping from an integral template
4480 /// argument (which may have any integral type) to the appropriate
4483 Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
4484 SourceLocation Loc) {
4485 assert(Arg.getKind() == TemplateArgument::Integral &&
4486 "Operation is only valid for integral template arguments");
4487 QualType T = Arg.getIntegralType();
4488 if (T->isAnyCharacterType()) {
4489 CharacterLiteral::CharacterKind Kind;
4490 if (T->isWideCharType())
4491 Kind = CharacterLiteral::Wide;
4492 else if (T->isChar16Type())
4493 Kind = CharacterLiteral::UTF16;
4494 else if (T->isChar32Type())
4495 Kind = CharacterLiteral::UTF32;
4497 Kind = CharacterLiteral::Ascii;
4499 return Owned(new (Context) CharacterLiteral(
4500 Arg.getAsIntegral()->getZExtValue(),
4504 if (T->isBooleanType())
4505 return Owned(new (Context) CXXBoolLiteralExpr(
4506 Arg.getAsIntegral()->getBoolValue(),
4509 if (T->isNullPtrType())
4510 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
4512 // If this is an enum type that we're instantiating, we need to use an integer
4513 // type the same size as the enumerator. We don't want to build an
4514 // IntegerLiteral with enum type.
4516 if (const EnumType *ET = T->getAs<EnumType>())
4517 BT = ET->getDecl()->getIntegerType();
4521 Expr *E = IntegerLiteral::Create(Context, *Arg.getAsIntegral(), BT, Loc);
4522 if (T->isEnumeralType()) {
4523 // FIXME: This is a hack. We need a better way to handle substituted
4524 // non-type template parameters.
4525 E = CStyleCastExpr::Create(Context, T, VK_RValue, CK_IntegralCast, E, 0,
4526 Context.getTrivialTypeSourceInfo(T, Loc),
4533 /// \brief Match two template parameters within template parameter lists.
4534 static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
4536 Sema::TemplateParameterListEqualKind Kind,
4537 SourceLocation TemplateArgLoc) {
4538 // Check the actual kind (type, non-type, template).
4539 if (Old->getKind() != New->getKind()) {
4541 unsigned NextDiag = diag::err_template_param_different_kind;
4542 if (TemplateArgLoc.isValid()) {
4543 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
4544 NextDiag = diag::note_template_param_different_kind;
4546 S.Diag(New->getLocation(), NextDiag)
4547 << (Kind != Sema::TPL_TemplateMatch);
4548 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
4549 << (Kind != Sema::TPL_TemplateMatch);
4555 // Check that both are parameter packs are neither are parameter packs.
4556 // However, if we are matching a template template argument to a
4557 // template template parameter, the template template parameter can have
4558 // a parameter pack where the template template argument does not.
4559 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
4560 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
4561 Old->isTemplateParameterPack())) {
4563 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
4564 if (TemplateArgLoc.isValid()) {
4565 S.Diag(TemplateArgLoc,
4566 diag::err_template_arg_template_params_mismatch);
4567 NextDiag = diag::note_template_parameter_pack_non_pack;
4570 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
4571 : isa<NonTypeTemplateParmDecl>(New)? 1
4573 S.Diag(New->getLocation(), NextDiag)
4574 << ParamKind << New->isParameterPack();
4575 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
4576 << ParamKind << Old->isParameterPack();
4582 // For non-type template parameters, check the type of the parameter.
4583 if (NonTypeTemplateParmDecl *OldNTTP
4584 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
4585 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
4587 // If we are matching a template template argument to a template
4588 // template parameter and one of the non-type template parameter types
4589 // is dependent, then we must wait until template instantiation time
4590 // to actually compare the arguments.
4591 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
4592 (OldNTTP->getType()->isDependentType() ||
4593 NewNTTP->getType()->isDependentType()))
4596 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
4598 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
4599 if (TemplateArgLoc.isValid()) {
4600 S.Diag(TemplateArgLoc,
4601 diag::err_template_arg_template_params_mismatch);
4602 NextDiag = diag::note_template_nontype_parm_different_type;
4604 S.Diag(NewNTTP->getLocation(), NextDiag)
4605 << NewNTTP->getType()
4606 << (Kind != Sema::TPL_TemplateMatch);
4607 S.Diag(OldNTTP->getLocation(),
4608 diag::note_template_nontype_parm_prev_declaration)
4609 << OldNTTP->getType();
4618 // For template template parameters, check the template parameter types.
4619 // The template parameter lists of template template
4620 // parameters must agree.
4621 if (TemplateTemplateParmDecl *OldTTP
4622 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
4623 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
4624 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
4625 OldTTP->getTemplateParameters(),
4627 (Kind == Sema::TPL_TemplateMatch
4628 ? Sema::TPL_TemplateTemplateParmMatch
4636 /// \brief Diagnose a known arity mismatch when comparing template argument
4639 void DiagnoseTemplateParameterListArityMismatch(Sema &S,
4640 TemplateParameterList *New,
4641 TemplateParameterList *Old,
4642 Sema::TemplateParameterListEqualKind Kind,
4643 SourceLocation TemplateArgLoc) {
4644 unsigned NextDiag = diag::err_template_param_list_different_arity;
4645 if (TemplateArgLoc.isValid()) {
4646 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
4647 NextDiag = diag::note_template_param_list_different_arity;
4649 S.Diag(New->getTemplateLoc(), NextDiag)
4650 << (New->size() > Old->size())
4651 << (Kind != Sema::TPL_TemplateMatch)
4652 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
4653 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
4654 << (Kind != Sema::TPL_TemplateMatch)
4655 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
4658 /// \brief Determine whether the given template parameter lists are
4661 /// \param New The new template parameter list, typically written in the
4662 /// source code as part of a new template declaration.
4664 /// \param Old The old template parameter list, typically found via
4665 /// name lookup of the template declared with this template parameter
4668 /// \param Complain If true, this routine will produce a diagnostic if
4669 /// the template parameter lists are not equivalent.
4671 /// \param Kind describes how we are to match the template parameter lists.
4673 /// \param TemplateArgLoc If this source location is valid, then we
4674 /// are actually checking the template parameter list of a template
4675 /// argument (New) against the template parameter list of its
4676 /// corresponding template template parameter (Old). We produce
4677 /// slightly different diagnostics in this scenario.
4679 /// \returns True if the template parameter lists are equal, false
4682 Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
4683 TemplateParameterList *Old,
4685 TemplateParameterListEqualKind Kind,
4686 SourceLocation TemplateArgLoc) {
4687 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
4689 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
4695 // C++0x [temp.arg.template]p3:
4696 // A template-argument matches a template template-parameter (call it P)
4697 // when each of the template parameters in the template-parameter-list of
4698 // the template-argument's corresponding class template or alias template
4699 // (call it A) matches the corresponding template parameter in the
4700 // template-parameter-list of P. [...]
4701 TemplateParameterList::iterator NewParm = New->begin();
4702 TemplateParameterList::iterator NewParmEnd = New->end();
4703 for (TemplateParameterList::iterator OldParm = Old->begin(),
4704 OldParmEnd = Old->end();
4705 OldParm != OldParmEnd; ++OldParm) {
4706 if (Kind != TPL_TemplateTemplateArgumentMatch ||
4707 !(*OldParm)->isTemplateParameterPack()) {
4708 if (NewParm == NewParmEnd) {
4710 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
4716 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
4717 Kind, TemplateArgLoc))
4724 // C++0x [temp.arg.template]p3:
4725 // [...] When P's template- parameter-list contains a template parameter
4726 // pack (14.5.3), the template parameter pack will match zero or more
4727 // template parameters or template parameter packs in the
4728 // template-parameter-list of A with the same type and form as the
4729 // template parameter pack in P (ignoring whether those template
4730 // parameters are template parameter packs).
4731 for (; NewParm != NewParmEnd; ++NewParm) {
4732 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
4733 Kind, TemplateArgLoc))
4738 // Make sure we exhausted all of the arguments.
4739 if (NewParm != NewParmEnd) {
4741 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
4750 /// \brief Check whether a template can be declared within this scope.
4752 /// If the template declaration is valid in this scope, returns
4753 /// false. Otherwise, issues a diagnostic and returns true.
4755 Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
4759 // Find the nearest enclosing declaration scope.
4760 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4761 (S->getFlags() & Scope::TemplateParamScope) != 0)
4765 // A template-declaration can appear only as a namespace scope or
4766 // class scope declaration.
4767 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
4768 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
4769 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
4770 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
4771 << TemplateParams->getSourceRange();
4773 while (Ctx && isa<LinkageSpecDecl>(Ctx))
4774 Ctx = Ctx->getParent();
4776 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
4779 return Diag(TemplateParams->getTemplateLoc(),
4780 diag::err_template_outside_namespace_or_class_scope)
4781 << TemplateParams->getSourceRange();
4784 /// \brief Determine what kind of template specialization the given declaration
4786 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
4788 return TSK_Undeclared;
4790 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
4791 return Record->getTemplateSpecializationKind();
4792 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
4793 return Function->getTemplateSpecializationKind();
4794 if (VarDecl *Var = dyn_cast<VarDecl>(D))
4795 return Var->getTemplateSpecializationKind();
4797 return TSK_Undeclared;
4800 /// \brief Check whether a specialization is well-formed in the current
4803 /// This routine determines whether a template specialization can be declared
4804 /// in the current context (C++ [temp.expl.spec]p2).
4806 /// \param S the semantic analysis object for which this check is being
4809 /// \param Specialized the entity being specialized or instantiated, which
4810 /// may be a kind of template (class template, function template, etc.) or
4811 /// a member of a class template (member function, static data member,
4814 /// \param PrevDecl the previous declaration of this entity, if any.
4816 /// \param Loc the location of the explicit specialization or instantiation of
4819 /// \param IsPartialSpecialization whether this is a partial specialization of
4820 /// a class template.
4822 /// \returns true if there was an error that we cannot recover from, false
4824 static bool CheckTemplateSpecializationScope(Sema &S,
4825 NamedDecl *Specialized,
4826 NamedDecl *PrevDecl,
4828 bool IsPartialSpecialization) {
4829 // Keep these "kind" numbers in sync with the %select statements in the
4830 // various diagnostics emitted by this routine.
4832 if (isa<ClassTemplateDecl>(Specialized))
4833 EntityKind = IsPartialSpecialization? 1 : 0;
4834 else if (isa<FunctionTemplateDecl>(Specialized))
4836 else if (isa<CXXMethodDecl>(Specialized))
4838 else if (isa<VarDecl>(Specialized))
4840 else if (isa<RecordDecl>(Specialized))
4842 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus0x)
4845 S.Diag(Loc, diag::err_template_spec_unknown_kind)
4846 << S.getLangOpts().CPlusPlus0x;
4847 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
4851 // C++ [temp.expl.spec]p2:
4852 // An explicit specialization shall be declared in the namespace
4853 // of which the template is a member, or, for member templates, in
4854 // the namespace of which the enclosing class or enclosing class
4855 // template is a member. An explicit specialization of a member
4856 // function, member class or static data member of a class
4857 // template shall be declared in the namespace of which the class
4858 // template is a member. Such a declaration may also be a
4859 // definition. If the declaration is not a definition, the
4860 // specialization may be defined later in the name- space in which
4861 // the explicit specialization was declared, or in a namespace
4862 // that encloses the one in which the explicit specialization was
4864 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
4865 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
4870 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
4871 if (S.getLangOpts().MicrosoftExt) {
4872 // Do not warn for class scope explicit specialization during
4873 // instantiation, warning was already emitted during pattern
4874 // semantic analysis.
4875 if (!S.ActiveTemplateInstantiations.size())
4876 S.Diag(Loc, diag::ext_function_specialization_in_class)
4879 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
4885 if (S.CurContext->isRecord() &&
4886 !S.CurContext->Equals(Specialized->getDeclContext())) {
4887 // Make sure that we're specializing in the right record context.
4888 // Otherwise, things can go horribly wrong.
4889 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
4894 // C++ [temp.class.spec]p6:
4895 // A class template partial specialization may be declared or redeclared
4896 // in any namespace scope in which its definition may be defined (14.5.1
4898 bool ComplainedAboutScope = false;
4899 DeclContext *SpecializedContext
4900 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
4901 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
4903 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
4904 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
4905 // C++ [temp.exp.spec]p2:
4906 // An explicit specialization shall be declared in the namespace of which
4907 // the template is a member, or, for member templates, in the namespace
4908 // of which the enclosing class or enclosing class template is a member.
4909 // An explicit specialization of a member function, member class or
4910 // static data member of a class template shall be declared in the
4911 // namespace of which the class template is a member.
4913 // C++0x [temp.expl.spec]p2:
4914 // An explicit specialization shall be declared in a namespace enclosing
4915 // the specialized template.
4916 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
4917 bool IsCPlusPlus0xExtension = DC->Encloses(SpecializedContext);
4918 if (isa<TranslationUnitDecl>(SpecializedContext)) {
4919 assert(!IsCPlusPlus0xExtension &&
4920 "DC encloses TU but isn't in enclosing namespace set");
4921 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
4922 << EntityKind << Specialized;
4923 } else if (isa<NamespaceDecl>(SpecializedContext)) {
4925 if (!IsCPlusPlus0xExtension)
4926 Diag = diag::err_template_spec_decl_out_of_scope;
4927 else if (!S.getLangOpts().CPlusPlus0x)
4928 Diag = diag::ext_template_spec_decl_out_of_scope;
4930 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
4932 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
4935 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
4936 ComplainedAboutScope =
4937 !(IsCPlusPlus0xExtension && S.getLangOpts().CPlusPlus0x);
4941 // Make sure that this redeclaration (or definition) occurs in an enclosing
4943 // Note that HandleDeclarator() performs this check for explicit
4944 // specializations of function templates, static data members, and member
4945 // functions, so we skip the check here for those kinds of entities.
4946 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
4947 // Should we refactor that check, so that it occurs later?
4948 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
4949 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
4950 isa<FunctionDecl>(Specialized))) {
4951 if (isa<TranslationUnitDecl>(SpecializedContext))
4952 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
4953 << EntityKind << Specialized;
4954 else if (isa<NamespaceDecl>(SpecializedContext))
4955 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
4956 << EntityKind << Specialized
4957 << cast<NamedDecl>(SpecializedContext);
4959 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
4962 // FIXME: check for specialization-after-instantiation errors and such.
4967 /// \brief Subroutine of Sema::CheckClassTemplatePartialSpecializationArgs
4968 /// that checks non-type template partial specialization arguments.
4969 static bool CheckNonTypeClassTemplatePartialSpecializationArgs(Sema &S,
4970 NonTypeTemplateParmDecl *Param,
4971 const TemplateArgument *Args,
4973 for (unsigned I = 0; I != NumArgs; ++I) {
4974 if (Args[I].getKind() == TemplateArgument::Pack) {
4975 if (CheckNonTypeClassTemplatePartialSpecializationArgs(S, Param,
4976 Args[I].pack_begin(),
4977 Args[I].pack_size()))
4983 Expr *ArgExpr = Args[I].getAsExpr();
4988 // We can have a pack expansion of any of the bullets below.
4989 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
4990 ArgExpr = Expansion->getPattern();
4992 // Strip off any implicit casts we added as part of type checking.
4993 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
4994 ArgExpr = ICE->getSubExpr();
4996 // C++ [temp.class.spec]p8:
4997 // A non-type argument is non-specialized if it is the name of a
4998 // non-type parameter. All other non-type arguments are
5001 // Below, we check the two conditions that only apply to
5002 // specialized non-type arguments, so skip any non-specialized
5004 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
5005 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
5008 // C++ [temp.class.spec]p9:
5009 // Within the argument list of a class template partial
5010 // specialization, the following restrictions apply:
5011 // -- A partially specialized non-type argument expression
5012 // shall not involve a template parameter of the partial
5013 // specialization except when the argument expression is a
5014 // simple identifier.
5015 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
5016 S.Diag(ArgExpr->getLocStart(),
5017 diag::err_dependent_non_type_arg_in_partial_spec)
5018 << ArgExpr->getSourceRange();
5022 // -- The type of a template parameter corresponding to a
5023 // specialized non-type argument shall not be dependent on a
5024 // parameter of the specialization.
5025 if (Param->getType()->isDependentType()) {
5026 S.Diag(ArgExpr->getLocStart(),
5027 diag::err_dependent_typed_non_type_arg_in_partial_spec)
5029 << ArgExpr->getSourceRange();
5030 S.Diag(Param->getLocation(), diag::note_template_param_here);
5038 /// \brief Check the non-type template arguments of a class template
5039 /// partial specialization according to C++ [temp.class.spec]p9.
5041 /// \param TemplateParams the template parameters of the primary class
5044 /// \param TemplateArg the template arguments of the class template
5045 /// partial specialization.
5047 /// \returns true if there was an error, false otherwise.
5048 static bool CheckClassTemplatePartialSpecializationArgs(Sema &S,
5049 TemplateParameterList *TemplateParams,
5050 SmallVectorImpl<TemplateArgument> &TemplateArgs) {
5051 const TemplateArgument *ArgList = TemplateArgs.data();
5053 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
5054 NonTypeTemplateParmDecl *Param
5055 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
5059 if (CheckNonTypeClassTemplatePartialSpecializationArgs(S, Param,
5068 Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
5070 SourceLocation KWLoc,
5071 SourceLocation ModulePrivateLoc,
5073 TemplateTy TemplateD,
5074 SourceLocation TemplateNameLoc,
5075 SourceLocation LAngleLoc,
5076 ASTTemplateArgsPtr TemplateArgsIn,
5077 SourceLocation RAngleLoc,
5078 AttributeList *Attr,
5079 MultiTemplateParamsArg TemplateParameterLists) {
5080 assert(TUK != TUK_Reference && "References are not specializations");
5082 // NOTE: KWLoc is the location of the tag keyword. This will instead
5083 // store the location of the outermost template keyword in the declaration.
5084 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
5085 ? TemplateParameterLists.get()[0]->getTemplateLoc() : SourceLocation();
5087 // Find the class template we're specializing
5088 TemplateName Name = TemplateD.getAsVal<TemplateName>();
5089 ClassTemplateDecl *ClassTemplate
5090 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
5092 if (!ClassTemplate) {
5093 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
5094 << (Name.getAsTemplateDecl() &&
5095 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
5099 bool isExplicitSpecialization = false;
5100 bool isPartialSpecialization = false;
5102 // Check the validity of the template headers that introduce this
5104 // FIXME: We probably shouldn't complain about these headers for
5105 // friend declarations.
5106 bool Invalid = false;
5107 TemplateParameterList *TemplateParams
5108 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc,
5111 (TemplateParameterList**)TemplateParameterLists.get(),
5112 TemplateParameterLists.size(),
5114 isExplicitSpecialization,
5119 if (TemplateParams && TemplateParams->size() > 0) {
5120 isPartialSpecialization = true;
5122 if (TUK == TUK_Friend) {
5123 Diag(KWLoc, diag::err_partial_specialization_friend)
5124 << SourceRange(LAngleLoc, RAngleLoc);
5128 // C++ [temp.class.spec]p10:
5129 // The template parameter list of a specialization shall not
5130 // contain default template argument values.
5131 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
5132 Decl *Param = TemplateParams->getParam(I);
5133 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
5134 if (TTP->hasDefaultArgument()) {
5135 Diag(TTP->getDefaultArgumentLoc(),
5136 diag::err_default_arg_in_partial_spec);
5137 TTP->removeDefaultArgument();
5139 } else if (NonTypeTemplateParmDecl *NTTP
5140 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5141 if (Expr *DefArg = NTTP->getDefaultArgument()) {
5142 Diag(NTTP->getDefaultArgumentLoc(),
5143 diag::err_default_arg_in_partial_spec)
5144 << DefArg->getSourceRange();
5145 NTTP->removeDefaultArgument();
5148 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
5149 if (TTP->hasDefaultArgument()) {
5150 Diag(TTP->getDefaultArgument().getLocation(),
5151 diag::err_default_arg_in_partial_spec)
5152 << TTP->getDefaultArgument().getSourceRange();
5153 TTP->removeDefaultArgument();
5157 } else if (TemplateParams) {
5158 if (TUK == TUK_Friend)
5159 Diag(KWLoc, diag::err_template_spec_friend)
5160 << FixItHint::CreateRemoval(
5161 SourceRange(TemplateParams->getTemplateLoc(),
5162 TemplateParams->getRAngleLoc()))
5163 << SourceRange(LAngleLoc, RAngleLoc);
5165 isExplicitSpecialization = true;
5166 } else if (TUK != TUK_Friend) {
5167 Diag(KWLoc, diag::err_template_spec_needs_header)
5168 << FixItHint::CreateInsertion(KWLoc, "template<> ");
5169 isExplicitSpecialization = true;
5172 // Check that the specialization uses the same tag kind as the
5173 // original template.
5174 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
5175 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
5176 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
5177 Kind, TUK == TUK_Definition, KWLoc,
5178 *ClassTemplate->getIdentifier())) {
5179 Diag(KWLoc, diag::err_use_with_wrong_tag)
5181 << FixItHint::CreateReplacement(KWLoc,
5182 ClassTemplate->getTemplatedDecl()->getKindName());
5183 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
5184 diag::note_previous_use);
5185 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
5188 // Translate the parser's template argument list in our AST format.
5189 TemplateArgumentListInfo TemplateArgs;
5190 TemplateArgs.setLAngleLoc(LAngleLoc);
5191 TemplateArgs.setRAngleLoc(RAngleLoc);
5192 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
5194 // Check for unexpanded parameter packs in any of the template arguments.
5195 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
5196 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
5197 UPPC_PartialSpecialization))
5200 // Check that the template argument list is well-formed for this
5202 SmallVector<TemplateArgument, 4> Converted;
5203 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
5204 TemplateArgs, false, Converted))
5207 // Find the class template (partial) specialization declaration that
5208 // corresponds to these arguments.
5209 if (isPartialSpecialization) {
5210 if (CheckClassTemplatePartialSpecializationArgs(*this,
5211 ClassTemplate->getTemplateParameters(),
5215 bool InstantiationDependent;
5216 if (!Name.isDependent() &&
5217 !TemplateSpecializationType::anyDependentTemplateArguments(
5218 TemplateArgs.getArgumentArray(),
5219 TemplateArgs.size(),
5220 InstantiationDependent)) {
5221 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
5222 << ClassTemplate->getDeclName();
5223 isPartialSpecialization = false;
5227 void *InsertPos = 0;
5228 ClassTemplateSpecializationDecl *PrevDecl = 0;
5230 if (isPartialSpecialization)
5231 // FIXME: Template parameter list matters, too
5233 = ClassTemplate->findPartialSpecialization(Converted.data(),
5238 = ClassTemplate->findSpecialization(Converted.data(),
5239 Converted.size(), InsertPos);
5241 ClassTemplateSpecializationDecl *Specialization = 0;
5243 // Check whether we can declare a class template specialization in
5244 // the current scope.
5245 if (TUK != TUK_Friend &&
5246 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
5248 isPartialSpecialization))
5251 // The canonical type
5254 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
5255 TUK == TUK_Friend)) {
5256 // Since the only prior class template specialization with these
5257 // arguments was referenced but not declared, or we're only
5258 // referencing this specialization as a friend, reuse that
5259 // declaration node as our own, updating its source location and
5260 // the list of outer template parameters to reflect our new declaration.
5261 Specialization = PrevDecl;
5262 Specialization->setLocation(TemplateNameLoc);
5263 if (TemplateParameterLists.size() > 0) {
5264 Specialization->setTemplateParameterListsInfo(Context,
5265 TemplateParameterLists.size(),
5266 (TemplateParameterList**) TemplateParameterLists.release());
5269 CanonType = Context.getTypeDeclType(Specialization);
5270 } else if (isPartialSpecialization) {
5271 // Build the canonical type that describes the converted template
5272 // arguments of the class template partial specialization.
5273 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
5274 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
5278 if (Context.hasSameType(CanonType,
5279 ClassTemplate->getInjectedClassNameSpecialization())) {
5280 // C++ [temp.class.spec]p9b3:
5282 // -- The argument list of the specialization shall not be identical
5283 // to the implicit argument list of the primary template.
5284 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
5285 << (TUK == TUK_Definition)
5286 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
5287 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
5288 ClassTemplate->getIdentifier(),
5292 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
5293 TemplateParameterLists.size() - 1,
5294 (TemplateParameterList**) TemplateParameterLists.release());
5297 // Create a new class template partial specialization declaration node.
5298 ClassTemplatePartialSpecializationDecl *PrevPartial
5299 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
5300 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
5301 : ClassTemplate->getNextPartialSpecSequenceNumber();
5302 ClassTemplatePartialSpecializationDecl *Partial
5303 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
5304 ClassTemplate->getDeclContext(),
5305 KWLoc, TemplateNameLoc,
5314 SetNestedNameSpecifier(Partial, SS);
5315 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
5316 Partial->setTemplateParameterListsInfo(Context,
5317 TemplateParameterLists.size() - 1,
5318 (TemplateParameterList**) TemplateParameterLists.release());
5322 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
5323 Specialization = Partial;
5325 // If we are providing an explicit specialization of a member class
5326 // template specialization, make a note of that.
5327 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
5328 PrevPartial->setMemberSpecialization();
5330 // Check that all of the template parameters of the class template
5331 // partial specialization are deducible from the template
5332 // arguments. If not, this class template partial specialization
5333 // will never be used.
5334 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
5335 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
5336 TemplateParams->getDepth(),
5339 if (!DeducibleParams.all()) {
5340 unsigned NumNonDeducible = DeducibleParams.size()-DeducibleParams.count();
5341 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
5342 << (NumNonDeducible > 1)
5343 << SourceRange(TemplateNameLoc, RAngleLoc);
5344 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
5345 if (!DeducibleParams[I]) {
5346 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
5347 if (Param->getDeclName())
5348 Diag(Param->getLocation(),
5349 diag::note_partial_spec_unused_parameter)
5350 << Param->getDeclName();
5352 Diag(Param->getLocation(),
5353 diag::note_partial_spec_unused_parameter)
5359 // Create a new class template specialization declaration node for
5360 // this explicit specialization or friend declaration.
5362 = ClassTemplateSpecializationDecl::Create(Context, Kind,
5363 ClassTemplate->getDeclContext(),
5364 KWLoc, TemplateNameLoc,
5369 SetNestedNameSpecifier(Specialization, SS);
5370 if (TemplateParameterLists.size() > 0) {
5371 Specialization->setTemplateParameterListsInfo(Context,
5372 TemplateParameterLists.size(),
5373 (TemplateParameterList**) TemplateParameterLists.release());
5377 ClassTemplate->AddSpecialization(Specialization, InsertPos);
5379 CanonType = Context.getTypeDeclType(Specialization);
5382 // C++ [temp.expl.spec]p6:
5383 // If a template, a member template or the member of a class template is
5384 // explicitly specialized then that specialization shall be declared
5385 // before the first use of that specialization that would cause an implicit
5386 // instantiation to take place, in every translation unit in which such a
5387 // use occurs; no diagnostic is required.
5388 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
5390 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
5391 // Is there any previous explicit specialization declaration?
5392 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
5399 SourceRange Range(TemplateNameLoc, RAngleLoc);
5400 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
5401 << Context.getTypeDeclType(Specialization) << Range;
5403 Diag(PrevDecl->getPointOfInstantiation(),
5404 diag::note_instantiation_required_here)
5405 << (PrevDecl->getTemplateSpecializationKind()
5406 != TSK_ImplicitInstantiation);
5411 // If this is not a friend, note that this is an explicit specialization.
5412 if (TUK != TUK_Friend)
5413 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
5415 // Check that this isn't a redefinition of this specialization.
5416 if (TUK == TUK_Definition) {
5417 if (RecordDecl *Def = Specialization->getDefinition()) {
5418 SourceRange Range(TemplateNameLoc, RAngleLoc);
5419 Diag(TemplateNameLoc, diag::err_redefinition)
5420 << Context.getTypeDeclType(Specialization) << Range;
5421 Diag(Def->getLocation(), diag::note_previous_definition);
5422 Specialization->setInvalidDecl();
5428 ProcessDeclAttributeList(S, Specialization, Attr);
5430 if (ModulePrivateLoc.isValid())
5431 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
5432 << (isPartialSpecialization? 1 : 0)
5433 << FixItHint::CreateRemoval(ModulePrivateLoc);
5435 // Build the fully-sugared type for this class template
5436 // specialization as the user wrote in the specialization
5437 // itself. This means that we'll pretty-print the type retrieved
5438 // from the specialization's declaration the way that the user
5439 // actually wrote the specialization, rather than formatting the
5440 // name based on the "canonical" representation used to store the
5441 // template arguments in the specialization.
5442 TypeSourceInfo *WrittenTy
5443 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
5444 TemplateArgs, CanonType);
5445 if (TUK != TUK_Friend) {
5446 Specialization->setTypeAsWritten(WrittenTy);
5447 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
5449 TemplateArgsIn.release();
5451 // C++ [temp.expl.spec]p9:
5452 // A template explicit specialization is in the scope of the
5453 // namespace in which the template was defined.
5455 // We actually implement this paragraph where we set the semantic
5456 // context (in the creation of the ClassTemplateSpecializationDecl),
5457 // but we also maintain the lexical context where the actual
5458 // definition occurs.
5459 Specialization->setLexicalDeclContext(CurContext);
5461 // We may be starting the definition of this specialization.
5462 if (TUK == TUK_Definition)
5463 Specialization->startDefinition();
5465 if (TUK == TUK_Friend) {
5466 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
5470 Friend->setAccess(AS_public);
5471 CurContext->addDecl(Friend);
5473 // Add the specialization into its lexical context, so that it can
5474 // be seen when iterating through the list of declarations in that
5475 // context. However, specializations are not found by name lookup.
5476 CurContext->addDecl(Specialization);
5478 return Specialization;
5481 Decl *Sema::ActOnTemplateDeclarator(Scope *S,
5482 MultiTemplateParamsArg TemplateParameterLists,
5484 return HandleDeclarator(S, D, move(TemplateParameterLists));
5487 Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
5488 MultiTemplateParamsArg TemplateParameterLists,
5490 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
5491 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5493 if (FTI.hasPrototype) {
5494 // FIXME: Diagnose arguments without names in C.
5497 Scope *ParentScope = FnBodyScope->getParent();
5499 D.setFunctionDefinitionKind(FDK_Definition);
5500 Decl *DP = HandleDeclarator(ParentScope, D,
5501 move(TemplateParameterLists));
5502 if (FunctionTemplateDecl *FunctionTemplate
5503 = dyn_cast_or_null<FunctionTemplateDecl>(DP))
5504 return ActOnStartOfFunctionDef(FnBodyScope,
5505 FunctionTemplate->getTemplatedDecl());
5506 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP))
5507 return ActOnStartOfFunctionDef(FnBodyScope, Function);
5511 /// \brief Strips various properties off an implicit instantiation
5512 /// that has just been explicitly specialized.
5513 static void StripImplicitInstantiation(NamedDecl *D) {
5514 // FIXME: "make check" is clean if the call to dropAttrs() is commented out.
5517 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5518 FD->setInlineSpecified(false);
5522 /// \brief Compute the diagnostic location for an explicit instantiation
5523 // declaration or definition.
5524 static SourceLocation DiagLocForExplicitInstantiation(
5525 NamedDecl* D, SourceLocation PointOfInstantiation) {
5526 // Explicit instantiations following a specialization have no effect and
5527 // hence no PointOfInstantiation. In that case, walk decl backwards
5528 // until a valid name loc is found.
5529 SourceLocation PrevDiagLoc = PointOfInstantiation;
5530 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
5531 Prev = Prev->getPreviousDecl()) {
5532 PrevDiagLoc = Prev->getLocation();
5534 assert(PrevDiagLoc.isValid() &&
5535 "Explicit instantiation without point of instantiation?");
5539 /// \brief Diagnose cases where we have an explicit template specialization
5540 /// before/after an explicit template instantiation, producing diagnostics
5541 /// for those cases where they are required and determining whether the
5542 /// new specialization/instantiation will have any effect.
5544 /// \param NewLoc the location of the new explicit specialization or
5547 /// \param NewTSK the kind of the new explicit specialization or instantiation.
5549 /// \param PrevDecl the previous declaration of the entity.
5551 /// \param PrevTSK the kind of the old explicit specialization or instantiatin.
5553 /// \param PrevPointOfInstantiation if valid, indicates where the previus
5554 /// declaration was instantiated (either implicitly or explicitly).
5556 /// \param HasNoEffect will be set to true to indicate that the new
5557 /// specialization or instantiation has no effect and should be ignored.
5559 /// \returns true if there was an error that should prevent the introduction of
5560 /// the new declaration into the AST, false otherwise.
5562 Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
5563 TemplateSpecializationKind NewTSK,
5564 NamedDecl *PrevDecl,
5565 TemplateSpecializationKind PrevTSK,
5566 SourceLocation PrevPointOfInstantiation,
5567 bool &HasNoEffect) {
5568 HasNoEffect = false;
5571 case TSK_Undeclared:
5572 case TSK_ImplicitInstantiation:
5573 llvm_unreachable("Don't check implicit instantiations here");
5575 case TSK_ExplicitSpecialization:
5577 case TSK_Undeclared:
5578 case TSK_ExplicitSpecialization:
5579 // Okay, we're just specializing something that is either already
5580 // explicitly specialized or has merely been mentioned without any
5584 case TSK_ImplicitInstantiation:
5585 if (PrevPointOfInstantiation.isInvalid()) {
5586 // The declaration itself has not actually been instantiated, so it is
5587 // still okay to specialize it.
5588 StripImplicitInstantiation(PrevDecl);
5593 case TSK_ExplicitInstantiationDeclaration:
5594 case TSK_ExplicitInstantiationDefinition:
5595 assert((PrevTSK == TSK_ImplicitInstantiation ||
5596 PrevPointOfInstantiation.isValid()) &&
5597 "Explicit instantiation without point of instantiation?");
5599 // C++ [temp.expl.spec]p6:
5600 // If a template, a member template or the member of a class template
5601 // is explicitly specialized then that specialization shall be declared
5602 // before the first use of that specialization that would cause an
5603 // implicit instantiation to take place, in every translation unit in
5604 // which such a use occurs; no diagnostic is required.
5605 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
5606 // Is there any previous explicit specialization declaration?
5607 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
5611 Diag(NewLoc, diag::err_specialization_after_instantiation)
5613 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
5614 << (PrevTSK != TSK_ImplicitInstantiation);
5619 case TSK_ExplicitInstantiationDeclaration:
5621 case TSK_ExplicitInstantiationDeclaration:
5622 // This explicit instantiation declaration is redundant (that's okay).
5626 case TSK_Undeclared:
5627 case TSK_ImplicitInstantiation:
5628 // We're explicitly instantiating something that may have already been
5629 // implicitly instantiated; that's fine.
5632 case TSK_ExplicitSpecialization:
5633 // C++0x [temp.explicit]p4:
5634 // For a given set of template parameters, if an explicit instantiation
5635 // of a template appears after a declaration of an explicit
5636 // specialization for that template, the explicit instantiation has no
5641 case TSK_ExplicitInstantiationDefinition:
5642 // C++0x [temp.explicit]p10:
5643 // If an entity is the subject of both an explicit instantiation
5644 // declaration and an explicit instantiation definition in the same
5645 // translation unit, the definition shall follow the declaration.
5647 diag::err_explicit_instantiation_declaration_after_definition);
5649 // Explicit instantiations following a specialization have no effect and
5650 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
5651 // until a valid name loc is found.
5652 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
5653 diag::note_explicit_instantiation_definition_here);
5658 case TSK_ExplicitInstantiationDefinition:
5660 case TSK_Undeclared:
5661 case TSK_ImplicitInstantiation:
5662 // We're explicitly instantiating something that may have already been
5663 // implicitly instantiated; that's fine.
5666 case TSK_ExplicitSpecialization:
5667 // C++ DR 259, C++0x [temp.explicit]p4:
5668 // For a given set of template parameters, if an explicit
5669 // instantiation of a template appears after a declaration of
5670 // an explicit specialization for that template, the explicit
5671 // instantiation has no effect.
5673 // In C++98/03 mode, we only give an extension warning here, because it
5674 // is not harmful to try to explicitly instantiate something that
5675 // has been explicitly specialized.
5676 Diag(NewLoc, getLangOpts().CPlusPlus0x ?
5677 diag::warn_cxx98_compat_explicit_instantiation_after_specialization :
5678 diag::ext_explicit_instantiation_after_specialization)
5680 Diag(PrevDecl->getLocation(),
5681 diag::note_previous_template_specialization);
5685 case TSK_ExplicitInstantiationDeclaration:
5686 // We're explicity instantiating a definition for something for which we
5687 // were previously asked to suppress instantiations. That's fine.
5689 // C++0x [temp.explicit]p4:
5690 // For a given set of template parameters, if an explicit instantiation
5691 // of a template appears after a declaration of an explicit
5692 // specialization for that template, the explicit instantiation has no
5694 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
5695 // Is there any previous explicit specialization declaration?
5696 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
5704 case TSK_ExplicitInstantiationDefinition:
5705 // C++0x [temp.spec]p5:
5706 // For a given template and a given set of template-arguments,
5707 // - an explicit instantiation definition shall appear at most once
5709 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
5711 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
5712 diag::note_previous_explicit_instantiation);
5718 llvm_unreachable("Missing specialization/instantiation case?");
5721 /// \brief Perform semantic analysis for the given dependent function
5722 /// template specialization. The only possible way to get a dependent
5723 /// function template specialization is with a friend declaration,
5726 /// template <class T> void foo(T);
5727 /// template <class T> class A {
5728 /// friend void foo<>(T);
5731 /// There really isn't any useful analysis we can do here, so we
5732 /// just store the information.
5734 Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
5735 const TemplateArgumentListInfo &ExplicitTemplateArgs,
5736 LookupResult &Previous) {
5737 // Remove anything from Previous that isn't a function template in
5738 // the correct context.
5739 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
5740 LookupResult::Filter F = Previous.makeFilter();
5741 while (F.hasNext()) {
5742 NamedDecl *D = F.next()->getUnderlyingDecl();
5743 if (!isa<FunctionTemplateDecl>(D) ||
5744 !FDLookupContext->InEnclosingNamespaceSetOf(
5745 D->getDeclContext()->getRedeclContext()))
5750 // Should this be diagnosed here?
5751 if (Previous.empty()) return true;
5753 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
5754 ExplicitTemplateArgs);
5758 /// \brief Perform semantic analysis for the given function template
5761 /// This routine performs all of the semantic analysis required for an
5762 /// explicit function template specialization. On successful completion,
5763 /// the function declaration \p FD will become a function template
5766 /// \param FD the function declaration, which will be updated to become a
5767 /// function template specialization.
5769 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
5770 /// if any. Note that this may be valid info even when 0 arguments are
5771 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
5772 /// as it anyway contains info on the angle brackets locations.
5774 /// \param Previous the set of declarations that may be specialized by
5775 /// this function specialization.
5777 Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
5778 TemplateArgumentListInfo *ExplicitTemplateArgs,
5779 LookupResult &Previous) {
5780 // The set of function template specializations that could match this
5781 // explicit function template specialization.
5782 UnresolvedSet<8> Candidates;
5784 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
5785 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5787 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
5788 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
5789 // Only consider templates found within the same semantic lookup scope as
5791 if (!FDLookupContext->InEnclosingNamespaceSetOf(
5792 Ovl->getDeclContext()->getRedeclContext()))
5795 // C++ [temp.expl.spec]p11:
5796 // A trailing template-argument can be left unspecified in the
5797 // template-id naming an explicit function template specialization
5798 // provided it can be deduced from the function argument type.
5799 // Perform template argument deduction to determine whether we may be
5800 // specializing this template.
5801 // FIXME: It is somewhat wasteful to build
5802 TemplateDeductionInfo Info(Context, FD->getLocation());
5803 FunctionDecl *Specialization = 0;
5804 if (TemplateDeductionResult TDK
5805 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
5809 // FIXME: Template argument deduction failed; record why it failed, so
5810 // that we can provide nifty diagnostics.
5815 // Record this candidate.
5816 Candidates.addDecl(Specialization, I.getAccess());
5820 // Find the most specialized function template.
5821 UnresolvedSetIterator Result
5822 = getMostSpecialized(Candidates.begin(), Candidates.end(),
5823 TPOC_Other, 0, FD->getLocation(),
5824 PDiag(diag::err_function_template_spec_no_match)
5825 << FD->getDeclName(),
5826 PDiag(diag::err_function_template_spec_ambiguous)
5827 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
5828 PDiag(diag::note_function_template_spec_matched));
5829 if (Result == Candidates.end())
5832 // Ignore access information; it doesn't figure into redeclaration checking.
5833 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
5835 FunctionTemplateSpecializationInfo *SpecInfo
5836 = Specialization->getTemplateSpecializationInfo();
5837 assert(SpecInfo && "Function template specialization info missing?");
5839 // Note: do not overwrite location info if previous template
5840 // specialization kind was explicit.
5841 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
5842 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
5843 Specialization->setLocation(FD->getLocation());
5844 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
5845 // function can differ from the template declaration with respect to
5846 // the constexpr specifier.
5847 Specialization->setConstexpr(FD->isConstexpr());
5850 // FIXME: Check if the prior specialization has a point of instantiation.
5851 // If so, we have run afoul of .
5853 // If this is a friend declaration, then we're not really declaring
5854 // an explicit specialization.
5855 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
5857 // Check the scope of this explicit specialization.
5859 CheckTemplateSpecializationScope(*this,
5860 Specialization->getPrimaryTemplate(),
5861 Specialization, FD->getLocation(),
5865 // C++ [temp.expl.spec]p6:
5866 // If a template, a member template or the member of a class template is
5867 // explicitly specialized then that specialization shall be declared
5868 // before the first use of that specialization that would cause an implicit
5869 // instantiation to take place, in every translation unit in which such a
5870 // use occurs; no diagnostic is required.
5871 bool HasNoEffect = false;
5873 CheckSpecializationInstantiationRedecl(FD->getLocation(),
5874 TSK_ExplicitSpecialization,
5876 SpecInfo->getTemplateSpecializationKind(),
5877 SpecInfo->getPointOfInstantiation(),
5881 // Mark the prior declaration as an explicit specialization, so that later
5882 // clients know that this is an explicit specialization.
5884 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
5885 MarkUnusedFileScopedDecl(Specialization);
5888 // Turn the given function declaration into a function template
5889 // specialization, with the template arguments from the previous
5891 // Take copies of (semantic and syntactic) template argument lists.
5892 const TemplateArgumentList* TemplArgs = new (Context)
5893 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
5894 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
5895 TemplArgs, /*InsertPos=*/0,
5896 SpecInfo->getTemplateSpecializationKind(),
5897 ExplicitTemplateArgs);
5898 FD->setStorageClass(Specialization->getStorageClass());
5900 // The "previous declaration" for this function template specialization is
5901 // the prior function template specialization.
5903 Previous.addDecl(Specialization);
5907 /// \brief Perform semantic analysis for the given non-template member
5910 /// This routine performs all of the semantic analysis required for an
5911 /// explicit member function specialization. On successful completion,
5912 /// the function declaration \p FD will become a member function
5915 /// \param Member the member declaration, which will be updated to become a
5918 /// \param Previous the set of declarations, one of which may be specialized
5919 /// by this function specialization; the set will be modified to contain the
5920 /// redeclared member.
5922 Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
5923 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
5925 // Try to find the member we are instantiating.
5926 NamedDecl *Instantiation = 0;
5927 NamedDecl *InstantiatedFrom = 0;
5928 MemberSpecializationInfo *MSInfo = 0;
5930 if (Previous.empty()) {
5931 // Nowhere to look anyway.
5932 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
5933 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5935 NamedDecl *D = (*I)->getUnderlyingDecl();
5936 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
5937 if (Context.hasSameType(Function->getType(), Method->getType())) {
5938 Instantiation = Method;
5939 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
5940 MSInfo = Method->getMemberSpecializationInfo();
5945 } else if (isa<VarDecl>(Member)) {
5947 if (Previous.isSingleResult() &&
5948 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
5949 if (PrevVar->isStaticDataMember()) {
5950 Instantiation = PrevVar;
5951 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
5952 MSInfo = PrevVar->getMemberSpecializationInfo();
5954 } else if (isa<RecordDecl>(Member)) {
5955 CXXRecordDecl *PrevRecord;
5956 if (Previous.isSingleResult() &&
5957 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
5958 Instantiation = PrevRecord;
5959 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
5960 MSInfo = PrevRecord->getMemberSpecializationInfo();
5962 } else if (isa<EnumDecl>(Member)) {
5964 if (Previous.isSingleResult() &&
5965 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
5966 Instantiation = PrevEnum;
5967 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
5968 MSInfo = PrevEnum->getMemberSpecializationInfo();
5972 if (!Instantiation) {
5973 // There is no previous declaration that matches. Since member
5974 // specializations are always out-of-line, the caller will complain about
5975 // this mismatch later.
5979 // If this is a friend, just bail out here before we start turning
5980 // things into explicit specializations.
5981 if (Member->getFriendObjectKind() != Decl::FOK_None) {
5982 // Preserve instantiation information.
5983 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
5984 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
5985 cast<CXXMethodDecl>(InstantiatedFrom),
5986 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
5987 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
5988 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
5989 cast<CXXRecordDecl>(InstantiatedFrom),
5990 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
5994 Previous.addDecl(Instantiation);
5998 // Make sure that this is a specialization of a member.
5999 if (!InstantiatedFrom) {
6000 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
6002 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
6006 // C++ [temp.expl.spec]p6:
6007 // If a template, a member template or the member of a class template is
6008 // explicitly specialized then that specialization shall be declared
6009 // before the first use of that specialization that would cause an implicit
6010 // instantiation to take place, in every translation unit in which such a
6011 // use occurs; no diagnostic is required.
6012 assert(MSInfo && "Member specialization info missing?");
6014 bool HasNoEffect = false;
6015 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
6016 TSK_ExplicitSpecialization,
6018 MSInfo->getTemplateSpecializationKind(),
6019 MSInfo->getPointOfInstantiation(),
6023 // Check the scope of this explicit specialization.
6024 if (CheckTemplateSpecializationScope(*this,
6026 Instantiation, Member->getLocation(),
6030 // Note that this is an explicit instantiation of a member.
6031 // the original declaration to note that it is an explicit specialization
6032 // (if it was previously an implicit instantiation). This latter step
6033 // makes bookkeeping easier.
6034 if (isa<FunctionDecl>(Member)) {
6035 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
6036 if (InstantiationFunction->getTemplateSpecializationKind() ==
6037 TSK_ImplicitInstantiation) {
6038 InstantiationFunction->setTemplateSpecializationKind(
6039 TSK_ExplicitSpecialization);
6040 InstantiationFunction->setLocation(Member->getLocation());
6043 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
6044 cast<CXXMethodDecl>(InstantiatedFrom),
6045 TSK_ExplicitSpecialization);
6046 MarkUnusedFileScopedDecl(InstantiationFunction);
6047 } else if (isa<VarDecl>(Member)) {
6048 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
6049 if (InstantiationVar->getTemplateSpecializationKind() ==
6050 TSK_ImplicitInstantiation) {
6051 InstantiationVar->setTemplateSpecializationKind(
6052 TSK_ExplicitSpecialization);
6053 InstantiationVar->setLocation(Member->getLocation());
6056 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
6057 cast<VarDecl>(InstantiatedFrom),
6058 TSK_ExplicitSpecialization);
6059 MarkUnusedFileScopedDecl(InstantiationVar);
6060 } else if (isa<CXXRecordDecl>(Member)) {
6061 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
6062 if (InstantiationClass->getTemplateSpecializationKind() ==
6063 TSK_ImplicitInstantiation) {
6064 InstantiationClass->setTemplateSpecializationKind(
6065 TSK_ExplicitSpecialization);
6066 InstantiationClass->setLocation(Member->getLocation());
6069 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
6070 cast<CXXRecordDecl>(InstantiatedFrom),
6071 TSK_ExplicitSpecialization);
6073 assert(isa<EnumDecl>(Member) && "Only member enums remain");
6074 EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
6075 if (InstantiationEnum->getTemplateSpecializationKind() ==
6076 TSK_ImplicitInstantiation) {
6077 InstantiationEnum->setTemplateSpecializationKind(
6078 TSK_ExplicitSpecialization);
6079 InstantiationEnum->setLocation(Member->getLocation());
6082 cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
6083 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
6086 // Save the caller the trouble of having to figure out which declaration
6087 // this specialization matches.
6089 Previous.addDecl(Instantiation);
6093 /// \brief Check the scope of an explicit instantiation.
6095 /// \returns true if a serious error occurs, false otherwise.
6096 static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
6097 SourceLocation InstLoc,
6098 bool WasQualifiedName) {
6099 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
6100 DeclContext *CurContext = S.CurContext->getRedeclContext();
6102 if (CurContext->isRecord()) {
6103 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
6108 // C++11 [temp.explicit]p3:
6109 // An explicit instantiation shall appear in an enclosing namespace of its
6110 // template. If the name declared in the explicit instantiation is an
6111 // unqualified name, the explicit instantiation shall appear in the
6112 // namespace where its template is declared or, if that namespace is inline
6113 // (7.3.1), any namespace from its enclosing namespace set.
6115 // This is DR275, which we do not retroactively apply to C++98/03.
6116 if (WasQualifiedName) {
6117 if (CurContext->Encloses(OrigContext))
6120 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
6124 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
6125 if (WasQualifiedName)
6127 S.getLangOpts().CPlusPlus0x?
6128 diag::err_explicit_instantiation_out_of_scope :
6129 diag::warn_explicit_instantiation_out_of_scope_0x)
6133 S.getLangOpts().CPlusPlus0x?
6134 diag::err_explicit_instantiation_unqualified_wrong_namespace :
6135 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
6139 S.getLangOpts().CPlusPlus0x?
6140 diag::err_explicit_instantiation_must_be_global :
6141 diag::warn_explicit_instantiation_must_be_global_0x)
6143 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
6147 /// \brief Determine whether the given scope specifier has a template-id in it.
6148 static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
6152 // C++11 [temp.explicit]p3:
6153 // If the explicit instantiation is for a member function, a member class
6154 // or a static data member of a class template specialization, the name of
6155 // the class template specialization in the qualified-id for the member
6156 // name shall be a simple-template-id.
6158 // C++98 has the same restriction, just worded differently.
6159 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
6160 NNS; NNS = NNS->getPrefix())
6161 if (const Type *T = NNS->getAsType())
6162 if (isa<TemplateSpecializationType>(T))
6168 // Explicit instantiation of a class template specialization
6170 Sema::ActOnExplicitInstantiation(Scope *S,
6171 SourceLocation ExternLoc,
6172 SourceLocation TemplateLoc,
6174 SourceLocation KWLoc,
6175 const CXXScopeSpec &SS,
6176 TemplateTy TemplateD,
6177 SourceLocation TemplateNameLoc,
6178 SourceLocation LAngleLoc,
6179 ASTTemplateArgsPtr TemplateArgsIn,
6180 SourceLocation RAngleLoc,
6181 AttributeList *Attr) {
6182 // Find the class template we're specializing
6183 TemplateName Name = TemplateD.getAsVal<TemplateName>();
6184 ClassTemplateDecl *ClassTemplate
6185 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
6187 // Check that the specialization uses the same tag kind as the
6188 // original template.
6189 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6190 assert(Kind != TTK_Enum &&
6191 "Invalid enum tag in class template explicit instantiation!");
6192 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
6193 Kind, /*isDefinition*/false, KWLoc,
6194 *ClassTemplate->getIdentifier())) {
6195 Diag(KWLoc, diag::err_use_with_wrong_tag)
6197 << FixItHint::CreateReplacement(KWLoc,
6198 ClassTemplate->getTemplatedDecl()->getKindName());
6199 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
6200 diag::note_previous_use);
6201 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
6204 // C++0x [temp.explicit]p2:
6205 // There are two forms of explicit instantiation: an explicit instantiation
6206 // definition and an explicit instantiation declaration. An explicit
6207 // instantiation declaration begins with the extern keyword. [...]
6208 TemplateSpecializationKind TSK
6209 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
6210 : TSK_ExplicitInstantiationDeclaration;
6212 // Translate the parser's template argument list in our AST format.
6213 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
6214 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
6216 // Check that the template argument list is well-formed for this
6218 SmallVector<TemplateArgument, 4> Converted;
6219 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
6220 TemplateArgs, false, Converted))
6223 // Find the class template specialization declaration that
6224 // corresponds to these arguments.
6225 void *InsertPos = 0;
6226 ClassTemplateSpecializationDecl *PrevDecl
6227 = ClassTemplate->findSpecialization(Converted.data(),
6228 Converted.size(), InsertPos);
6230 TemplateSpecializationKind PrevDecl_TSK
6231 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
6233 // C++0x [temp.explicit]p2:
6234 // [...] An explicit instantiation shall appear in an enclosing
6235 // namespace of its template. [...]
6237 // This is C++ DR 275.
6238 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
6242 ClassTemplateSpecializationDecl *Specialization = 0;
6244 bool HasNoEffect = false;
6246 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
6247 PrevDecl, PrevDecl_TSK,
6248 PrevDecl->getPointOfInstantiation(),
6252 // Even though HasNoEffect == true means that this explicit instantiation
6253 // has no effect on semantics, we go on to put its syntax in the AST.
6255 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
6256 PrevDecl_TSK == TSK_Undeclared) {
6257 // Since the only prior class template specialization with these
6258 // arguments was referenced but not declared, reuse that
6259 // declaration node as our own, updating the source location
6260 // for the template name to reflect our new declaration.
6261 // (Other source locations will be updated later.)
6262 Specialization = PrevDecl;
6263 Specialization->setLocation(TemplateNameLoc);
6268 if (!Specialization) {
6269 // Create a new class template specialization declaration node for
6270 // this explicit specialization.
6272 = ClassTemplateSpecializationDecl::Create(Context, Kind,
6273 ClassTemplate->getDeclContext(),
6274 KWLoc, TemplateNameLoc,
6279 SetNestedNameSpecifier(Specialization, SS);
6281 if (!HasNoEffect && !PrevDecl) {
6282 // Insert the new specialization.
6283 ClassTemplate->AddSpecialization(Specialization, InsertPos);
6287 // Build the fully-sugared type for this explicit instantiation as
6288 // the user wrote in the explicit instantiation itself. This means
6289 // that we'll pretty-print the type retrieved from the
6290 // specialization's declaration the way that the user actually wrote
6291 // the explicit instantiation, rather than formatting the name based
6292 // on the "canonical" representation used to store the template
6293 // arguments in the specialization.
6294 TypeSourceInfo *WrittenTy
6295 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
6297 Context.getTypeDeclType(Specialization));
6298 Specialization->setTypeAsWritten(WrittenTy);
6299 TemplateArgsIn.release();
6301 // Set source locations for keywords.
6302 Specialization->setExternLoc(ExternLoc);
6303 Specialization->setTemplateKeywordLoc(TemplateLoc);
6306 ProcessDeclAttributeList(S, Specialization, Attr);
6308 // Add the explicit instantiation into its lexical context. However,
6309 // since explicit instantiations are never found by name lookup, we
6310 // just put it into the declaration context directly.
6311 Specialization->setLexicalDeclContext(CurContext);
6312 CurContext->addDecl(Specialization);
6314 // Syntax is now OK, so return if it has no other effect on semantics.
6316 // Set the template specialization kind.
6317 Specialization->setTemplateSpecializationKind(TSK);
6318 return Specialization;
6321 // C++ [temp.explicit]p3:
6322 // A definition of a class template or class member template
6323 // shall be in scope at the point of the explicit instantiation of
6324 // the class template or class member template.
6326 // This check comes when we actually try to perform the
6328 ClassTemplateSpecializationDecl *Def
6329 = cast_or_null<ClassTemplateSpecializationDecl>(
6330 Specialization->getDefinition());
6332 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
6333 else if (TSK == TSK_ExplicitInstantiationDefinition) {
6334 MarkVTableUsed(TemplateNameLoc, Specialization, true);
6335 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
6338 // Instantiate the members of this class template specialization.
6339 Def = cast_or_null<ClassTemplateSpecializationDecl>(
6340 Specialization->getDefinition());
6342 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
6344 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
6345 // TSK_ExplicitInstantiationDefinition
6346 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
6347 TSK == TSK_ExplicitInstantiationDefinition)
6348 Def->setTemplateSpecializationKind(TSK);
6350 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
6353 // Set the template specialization kind.
6354 Specialization->setTemplateSpecializationKind(TSK);
6355 return Specialization;
6358 // Explicit instantiation of a member class of a class template.
6360 Sema::ActOnExplicitInstantiation(Scope *S,
6361 SourceLocation ExternLoc,
6362 SourceLocation TemplateLoc,
6364 SourceLocation KWLoc,
6366 IdentifierInfo *Name,
6367 SourceLocation NameLoc,
6368 AttributeList *Attr) {
6371 bool IsDependent = false;
6372 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
6373 KWLoc, SS, Name, NameLoc, Attr, AS_none,
6374 /*ModulePrivateLoc=*/SourceLocation(),
6375 MultiTemplateParamsArg(*this, 0, 0),
6376 Owned, IsDependent, SourceLocation(), false,
6378 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
6383 TagDecl *Tag = cast<TagDecl>(TagD);
6384 assert(!Tag->isEnum() && "shouldn't see enumerations here");
6386 if (Tag->isInvalidDecl())
6389 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
6390 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
6392 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
6393 << Context.getTypeDeclType(Record);
6394 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
6398 // C++0x [temp.explicit]p2:
6399 // If the explicit instantiation is for a class or member class, the
6400 // elaborated-type-specifier in the declaration shall include a
6401 // simple-template-id.
6403 // C++98 has the same restriction, just worded differently.
6404 if (!ScopeSpecifierHasTemplateId(SS))
6405 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
6406 << Record << SS.getRange();
6408 // C++0x [temp.explicit]p2:
6409 // There are two forms of explicit instantiation: an explicit instantiation
6410 // definition and an explicit instantiation declaration. An explicit
6411 // instantiation declaration begins with the extern keyword. [...]
6412 TemplateSpecializationKind TSK
6413 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
6414 : TSK_ExplicitInstantiationDeclaration;
6416 // C++0x [temp.explicit]p2:
6417 // [...] An explicit instantiation shall appear in an enclosing
6418 // namespace of its template. [...]
6420 // This is C++ DR 275.
6421 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
6423 // Verify that it is okay to explicitly instantiate here.
6424 CXXRecordDecl *PrevDecl
6425 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
6426 if (!PrevDecl && Record->getDefinition())
6429 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
6430 bool HasNoEffect = false;
6431 assert(MSInfo && "No member specialization information?");
6432 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
6434 MSInfo->getTemplateSpecializationKind(),
6435 MSInfo->getPointOfInstantiation(),
6442 CXXRecordDecl *RecordDef
6443 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
6445 // C++ [temp.explicit]p3:
6446 // A definition of a member class of a class template shall be in scope
6447 // at the point of an explicit instantiation of the member class.
6449 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
6451 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
6452 << 0 << Record->getDeclName() << Record->getDeclContext();
6453 Diag(Pattern->getLocation(), diag::note_forward_declaration)
6457 if (InstantiateClass(NameLoc, Record, Def,
6458 getTemplateInstantiationArgs(Record),
6462 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
6468 // Instantiate all of the members of the class.
6469 InstantiateClassMembers(NameLoc, RecordDef,
6470 getTemplateInstantiationArgs(Record), TSK);
6472 if (TSK == TSK_ExplicitInstantiationDefinition)
6473 MarkVTableUsed(NameLoc, RecordDef, true);
6475 // FIXME: We don't have any representation for explicit instantiations of
6476 // member classes. Such a representation is not needed for compilation, but it
6477 // should be available for clients that want to see all of the declarations in
6482 DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
6483 SourceLocation ExternLoc,
6484 SourceLocation TemplateLoc,
6486 // Explicit instantiations always require a name.
6487 // TODO: check if/when DNInfo should replace Name.
6488 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6489 DeclarationName Name = NameInfo.getName();
6491 if (!D.isInvalidType())
6492 Diag(D.getDeclSpec().getLocStart(),
6493 diag::err_explicit_instantiation_requires_name)
6494 << D.getDeclSpec().getSourceRange()
6495 << D.getSourceRange();
6500 // The scope passed in may not be a decl scope. Zip up the scope tree until
6501 // we find one that is.
6502 while ((S->getFlags() & Scope::DeclScope) == 0 ||
6503 (S->getFlags() & Scope::TemplateParamScope) != 0)
6506 // Determine the type of the declaration.
6507 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
6508 QualType R = T->getType();
6513 // A storage-class-specifier shall not be specified in [...] an explicit
6514 // instantiation (14.7.2) directive.
6515 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6516 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
6519 } else if (D.getDeclSpec().getStorageClassSpec()
6520 != DeclSpec::SCS_unspecified) {
6521 // Complain about then remove the storage class specifier.
6522 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
6523 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6525 D.getMutableDeclSpec().ClearStorageClassSpecs();
6528 // C++0x [temp.explicit]p1:
6529 // [...] An explicit instantiation of a function template shall not use the
6530 // inline or constexpr specifiers.
6531 // Presumably, this also applies to member functions of class templates as
6533 if (D.getDeclSpec().isInlineSpecified())
6534 Diag(D.getDeclSpec().getInlineSpecLoc(),
6535 getLangOpts().CPlusPlus0x ?
6536 diag::err_explicit_instantiation_inline :
6537 diag::warn_explicit_instantiation_inline_0x)
6538 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6539 if (D.getDeclSpec().isConstexprSpecified())
6540 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
6541 // not already specified.
6542 Diag(D.getDeclSpec().getConstexprSpecLoc(),
6543 diag::err_explicit_instantiation_constexpr);
6545 // C++0x [temp.explicit]p2:
6546 // There are two forms of explicit instantiation: an explicit instantiation
6547 // definition and an explicit instantiation declaration. An explicit
6548 // instantiation declaration begins with the extern keyword. [...]
6549 TemplateSpecializationKind TSK
6550 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
6551 : TSK_ExplicitInstantiationDeclaration;
6553 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
6554 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
6556 if (!R->isFunctionType()) {
6557 // C++ [temp.explicit]p1:
6558 // A [...] static data member of a class template can be explicitly
6559 // instantiated from the member definition associated with its class
6561 if (Previous.isAmbiguous())
6564 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
6565 if (!Prev || !Prev->isStaticDataMember()) {
6566 // We expect to see a data data member here.
6567 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
6569 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
6571 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
6575 if (!Prev->getInstantiatedFromStaticDataMember()) {
6576 // FIXME: Check for explicit specialization?
6577 Diag(D.getIdentifierLoc(),
6578 diag::err_explicit_instantiation_data_member_not_instantiated)
6580 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
6581 // FIXME: Can we provide a note showing where this was declared?
6585 // C++0x [temp.explicit]p2:
6586 // If the explicit instantiation is for a member function, a member class
6587 // or a static data member of a class template specialization, the name of
6588 // the class template specialization in the qualified-id for the member
6589 // name shall be a simple-template-id.
6591 // C++98 has the same restriction, just worded differently.
6592 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
6593 Diag(D.getIdentifierLoc(),
6594 diag::ext_explicit_instantiation_without_qualified_id)
6595 << Prev << D.getCXXScopeSpec().getRange();
6597 // Check the scope of this explicit instantiation.
6598 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
6600 // Verify that it is okay to explicitly instantiate here.
6601 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
6602 assert(MSInfo && "Missing static data member specialization info?");
6603 bool HasNoEffect = false;
6604 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
6605 MSInfo->getTemplateSpecializationKind(),
6606 MSInfo->getPointOfInstantiation(),
6612 // Instantiate static data member.
6613 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
6614 if (TSK == TSK_ExplicitInstantiationDefinition)
6615 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev);
6617 // FIXME: Create an ExplicitInstantiation node?
6621 // If the declarator is a template-id, translate the parser's template
6622 // argument list into our AST format.
6623 bool HasExplicitTemplateArgs = false;
6624 TemplateArgumentListInfo TemplateArgs;
6625 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
6626 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
6627 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
6628 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
6629 ASTTemplateArgsPtr TemplateArgsPtr(*this,
6630 TemplateId->getTemplateArgs(),
6631 TemplateId->NumArgs);
6632 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
6633 HasExplicitTemplateArgs = true;
6634 TemplateArgsPtr.release();
6637 // C++ [temp.explicit]p1:
6638 // A [...] function [...] can be explicitly instantiated from its template.
6639 // A member function [...] of a class template can be explicitly
6640 // instantiated from the member definition associated with its class
6642 UnresolvedSet<8> Matches;
6643 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
6645 NamedDecl *Prev = *P;
6646 if (!HasExplicitTemplateArgs) {
6647 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
6648 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
6651 Matches.addDecl(Method, P.getAccess());
6652 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
6658 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
6662 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
6663 FunctionDecl *Specialization = 0;
6664 if (TemplateDeductionResult TDK
6665 = DeduceTemplateArguments(FunTmpl,
6666 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
6667 R, Specialization, Info)) {
6668 // FIXME: Keep track of almost-matches?
6673 Matches.addDecl(Specialization, P.getAccess());
6676 // Find the most specialized function template specialization.
6677 UnresolvedSetIterator Result
6678 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other, 0,
6679 D.getIdentifierLoc(),
6680 PDiag(diag::err_explicit_instantiation_not_known) << Name,
6681 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
6682 PDiag(diag::note_explicit_instantiation_candidate));
6684 if (Result == Matches.end())
6687 // Ignore access control bits, we don't need them for redeclaration checking.
6688 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
6690 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
6691 Diag(D.getIdentifierLoc(),
6692 diag::err_explicit_instantiation_member_function_not_instantiated)
6694 << (Specialization->getTemplateSpecializationKind() ==
6695 TSK_ExplicitSpecialization);
6696 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
6700 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
6701 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
6702 PrevDecl = Specialization;
6705 bool HasNoEffect = false;
6706 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
6708 PrevDecl->getTemplateSpecializationKind(),
6709 PrevDecl->getPointOfInstantiation(),
6713 // FIXME: We may still want to build some representation of this
6714 // explicit specialization.
6719 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
6720 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
6722 ProcessDeclAttributeList(S, Specialization, Attr);
6724 if (TSK == TSK_ExplicitInstantiationDefinition)
6725 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
6727 // C++0x [temp.explicit]p2:
6728 // If the explicit instantiation is for a member function, a member class
6729 // or a static data member of a class template specialization, the name of
6730 // the class template specialization in the qualified-id for the member
6731 // name shall be a simple-template-id.
6733 // C++98 has the same restriction, just worded differently.
6734 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
6735 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
6736 D.getCXXScopeSpec().isSet() &&
6737 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
6738 Diag(D.getIdentifierLoc(),
6739 diag::ext_explicit_instantiation_without_qualified_id)
6740 << Specialization << D.getCXXScopeSpec().getRange();
6742 CheckExplicitInstantiationScope(*this,
6743 FunTmpl? (NamedDecl *)FunTmpl
6744 : Specialization->getInstantiatedFromMemberFunction(),
6745 D.getIdentifierLoc(),
6746 D.getCXXScopeSpec().isSet());
6748 // FIXME: Create some kind of ExplicitInstantiationDecl here.
6753 Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
6754 const CXXScopeSpec &SS, IdentifierInfo *Name,
6755 SourceLocation TagLoc, SourceLocation NameLoc) {
6756 // This has to hold, because SS is expected to be defined.
6757 assert(Name && "Expected a name in a dependent tag");
6759 NestedNameSpecifier *NNS
6760 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6764 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6766 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
6767 Diag(NameLoc, diag::err_dependent_tag_decl)
6768 << (TUK == TUK_Definition) << Kind << SS.getRange();
6772 // Create the resulting type.
6773 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6774 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
6776 // Create type-source location information for this type.
6778 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
6779 TL.setElaboratedKeywordLoc(TagLoc);
6780 TL.setQualifierLoc(SS.getWithLocInContext(Context));
6781 TL.setNameLoc(NameLoc);
6782 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
6786 Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6787 const CXXScopeSpec &SS, const IdentifierInfo &II,
6788 SourceLocation IdLoc) {
6792 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
6794 getLangOpts().CPlusPlus0x ?
6795 diag::warn_cxx98_compat_typename_outside_of_template :
6796 diag::ext_typename_outside_of_template)
6797 << FixItHint::CreateRemoval(TypenameLoc);
6799 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
6800 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
6801 TypenameLoc, QualifierLoc, II, IdLoc);
6805 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6806 if (isa<DependentNameType>(T)) {
6807 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6808 TL.setElaboratedKeywordLoc(TypenameLoc);
6809 TL.setQualifierLoc(QualifierLoc);
6810 TL.setNameLoc(IdLoc);
6812 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
6813 TL.setElaboratedKeywordLoc(TypenameLoc);
6814 TL.setQualifierLoc(QualifierLoc);
6815 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
6818 return CreateParsedType(T, TSI);
6822 Sema::ActOnTypenameType(Scope *S,
6823 SourceLocation TypenameLoc,
6824 const CXXScopeSpec &SS,
6825 SourceLocation TemplateKWLoc,
6826 TemplateTy TemplateIn,
6827 SourceLocation TemplateNameLoc,
6828 SourceLocation LAngleLoc,
6829 ASTTemplateArgsPtr TemplateArgsIn,
6830 SourceLocation RAngleLoc) {
6831 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
6833 getLangOpts().CPlusPlus0x ?
6834 diag::warn_cxx98_compat_typename_outside_of_template :
6835 diag::ext_typename_outside_of_template)
6836 << FixItHint::CreateRemoval(TypenameLoc);
6838 // Translate the parser's template argument list in our AST format.
6839 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
6840 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
6842 TemplateName Template = TemplateIn.get();
6843 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
6844 // Construct a dependent template specialization type.
6845 assert(DTN && "dependent template has non-dependent name?");
6846 assert(DTN->getQualifier()
6847 == static_cast<NestedNameSpecifier*>(SS.getScopeRep()));
6848 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
6849 DTN->getQualifier(),
6850 DTN->getIdentifier(),
6853 // Create source-location information for this type.
6854 TypeLocBuilder Builder;
6855 DependentTemplateSpecializationTypeLoc SpecTL
6856 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
6857 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
6858 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
6859 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
6860 SpecTL.setTemplateNameLoc(TemplateNameLoc);
6861 SpecTL.setLAngleLoc(LAngleLoc);
6862 SpecTL.setRAngleLoc(RAngleLoc);
6863 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
6864 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
6865 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
6868 QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
6872 // Provide source-location information for the template specialization type.
6873 TypeLocBuilder Builder;
6874 TemplateSpecializationTypeLoc SpecTL
6875 = Builder.push<TemplateSpecializationTypeLoc>(T);
6876 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
6877 SpecTL.setTemplateNameLoc(TemplateNameLoc);
6878 SpecTL.setLAngleLoc(LAngleLoc);
6879 SpecTL.setRAngleLoc(RAngleLoc);
6880 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
6881 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
6883 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
6884 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
6885 TL.setElaboratedKeywordLoc(TypenameLoc);
6886 TL.setQualifierLoc(SS.getWithLocInContext(Context));
6888 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
6889 return CreateParsedType(T, TSI);
6893 /// \brief Build the type that describes a C++ typename specifier,
6894 /// e.g., "typename T::type".
6896 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
6897 SourceLocation KeywordLoc,
6898 NestedNameSpecifierLoc QualifierLoc,
6899 const IdentifierInfo &II,
6900 SourceLocation IILoc) {
6902 SS.Adopt(QualifierLoc);
6904 DeclContext *Ctx = computeDeclContext(SS);
6906 // If the nested-name-specifier is dependent and couldn't be
6907 // resolved to a type, build a typename type.
6908 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
6909 return Context.getDependentNameType(Keyword,
6910 QualifierLoc.getNestedNameSpecifier(),
6914 // If the nested-name-specifier refers to the current instantiation,
6915 // the "typename" keyword itself is superfluous. In C++03, the
6916 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
6917 // allows such extraneous "typename" keywords, and we retroactively
6918 // apply this DR to C++03 code with only a warning. In any case we continue.
6920 if (RequireCompleteDeclContext(SS, Ctx))
6923 DeclarationName Name(&II);
6924 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
6925 LookupQualifiedName(Result, Ctx);
6926 unsigned DiagID = 0;
6927 Decl *Referenced = 0;
6928 switch (Result.getResultKind()) {
6929 case LookupResult::NotFound:
6930 DiagID = diag::err_typename_nested_not_found;
6933 case LookupResult::FoundUnresolvedValue: {
6934 // We found a using declaration that is a value. Most likely, the using
6935 // declaration itself is meant to have the 'typename' keyword.
6936 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
6938 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
6939 << Name << Ctx << FullRange;
6940 if (UnresolvedUsingValueDecl *Using
6941 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
6942 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
6943 Diag(Loc, diag::note_using_value_decl_missing_typename)
6944 << FixItHint::CreateInsertion(Loc, "typename ");
6947 // Fall through to create a dependent typename type, from which we can recover
6950 case LookupResult::NotFoundInCurrentInstantiation:
6951 // Okay, it's a member of an unknown instantiation.
6952 return Context.getDependentNameType(Keyword,
6953 QualifierLoc.getNestedNameSpecifier(),
6956 case LookupResult::Found:
6957 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
6958 // We found a type. Build an ElaboratedType, since the
6959 // typename-specifier was just sugar.
6960 return Context.getElaboratedType(ETK_Typename,
6961 QualifierLoc.getNestedNameSpecifier(),
6962 Context.getTypeDeclType(Type));
6965 DiagID = diag::err_typename_nested_not_type;
6966 Referenced = Result.getFoundDecl();
6969 case LookupResult::FoundOverloaded:
6970 DiagID = diag::err_typename_nested_not_type;
6971 Referenced = *Result.begin();
6974 case LookupResult::Ambiguous:
6978 // If we get here, it's because name lookup did not find a
6979 // type. Emit an appropriate diagnostic and return an error.
6980 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
6982 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
6984 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
6990 // See Sema::RebuildTypeInCurrentInstantiation
6991 class CurrentInstantiationRebuilder
6992 : public TreeTransform<CurrentInstantiationRebuilder> {
6994 DeclarationName Entity;
6997 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
6999 CurrentInstantiationRebuilder(Sema &SemaRef,
7001 DeclarationName Entity)
7002 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
7003 Loc(Loc), Entity(Entity) { }
7005 /// \brief Determine whether the given type \p T has already been
7008 /// For the purposes of type reconstruction, a type has already been
7009 /// transformed if it is NULL or if it is not dependent.
7010 bool AlreadyTransformed(QualType T) {
7011 return T.isNull() || !T->isDependentType();
7014 /// \brief Returns the location of the entity whose type is being
7016 SourceLocation getBaseLocation() { return Loc; }
7018 /// \brief Returns the name of the entity whose type is being rebuilt.
7019 DeclarationName getBaseEntity() { return Entity; }
7021 /// \brief Sets the "base" location and entity when that
7022 /// information is known based on another transformation.
7023 void setBase(SourceLocation Loc, DeclarationName Entity) {
7025 this->Entity = Entity;
7028 ExprResult TransformLambdaExpr(LambdaExpr *E) {
7029 // Lambdas never need to be transformed.
7035 /// \brief Rebuilds a type within the context of the current instantiation.
7037 /// The type \p T is part of the type of an out-of-line member definition of
7038 /// a class template (or class template partial specialization) that was parsed
7039 /// and constructed before we entered the scope of the class template (or
7040 /// partial specialization thereof). This routine will rebuild that type now
7041 /// that we have entered the declarator's scope, which may produce different
7042 /// canonical types, e.g.,
7045 /// template<typename T>
7047 /// typedef T* pointer;
7051 /// template<typename T>
7052 /// typename X<T>::pointer X<T>::data() { ... }
7055 /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
7056 /// since we do not know that we can look into X<T> when we parsed the type.
7057 /// This function will rebuild the type, performing the lookup of "pointer"
7058 /// in X<T> and returning an ElaboratedType whose canonical type is the same
7059 /// as the canonical type of T*, allowing the return types of the out-of-line
7060 /// definition and the declaration to match.
7061 TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
7063 DeclarationName Name) {
7064 if (!T || !T->getType()->isDependentType())
7067 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
7068 return Rebuilder.TransformType(T);
7071 ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
7072 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
7074 return Rebuilder.TransformExpr(E);
7077 bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
7081 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
7082 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
7084 NestedNameSpecifierLoc Rebuilt
7085 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
7093 /// \brief Rebuild the template parameters now that we know we're in a current
7095 bool Sema::RebuildTemplateParamsInCurrentInstantiation(
7096 TemplateParameterList *Params) {
7097 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
7098 Decl *Param = Params->getParam(I);
7100 // There is nothing to rebuild in a type parameter.
7101 if (isa<TemplateTypeParmDecl>(Param))
7104 // Rebuild the template parameter list of a template template parameter.
7105 if (TemplateTemplateParmDecl *TTP
7106 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
7107 if (RebuildTemplateParamsInCurrentInstantiation(
7108 TTP->getTemplateParameters()))
7114 // Rebuild the type of a non-type template parameter.
7115 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
7116 TypeSourceInfo *NewTSI
7117 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
7118 NTTP->getLocation(),
7119 NTTP->getDeclName());
7123 if (NewTSI != NTTP->getTypeSourceInfo()) {
7124 NTTP->setTypeSourceInfo(NewTSI);
7125 NTTP->setType(NewTSI->getType());
7132 /// \brief Produces a formatted string that describes the binding of
7133 /// template parameters to template arguments.
7135 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
7136 const TemplateArgumentList &Args) {
7137 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
7141 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
7142 const TemplateArgument *Args,
7144 SmallString<128> Str;
7145 llvm::raw_svector_ostream Out(Str);
7147 if (!Params || Params->size() == 0 || NumArgs == 0)
7148 return std::string();
7150 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
7159 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
7160 Out << Id->getName();
7166 Args[I].print(getPrintingPolicy(), Out);
7173 void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, bool Flag) {
7176 FD->setLateTemplateParsed(Flag);
7179 bool Sema::IsInsideALocalClassWithinATemplateFunction() {
7180 DeclContext *DC = CurContext;
7183 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
7184 const FunctionDecl *FD = RD->isLocalClass();
7185 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
7186 } else if (DC->isTranslationUnit() || DC->isNamespace())
7189 DC = DC->getParent();