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 //===----------------------------------------------------------------------===/
14 #include "TreeTransform.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Expr.h"
17 #include "clang/AST/ExprCXX.h"
18 #include "clang/AST/DeclFriend.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/Parse/DeclSpec.h"
21 #include "clang/Parse/Template.h"
22 #include "clang/Basic/LangOptions.h"
23 #include "clang/Basic/PartialDiagnostic.h"
24 #include "llvm/ADT/StringExtras.h"
25 using namespace clang;
27 /// \brief Determine whether the declaration found is acceptable as the name
28 /// of a template and, if so, return that template declaration. Otherwise,
30 static NamedDecl *isAcceptableTemplateName(ASTContext &Context, NamedDecl *D) {
34 if (isa<TemplateDecl>(D))
37 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
38 // C++ [temp.local]p1:
39 // Like normal (non-template) classes, class templates have an
40 // injected-class-name (Clause 9). The injected-class-name
41 // can be used with or without a template-argument-list. When
42 // it is used without a template-argument-list, it is
43 // equivalent to the injected-class-name followed by the
44 // template-parameters of the class template enclosed in
45 // <>. When it is used with a template-argument-list, it
46 // refers to the specified class template specialization,
47 // which could be the current specialization or another
49 if (Record->isInjectedClassName()) {
50 Record = cast<CXXRecordDecl>(Record->getDeclContext());
51 if (Record->getDescribedClassTemplate())
52 return Record->getDescribedClassTemplate();
54 if (ClassTemplateSpecializationDecl *Spec
55 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
56 return Spec->getSpecializedTemplate();
65 static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) {
66 // The set of class templates we've already seen.
67 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
68 LookupResult::Filter filter = R.makeFilter();
69 while (filter.hasNext()) {
70 NamedDecl *Orig = filter.next();
71 NamedDecl *Repl = isAcceptableTemplateName(C, Orig->getUnderlyingDecl());
74 else if (Repl != Orig) {
76 // C++ [temp.local]p3:
77 // A lookup that finds an injected-class-name (10.2) can result in an
78 // ambiguity in certain cases (for example, if it is found in more than
79 // one base class). If all of the injected-class-names that are found
80 // refer to specializations of the same class template, and if the name
81 // is followed by a template-argument-list, the reference refers to the
82 // class template itself and not a specialization thereof, and is not
85 // FIXME: Will we eventually have to do the same for alias templates?
86 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
87 if (!ClassTemplates.insert(ClassTmpl)) {
98 TemplateNameKind Sema::isTemplateName(Scope *S,
101 TypeTy *ObjectTypePtr,
102 bool EnteringContext,
103 TemplateTy &TemplateResult,
104 bool &MemberOfUnknownSpecialization) {
105 assert(getLangOptions().CPlusPlus && "No template names in C!");
107 DeclarationName TName;
108 MemberOfUnknownSpecialization = false;
110 switch (Name.getKind()) {
111 case UnqualifiedId::IK_Identifier:
112 TName = DeclarationName(Name.Identifier);
115 case UnqualifiedId::IK_OperatorFunctionId:
116 TName = Context.DeclarationNames.getCXXOperatorName(
117 Name.OperatorFunctionId.Operator);
120 case UnqualifiedId::IK_LiteralOperatorId:
121 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
125 return TNK_Non_template;
128 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr);
130 LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
132 R.suppressDiagnostics();
133 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
134 MemberOfUnknownSpecialization);
135 if (R.empty() || R.isAmbiguous())
136 return TNK_Non_template;
138 TemplateName Template;
139 TemplateNameKind TemplateKind;
141 unsigned ResultCount = R.end() - R.begin();
142 if (ResultCount > 1) {
143 // We assume that we'll preserve the qualifier from a function
144 // template name in other ways.
145 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
146 TemplateKind = TNK_Function_template;
148 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
150 if (SS.isSet() && !SS.isInvalid()) {
151 NestedNameSpecifier *Qualifier
152 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
153 Template = Context.getQualifiedTemplateName(Qualifier, false, TD);
155 Template = TemplateName(TD);
158 if (isa<FunctionTemplateDecl>(TD))
159 TemplateKind = TNK_Function_template;
161 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD));
162 TemplateKind = TNK_Type_template;
166 TemplateResult = TemplateTy::make(Template);
170 bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
171 SourceLocation IILoc,
173 const CXXScopeSpec *SS,
174 TemplateTy &SuggestedTemplate,
175 TemplateNameKind &SuggestedKind) {
176 // We can't recover unless there's a dependent scope specifier preceding the
178 // FIXME: Typo correction?
179 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
180 computeDeclContext(*SS))
183 // The code is missing a 'template' keyword prior to the dependent template
185 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
186 Diag(IILoc, diag::err_template_kw_missing)
187 << Qualifier << II.getName()
188 << FixItHint::CreateInsertion(IILoc, "template ");
190 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
191 SuggestedKind = TNK_Dependent_template_name;
195 void Sema::LookupTemplateName(LookupResult &Found,
196 Scope *S, CXXScopeSpec &SS,
198 bool EnteringContext,
199 bool &MemberOfUnknownSpecialization) {
200 // Determine where to perform name lookup
201 MemberOfUnknownSpecialization = false;
202 DeclContext *LookupCtx = 0;
203 bool isDependent = false;
204 if (!ObjectType.isNull()) {
205 // This nested-name-specifier occurs in a member access expression, e.g.,
206 // x->B::f, and we are looking into the type of the object.
207 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
208 LookupCtx = computeDeclContext(ObjectType);
209 isDependent = ObjectType->isDependentType();
210 assert((isDependent || !ObjectType->isIncompleteType()) &&
211 "Caller should have completed object type");
212 } else if (SS.isSet()) {
213 // This nested-name-specifier occurs after another nested-name-specifier,
214 // so long into the context associated with the prior nested-name-specifier.
215 LookupCtx = computeDeclContext(SS, EnteringContext);
216 isDependent = isDependentScopeSpecifier(SS);
218 // The declaration context must be complete.
219 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
223 bool ObjectTypeSearchedInScope = false;
225 // Perform "qualified" name lookup into the declaration context we
226 // computed, which is either the type of the base of a member access
227 // expression or the declaration context associated with a prior
228 // nested-name-specifier.
229 LookupQualifiedName(Found, LookupCtx);
231 if (!ObjectType.isNull() && Found.empty()) {
232 // C++ [basic.lookup.classref]p1:
233 // In a class member access expression (5.2.5), if the . or -> token is
234 // immediately followed by an identifier followed by a <, the
235 // identifier must be looked up to determine whether the < is the
236 // beginning of a template argument list (14.2) or a less-than operator.
237 // The identifier is first looked up in the class of the object
238 // expression. If the identifier is not found, it is then looked up in
239 // the context of the entire postfix-expression and shall name a class
240 // or function template.
242 // FIXME: When we're instantiating a template, do we actually have to
243 // look in the scope of the template? Seems fishy...
244 if (S) LookupName(Found, S);
245 ObjectTypeSearchedInScope = true;
247 } else if (isDependent) {
248 // We cannot look into a dependent object type or nested nme
250 MemberOfUnknownSpecialization = true;
253 // Perform unqualified name lookup in the current scope.
254 LookupName(Found, S);
257 if (Found.empty() && !isDependent) {
258 // If we did not find any names, attempt to correct any typos.
259 DeclarationName Name = Found.getLookupName();
260 if (DeclarationName Corrected = CorrectTypo(Found, S, &SS, LookupCtx,
261 false, CTC_CXXCasts)) {
262 FilterAcceptableTemplateNames(Context, Found);
263 if (!Found.empty() && isa<TemplateDecl>(*Found.begin())) {
265 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
266 << Name << LookupCtx << Found.getLookupName() << SS.getRange()
267 << FixItHint::CreateReplacement(Found.getNameLoc(),
268 Found.getLookupName().getAsString());
270 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
271 << Name << Found.getLookupName()
272 << FixItHint::CreateReplacement(Found.getNameLoc(),
273 Found.getLookupName().getAsString());
274 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
275 Diag(Template->getLocation(), diag::note_previous_decl)
276 << Template->getDeclName();
284 FilterAcceptableTemplateNames(Context, Found);
288 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
289 // C++ [basic.lookup.classref]p1:
290 // [...] If the lookup in the class of the object expression finds a
291 // template, the name is also looked up in the context of the entire
292 // postfix-expression and [...]
294 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
296 LookupName(FoundOuter, S);
297 FilterAcceptableTemplateNames(Context, FoundOuter);
299 if (FoundOuter.empty()) {
300 // - if the name is not found, the name found in the class of the
301 // object expression is used, otherwise
302 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
303 // - if the name is found in the context of the entire
304 // postfix-expression and does not name a class template, the name
305 // found in the class of the object expression is used, otherwise
307 // - if the name found is a class template, it must refer to the same
308 // entity as the one found in the class of the object expression,
309 // otherwise the program is ill-formed.
310 if (!Found.isSingleResult() ||
311 Found.getFoundDecl()->getCanonicalDecl()
312 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
313 Diag(Found.getNameLoc(),
314 diag::err_nested_name_member_ref_lookup_ambiguous)
315 << Found.getLookupName();
316 Diag(Found.getRepresentativeDecl()->getLocation(),
317 diag::note_ambig_member_ref_object_type)
319 Diag(FoundOuter.getFoundDecl()->getLocation(),
320 diag::note_ambig_member_ref_scope);
322 // Recover by taking the template that we found in the object
323 // expression's type.
329 /// ActOnDependentIdExpression - Handle a dependent id-expression that
330 /// was just parsed. This is only possible with an explicit scope
331 /// specifier naming a dependent type.
332 Sema::OwningExprResult
333 Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
334 DeclarationName Name,
335 SourceLocation NameLoc,
336 bool isAddressOfOperand,
337 const TemplateArgumentListInfo *TemplateArgs) {
338 NestedNameSpecifier *Qualifier
339 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
341 DeclContext *DC = getFunctionLevelDeclContext();
343 if (!isAddressOfOperand &&
344 isa<CXXMethodDecl>(DC) &&
345 cast<CXXMethodDecl>(DC)->isInstance()) {
346 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
348 // Since the 'this' expression is synthesized, we don't need to
349 // perform the double-lookup check.
350 NamedDecl *FirstQualifierInScope = 0;
352 return Owned(CXXDependentScopeMemberExpr::Create(Context,
353 /*This*/ 0, ThisType,
355 /*Op*/ SourceLocation(),
356 Qualifier, SS.getRange(),
357 FirstQualifierInScope,
362 return BuildDependentDeclRefExpr(SS, Name, NameLoc, TemplateArgs);
365 Sema::OwningExprResult
366 Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
367 DeclarationName Name,
368 SourceLocation NameLoc,
369 const TemplateArgumentListInfo *TemplateArgs) {
370 return Owned(DependentScopeDeclRefExpr::Create(Context,
371 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
377 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
378 /// that the template parameter 'PrevDecl' is being shadowed by a new
379 /// declaration at location Loc. Returns true to indicate that this is
380 /// an error, and false otherwise.
381 bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
382 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
384 // Microsoft Visual C++ permits template parameters to be shadowed.
385 if (getLangOptions().Microsoft)
388 // C++ [temp.local]p4:
389 // A template-parameter shall not be redeclared within its
390 // scope (including nested scopes).
391 Diag(Loc, diag::err_template_param_shadow)
392 << cast<NamedDecl>(PrevDecl)->getDeclName();
393 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
397 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
398 /// the parameter D to reference the templated declaration and return a pointer
399 /// to the template declaration. Otherwise, do nothing to D and return null.
400 TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) {
401 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) {
402 D = DeclPtrTy::make(Temp->getTemplatedDecl());
408 static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
409 const ParsedTemplateArgument &Arg) {
411 switch (Arg.getKind()) {
412 case ParsedTemplateArgument::Type: {
414 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
416 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
417 return TemplateArgumentLoc(TemplateArgument(T), DI);
420 case ParsedTemplateArgument::NonType: {
421 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
422 return TemplateArgumentLoc(TemplateArgument(E), E);
425 case ParsedTemplateArgument::Template: {
426 TemplateName Template
427 = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get());
428 return TemplateArgumentLoc(TemplateArgument(Template),
429 Arg.getScopeSpec().getRange(),
434 llvm_unreachable("Unhandled parsed template argument");
435 return TemplateArgumentLoc();
438 /// \brief Translates template arguments as provided by the parser
439 /// into template arguments used by semantic analysis.
440 void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
441 TemplateArgumentListInfo &TemplateArgs) {
442 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
443 TemplateArgs.addArgument(translateTemplateArgument(*this,
447 /// ActOnTypeParameter - Called when a C++ template type parameter
448 /// (e.g., "typename T") has been parsed. Typename specifies whether
449 /// the keyword "typename" was used to declare the type parameter
450 /// (otherwise, "class" was used), and KeyLoc is the location of the
451 /// "class" or "typename" keyword. ParamName is the name of the
452 /// parameter (NULL indicates an unnamed template parameter) and
453 /// ParamName is the location of the parameter name (if any).
454 /// If the type parameter has a default argument, it will be added
455 /// later via ActOnTypeParameterDefault.
456 Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
457 SourceLocation EllipsisLoc,
458 SourceLocation KeyLoc,
459 IdentifierInfo *ParamName,
460 SourceLocation ParamNameLoc,
461 unsigned Depth, unsigned Position) {
462 assert(S->isTemplateParamScope() &&
463 "Template type parameter not in template parameter scope!");
464 bool Invalid = false;
467 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
470 if (PrevDecl && PrevDecl->isTemplateParameter())
471 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
475 SourceLocation Loc = ParamNameLoc;
479 TemplateTypeParmDecl *Param
480 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
481 Loc, Depth, Position, ParamName, Typename,
484 Param->setInvalidDecl();
487 // Add the template parameter into the current scope.
488 S->AddDecl(DeclPtrTy::make(Param));
489 IdResolver.AddDecl(Param);
492 return DeclPtrTy::make(Param);
495 /// ActOnTypeParameterDefault - Adds a default argument (the type
496 /// Default) to the given template type parameter (TypeParam).
497 void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam,
498 SourceLocation EqualLoc,
499 SourceLocation DefaultLoc,
501 TemplateTypeParmDecl *Parm
502 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>());
504 TypeSourceInfo *DefaultTInfo;
505 GetTypeFromParser(DefaultT, &DefaultTInfo);
507 assert(DefaultTInfo && "expected source information for type");
509 // C++0x [temp.param]p9:
510 // A default template-argument may be specified for any kind of
511 // template-parameter that is not a template parameter pack.
512 if (Parm->isParameterPack()) {
513 Diag(DefaultLoc, diag::err_template_param_pack_default_arg);
517 // C++ [temp.param]p14:
518 // A template-parameter shall not be used in its own default argument.
519 // FIXME: Implement this check! Needs a recursive walk over the types.
521 // Check the template argument itself.
522 if (CheckTemplateArgument(Parm, DefaultTInfo)) {
523 Parm->setInvalidDecl();
527 Parm->setDefaultArgument(DefaultTInfo, false);
530 /// \brief Check that the type of a non-type template parameter is
533 /// \returns the (possibly-promoted) parameter type if valid;
534 /// otherwise, produces a diagnostic and returns a NULL type.
536 Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
537 // We don't allow variably-modified types as the type of non-type template
539 if (T->isVariablyModifiedType()) {
540 Diag(Loc, diag::err_variably_modified_nontype_template_param)
545 // C++ [temp.param]p4:
547 // A non-type template-parameter shall have one of the following
548 // (optionally cv-qualified) types:
550 // -- integral or enumeration type,
551 if (T->isIntegralType() || T->isEnumeralType() ||
552 // -- pointer to object or pointer to function,
553 (T->isPointerType() &&
554 (T->getAs<PointerType>()->getPointeeType()->isObjectType() ||
555 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) ||
556 // -- reference to object or reference to function,
557 T->isReferenceType() ||
558 // -- pointer to member.
559 T->isMemberPointerType() ||
560 // If T is a dependent type, we can't do the check now, so we
561 // assume that it is well-formed.
562 T->isDependentType())
564 // C++ [temp.param]p8:
566 // A non-type template-parameter of type "array of T" or
567 // "function returning T" is adjusted to be of type "pointer to
568 // T" or "pointer to function returning T", respectively.
569 else if (T->isArrayType())
570 // FIXME: Keep the type prior to promotion?
571 return Context.getArrayDecayedType(T);
572 else if (T->isFunctionType())
573 // FIXME: Keep the type prior to promotion?
574 return Context.getPointerType(T);
576 Diag(Loc, diag::err_template_nontype_parm_bad_type)
582 /// ActOnNonTypeTemplateParameter - Called when a C++ non-type
583 /// template parameter (e.g., "int Size" in "template<int Size>
584 /// class Array") has been parsed. S is the current scope and D is
585 /// the parsed declarator.
586 Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
589 TypeSourceInfo *TInfo = 0;
590 QualType T = GetTypeForDeclarator(D, S, &TInfo);
592 assert(S->isTemplateParamScope() &&
593 "Non-type template parameter not in template parameter scope!");
594 bool Invalid = false;
596 IdentifierInfo *ParamName = D.getIdentifier();
598 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
601 if (PrevDecl && PrevDecl->isTemplateParameter())
602 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
606 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
608 T = Context.IntTy; // Recover with an 'int' type.
612 NonTypeTemplateParmDecl *Param
613 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
614 D.getIdentifierLoc(),
615 Depth, Position, ParamName, T, TInfo);
617 Param->setInvalidDecl();
619 if (D.getIdentifier()) {
620 // Add the template parameter into the current scope.
621 S->AddDecl(DeclPtrTy::make(Param));
622 IdResolver.AddDecl(Param);
624 return DeclPtrTy::make(Param);
627 /// \brief Adds a default argument to the given non-type template
629 void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD,
630 SourceLocation EqualLoc,
632 NonTypeTemplateParmDecl *TemplateParm
633 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>());
634 Expr *Default = static_cast<Expr *>(DefaultE.get());
636 // C++ [temp.param]p14:
637 // A template-parameter shall not be used in its own default argument.
638 // FIXME: Implement this check! Needs a recursive walk over the types.
640 // Check the well-formedness of the default template argument.
641 TemplateArgument Converted;
642 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default,
644 TemplateParm->setInvalidDecl();
648 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>());
652 /// ActOnTemplateTemplateParameter - Called when a C++ template template
653 /// parameter (e.g. T in template <template <typename> class T> class array)
654 /// has been parsed. S is the current scope.
655 Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S,
656 SourceLocation TmpLoc,
657 TemplateParamsTy *Params,
658 IdentifierInfo *Name,
659 SourceLocation NameLoc,
662 assert(S->isTemplateParamScope() &&
663 "Template template parameter not in template parameter scope!");
665 // Construct the parameter object.
666 TemplateTemplateParmDecl *Param =
667 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
668 TmpLoc, Depth, Position, Name,
669 (TemplateParameterList*)Params);
671 // Make sure the parameter is valid.
672 // FIXME: Decl object is not currently invalidated anywhere so this doesn't
673 // do anything yet. However, if the template parameter list or (eventual)
674 // default value is ever invalidated, that will propagate here.
675 bool Invalid = false;
677 Param->setInvalidDecl();
680 // If the tt-param has a name, then link the identifier into the scope
681 // and lookup mechanisms.
683 S->AddDecl(DeclPtrTy::make(Param));
684 IdResolver.AddDecl(Param);
687 return DeclPtrTy::make(Param);
690 /// \brief Adds a default argument to the given template template
692 void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD,
693 SourceLocation EqualLoc,
694 const ParsedTemplateArgument &Default) {
695 TemplateTemplateParmDecl *TemplateParm
696 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>());
698 // C++ [temp.param]p14:
699 // A template-parameter shall not be used in its own default argument.
700 // FIXME: Implement this check! Needs a recursive walk over the types.
702 // Check only that we have a template template argument. We don't want to
703 // try to check well-formedness now, because our template template parameter
704 // might have dependent types in its template parameters, which we wouldn't
705 // be able to match now.
707 // If none of the template template parameter's template arguments mention
708 // other template parameters, we could actually perform more checking here.
709 // However, it isn't worth doing.
710 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
711 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
712 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
713 << DefaultArg.getSourceRange();
717 TemplateParm->setDefaultArgument(DefaultArg);
720 /// ActOnTemplateParameterList - Builds a TemplateParameterList that
721 /// contains the template parameters in Params/NumParams.
722 Sema::TemplateParamsTy *
723 Sema::ActOnTemplateParameterList(unsigned Depth,
724 SourceLocation ExportLoc,
725 SourceLocation TemplateLoc,
726 SourceLocation LAngleLoc,
727 DeclPtrTy *Params, unsigned NumParams,
728 SourceLocation RAngleLoc) {
729 if (ExportLoc.isValid())
730 Diag(ExportLoc, diag::warn_template_export_unsupported);
732 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
733 (NamedDecl**)Params, NumParams,
737 static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
739 T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
744 Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
745 SourceLocation KWLoc, CXXScopeSpec &SS,
746 IdentifierInfo *Name, SourceLocation NameLoc,
748 TemplateParameterList *TemplateParams,
749 AccessSpecifier AS) {
750 assert(TemplateParams && TemplateParams->size() > 0 &&
751 "No template parameters");
752 assert(TUK != TUK_Reference && "Can only declare or define class templates");
753 bool Invalid = false;
755 // Check that we can declare a template here.
756 if (CheckTemplateDeclScope(S, TemplateParams))
759 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
760 assert(Kind != TTK_Enum && "can't build template of enumerated type");
762 // There is no such thing as an unnamed class template.
764 Diag(KWLoc, diag::err_template_unnamed_class);
768 // Find any previous declaration with this name.
769 DeclContext *SemanticContext;
770 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
772 if (SS.isNotEmpty() && !SS.isInvalid()) {
773 SemanticContext = computeDeclContext(SS, true);
774 if (!SemanticContext) {
775 // FIXME: Produce a reasonable diagnostic here
779 if (RequireCompleteDeclContext(SS, SemanticContext))
782 LookupQualifiedName(Previous, SemanticContext);
784 SemanticContext = CurContext;
785 LookupName(Previous, S);
788 if (Previous.isAmbiguous())
791 NamedDecl *PrevDecl = 0;
792 if (Previous.begin() != Previous.end())
793 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
795 // If there is a previous declaration with the same name, check
796 // whether this is a valid redeclaration.
797 ClassTemplateDecl *PrevClassTemplate
798 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
800 // We may have found the injected-class-name of a class template,
801 // class template partial specialization, or class template specialization.
802 // In these cases, grab the template that is being defined or specialized.
803 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
804 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
805 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
807 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
808 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
810 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
811 ->getSpecializedTemplate();
815 if (TUK == TUK_Friend) {
816 // C++ [namespace.memdef]p3:
817 // [...] When looking for a prior declaration of a class or a function
818 // declared as a friend, and when the name of the friend class or
819 // function is neither a qualified name nor a template-id, scopes outside
820 // the innermost enclosing namespace scope are not considered.
822 DeclContext *OutermostContext = CurContext;
823 while (!OutermostContext->isFileContext())
824 OutermostContext = OutermostContext->getLookupParent();
827 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
828 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
829 SemanticContext = PrevDecl->getDeclContext();
831 // Declarations in outer scopes don't matter. However, the outermost
832 // context we computed is the semantic context for our new
834 PrevDecl = PrevClassTemplate = 0;
835 SemanticContext = OutermostContext;
839 if (CurContext->isDependentContext()) {
840 // If this is a dependent context, we don't want to link the friend
841 // class template to the template in scope, because that would perform
842 // checking of the template parameter lists that can't be performed
843 // until the outer context is instantiated.
844 PrevDecl = PrevClassTemplate = 0;
846 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
847 PrevDecl = PrevClassTemplate = 0;
849 if (PrevClassTemplate) {
850 // Ensure that the template parameter lists are compatible.
851 if (!TemplateParameterListsAreEqual(TemplateParams,
852 PrevClassTemplate->getTemplateParameters(),
857 // C++ [temp.class]p4:
858 // In a redeclaration, partial specialization, explicit
859 // specialization or explicit instantiation of a class template,
860 // the class-key shall agree in kind with the original class
861 // template declaration (7.1.5.3).
862 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
863 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
864 Diag(KWLoc, diag::err_use_with_wrong_tag)
866 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
867 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
868 Kind = PrevRecordDecl->getTagKind();
871 // Check for redefinition of this class template.
872 if (TUK == TUK_Definition) {
873 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
874 Diag(NameLoc, diag::err_redefinition) << Name;
875 Diag(Def->getLocation(), diag::note_previous_definition);
876 // FIXME: Would it make sense to try to "forget" the previous
877 // definition, as part of error recovery?
881 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
882 // Maybe we will complain about the shadowed template parameter.
883 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
884 // Just pretend that we didn't see the previous declaration.
886 } else if (PrevDecl) {
888 // A class template shall not have the same name as any other
889 // template, class, function, object, enumeration, enumerator,
890 // namespace, or type in the same scope (3.3), except as specified
892 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
893 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
897 // Check the template parameter list of this declaration, possibly
898 // merging in the template parameter list from the previous class
899 // template declaration.
900 if (CheckTemplateParameterList(TemplateParams,
901 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
906 // If the name of the template was qualified, we must be defining the
907 // template out-of-line.
908 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
909 !(TUK == TUK_Friend && CurContext->isDependentContext()))
910 Diag(NameLoc, diag::err_member_def_does_not_match)
911 << Name << SemanticContext << SS.getRange();
914 CXXRecordDecl *NewClass =
915 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
917 PrevClassTemplate->getTemplatedDecl() : 0,
918 /*DelayTypeCreation=*/true);
919 SetNestedNameSpecifier(NewClass, SS);
921 ClassTemplateDecl *NewTemplate
922 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
923 DeclarationName(Name), TemplateParams,
924 NewClass, PrevClassTemplate);
925 NewClass->setDescribedClassTemplate(NewTemplate);
927 // Build the type for the class template declaration now.
928 QualType T = NewTemplate->getInjectedClassNameSpecialization(Context);
929 T = Context.getInjectedClassNameType(NewClass, T);
930 assert(T->isDependentType() && "Class template type is not dependent?");
933 // If we are providing an explicit specialization of a member that is a
934 // class template, make a note of that.
935 if (PrevClassTemplate &&
936 PrevClassTemplate->getInstantiatedFromMemberTemplate())
937 PrevClassTemplate->setMemberSpecialization();
939 // Set the access specifier.
940 if (!Invalid && TUK != TUK_Friend)
941 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
943 // Set the lexical context of these templates
944 NewClass->setLexicalDeclContext(CurContext);
945 NewTemplate->setLexicalDeclContext(CurContext);
947 if (TUK == TUK_Definition)
948 NewClass->startDefinition();
951 ProcessDeclAttributeList(S, NewClass, Attr);
953 if (TUK != TUK_Friend)
954 PushOnScopeChains(NewTemplate, S);
956 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
957 NewTemplate->setAccess(PrevClassTemplate->getAccess());
958 NewClass->setAccess(PrevClassTemplate->getAccess());
961 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
962 PrevClassTemplate != NULL);
964 // Friend templates are visible in fairly strange ways.
965 if (!CurContext->isDependentContext()) {
966 DeclContext *DC = SemanticContext->getLookupContext();
967 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
968 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
969 PushOnScopeChains(NewTemplate, EnclosingScope,
970 /* AddToContext = */ false);
973 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
974 NewClass->getLocation(),
976 /*FIXME:*/NewClass->getLocation());
977 Friend->setAccess(AS_public);
978 CurContext->addDecl(Friend);
982 NewTemplate->setInvalidDecl();
983 NewClass->setInvalidDecl();
985 return DeclPtrTy::make(NewTemplate);
988 /// \brief Diagnose the presence of a default template argument on a
989 /// template parameter, which is ill-formed in certain contexts.
991 /// \returns true if the default template argument should be dropped.
992 static bool DiagnoseDefaultTemplateArgument(Sema &S,
993 Sema::TemplateParamListContext TPC,
994 SourceLocation ParamLoc,
995 SourceRange DefArgRange) {
997 case Sema::TPC_ClassTemplate:
1000 case Sema::TPC_FunctionTemplate:
1001 // C++ [temp.param]p9:
1002 // A default template-argument shall not be specified in a
1003 // function template declaration or a function template
1005 // (This sentence is not in C++0x, per DR226).
1006 if (!S.getLangOptions().CPlusPlus0x)
1008 diag::err_template_parameter_default_in_function_template)
1012 case Sema::TPC_ClassTemplateMember:
1013 // C++0x [temp.param]p9:
1014 // A default template-argument shall not be specified in the
1015 // template-parameter-lists of the definition of a member of a
1016 // class template that appears outside of the member's class.
1017 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1021 case Sema::TPC_FriendFunctionTemplate:
1022 // C++ [temp.param]p9:
1023 // A default template-argument shall not be specified in a
1024 // friend template declaration.
1025 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1029 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1030 // for friend function templates if there is only a single
1031 // declaration (and it is a definition). Strange!
1037 /// \brief Checks the validity of a template parameter list, possibly
1038 /// considering the template parameter list from a previous
1041 /// If an "old" template parameter list is provided, it must be
1042 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
1043 /// template parameter list.
1045 /// \param NewParams Template parameter list for a new template
1046 /// declaration. This template parameter list will be updated with any
1047 /// default arguments that are carried through from the previous
1048 /// template parameter list.
1050 /// \param OldParams If provided, template parameter list from a
1051 /// previous declaration of the same template. Default template
1052 /// arguments will be merged from the old template parameter list to
1053 /// the new template parameter list.
1055 /// \param TPC Describes the context in which we are checking the given
1056 /// template parameter list.
1058 /// \returns true if an error occurred, false otherwise.
1059 bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
1060 TemplateParameterList *OldParams,
1061 TemplateParamListContext TPC) {
1062 bool Invalid = false;
1064 // C++ [temp.param]p10:
1065 // The set of default template-arguments available for use with a
1066 // template declaration or definition is obtained by merging the
1067 // default arguments from the definition (if in scope) and all
1068 // declarations in scope in the same way default function
1069 // arguments are (8.3.6).
1070 bool SawDefaultArgument = false;
1071 SourceLocation PreviousDefaultArgLoc;
1073 bool SawParameterPack = false;
1074 SourceLocation ParameterPackLoc;
1076 // Dummy initialization to avoid warnings.
1077 TemplateParameterList::iterator OldParam = NewParams->end();
1079 OldParam = OldParams->begin();
1081 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1082 NewParamEnd = NewParams->end();
1083 NewParam != NewParamEnd; ++NewParam) {
1084 // Variables used to diagnose redundant default arguments
1085 bool RedundantDefaultArg = false;
1086 SourceLocation OldDefaultLoc;
1087 SourceLocation NewDefaultLoc;
1089 // Variables used to diagnose missing default arguments
1090 bool MissingDefaultArg = false;
1092 // C++0x [temp.param]p11:
1093 // If a template parameter of a class template is a template parameter pack,
1094 // it must be the last template parameter.
1095 if (SawParameterPack) {
1096 Diag(ParameterPackLoc,
1097 diag::err_template_param_pack_must_be_last_template_parameter);
1101 if (TemplateTypeParmDecl *NewTypeParm
1102 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
1103 // Check the presence of a default argument here.
1104 if (NewTypeParm->hasDefaultArgument() &&
1105 DiagnoseDefaultTemplateArgument(*this, TPC,
1106 NewTypeParm->getLocation(),
1107 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1109 NewTypeParm->removeDefaultArgument();
1111 // Merge default arguments for template type parameters.
1112 TemplateTypeParmDecl *OldTypeParm
1113 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
1115 if (NewTypeParm->isParameterPack()) {
1116 assert(!NewTypeParm->hasDefaultArgument() &&
1117 "Parameter packs can't have a default argument!");
1118 SawParameterPack = true;
1119 ParameterPackLoc = NewTypeParm->getLocation();
1120 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
1121 NewTypeParm->hasDefaultArgument()) {
1122 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1123 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1124 SawDefaultArgument = true;
1125 RedundantDefaultArg = true;
1126 PreviousDefaultArgLoc = NewDefaultLoc;
1127 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1128 // Merge the default argument from the old declaration to the
1130 SawDefaultArgument = true;
1131 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
1133 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1134 } else if (NewTypeParm->hasDefaultArgument()) {
1135 SawDefaultArgument = true;
1136 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1137 } else if (SawDefaultArgument)
1138 MissingDefaultArg = true;
1139 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
1140 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
1141 // Check the presence of a default argument here.
1142 if (NewNonTypeParm->hasDefaultArgument() &&
1143 DiagnoseDefaultTemplateArgument(*this, TPC,
1144 NewNonTypeParm->getLocation(),
1145 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1146 NewNonTypeParm->getDefaultArgument()->Destroy(Context);
1147 NewNonTypeParm->setDefaultArgument(0);
1150 // Merge default arguments for non-type template parameters
1151 NonTypeTemplateParmDecl *OldNonTypeParm
1152 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
1153 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
1154 NewNonTypeParm->hasDefaultArgument()) {
1155 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1156 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1157 SawDefaultArgument = true;
1158 RedundantDefaultArg = true;
1159 PreviousDefaultArgLoc = NewDefaultLoc;
1160 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1161 // Merge the default argument from the old declaration to the
1163 SawDefaultArgument = true;
1164 // FIXME: We need to create a new kind of "default argument"
1165 // expression that points to a previous template template
1167 NewNonTypeParm->setDefaultArgument(
1168 OldNonTypeParm->getDefaultArgument());
1169 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1170 } else if (NewNonTypeParm->hasDefaultArgument()) {
1171 SawDefaultArgument = true;
1172 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1173 } else if (SawDefaultArgument)
1174 MissingDefaultArg = true;
1176 // Check the presence of a default argument here.
1177 TemplateTemplateParmDecl *NewTemplateParm
1178 = cast<TemplateTemplateParmDecl>(*NewParam);
1179 if (NewTemplateParm->hasDefaultArgument() &&
1180 DiagnoseDefaultTemplateArgument(*this, TPC,
1181 NewTemplateParm->getLocation(),
1182 NewTemplateParm->getDefaultArgument().getSourceRange()))
1183 NewTemplateParm->setDefaultArgument(TemplateArgumentLoc());
1185 // Merge default arguments for template template parameters
1186 TemplateTemplateParmDecl *OldTemplateParm
1187 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
1188 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
1189 NewTemplateParm->hasDefaultArgument()) {
1190 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1191 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
1192 SawDefaultArgument = true;
1193 RedundantDefaultArg = true;
1194 PreviousDefaultArgLoc = NewDefaultLoc;
1195 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1196 // Merge the default argument from the old declaration to the
1198 SawDefaultArgument = true;
1199 // FIXME: We need to create a new kind of "default argument" expression
1200 // that points to a previous template template parameter.
1201 NewTemplateParm->setDefaultArgument(
1202 OldTemplateParm->getDefaultArgument());
1203 PreviousDefaultArgLoc
1204 = OldTemplateParm->getDefaultArgument().getLocation();
1205 } else if (NewTemplateParm->hasDefaultArgument()) {
1206 SawDefaultArgument = true;
1207 PreviousDefaultArgLoc
1208 = NewTemplateParm->getDefaultArgument().getLocation();
1209 } else if (SawDefaultArgument)
1210 MissingDefaultArg = true;
1213 if (RedundantDefaultArg) {
1214 // C++ [temp.param]p12:
1215 // A template-parameter shall not be given default arguments
1216 // by two different declarations in the same scope.
1217 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1218 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1220 } else if (MissingDefaultArg) {
1221 // C++ [temp.param]p11:
1222 // If a template-parameter has a default template-argument,
1223 // all subsequent template-parameters shall have a default
1224 // template-argument supplied.
1225 Diag((*NewParam)->getLocation(),
1226 diag::err_template_param_default_arg_missing);
1227 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1231 // If we have an old template parameter list that we're merging
1232 // in, move on to the next parameter.
1240 /// \brief Match the given template parameter lists to the given scope
1241 /// specifier, returning the template parameter list that applies to the
1244 /// \param DeclStartLoc the start of the declaration that has a scope
1245 /// specifier or a template parameter list.
1247 /// \param SS the scope specifier that will be matched to the given template
1248 /// parameter lists. This scope specifier precedes a qualified name that is
1251 /// \param ParamLists the template parameter lists, from the outermost to the
1252 /// innermost template parameter lists.
1254 /// \param NumParamLists the number of template parameter lists in ParamLists.
1256 /// \param IsFriend Whether to apply the slightly different rules for
1257 /// matching template parameters to scope specifiers in friend
1260 /// \param IsExplicitSpecialization will be set true if the entity being
1261 /// declared is an explicit specialization, false otherwise.
1263 /// \returns the template parameter list, if any, that corresponds to the
1264 /// name that is preceded by the scope specifier @p SS. This template
1265 /// parameter list may be have template parameters (if we're declaring a
1266 /// template) or may have no template parameters (if we're declaring a
1267 /// template specialization), or may be NULL (if we were's declaring isn't
1268 /// itself a template).
1269 TemplateParameterList *
1270 Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1271 const CXXScopeSpec &SS,
1272 TemplateParameterList **ParamLists,
1273 unsigned NumParamLists,
1275 bool &IsExplicitSpecialization) {
1276 IsExplicitSpecialization = false;
1278 // Find the template-ids that occur within the nested-name-specifier. These
1279 // template-ids will match up with the template parameter lists.
1280 llvm::SmallVector<const TemplateSpecializationType *, 4>
1281 TemplateIdsInSpecifier;
1282 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1283 ExplicitSpecializationsInSpecifier;
1284 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1285 NNS; NNS = NNS->getPrefix()) {
1286 const Type *T = NNS->getAsType();
1289 // C++0x [temp.expl.spec]p17:
1290 // A member or a member template may be nested within many
1291 // enclosing class templates. In an explicit specialization for
1292 // such a member, the member declaration shall be preceded by a
1293 // template<> for each enclosing class template that is
1294 // explicitly specialized.
1296 // Following the existing practice of GNU and EDG, we allow a typedef of a
1297 // template specialization type.
1298 if (const TypedefType *TT = dyn_cast<TypedefType>(T))
1299 T = TT->LookThroughTypedefs().getTypePtr();
1301 if (const TemplateSpecializationType *SpecType
1302 = dyn_cast<TemplateSpecializationType>(T)) {
1303 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1305 continue; // FIXME: should this be an error? probably...
1307 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
1308 ClassTemplateSpecializationDecl *SpecDecl
1309 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1310 // If the nested name specifier refers to an explicit specialization,
1311 // we don't need a template<> header.
1312 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1313 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
1318 TemplateIdsInSpecifier.push_back(SpecType);
1322 // Reverse the list of template-ids in the scope specifier, so that we can
1323 // more easily match up the template-ids and the template parameter lists.
1324 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
1326 SourceLocation FirstTemplateLoc = DeclStartLoc;
1328 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
1330 // Match the template-ids found in the specifier to the template parameter
1333 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1334 Idx != NumTemplateIds; ++Idx) {
1335 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0);
1336 bool DependentTemplateId = TemplateId->isDependentType();
1337 if (Idx >= NumParamLists) {
1338 // We have a template-id without a corresponding template parameter
1341 // ...which is fine if this is a friend declaration.
1343 IsExplicitSpecialization = true;
1347 if (DependentTemplateId) {
1348 // FIXME: the location information here isn't great.
1349 Diag(SS.getRange().getBegin(),
1350 diag::err_template_spec_needs_template_parameters)
1354 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1356 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
1357 IsExplicitSpecialization = true;
1362 // Check the template parameter list against its corresponding template-id.
1363 if (DependentTemplateId) {
1364 TemplateParameterList *ExpectedTemplateParams = 0;
1366 // Are there cases in (e.g.) friends where this won't match?
1367 if (const InjectedClassNameType *Injected
1368 = TemplateId->getAs<InjectedClassNameType>()) {
1369 CXXRecordDecl *Record = Injected->getDecl();
1370 if (ClassTemplatePartialSpecializationDecl *Partial =
1371 dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
1372 ExpectedTemplateParams = Partial->getTemplateParameters();
1374 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1375 ->getTemplateParameters();
1378 if (ExpectedTemplateParams)
1379 TemplateParameterListsAreEqual(ParamLists[Idx],
1380 ExpectedTemplateParams,
1381 true, TPL_TemplateMatch);
1383 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember);
1384 } else if (ParamLists[Idx]->size() > 0)
1385 Diag(ParamLists[Idx]->getTemplateLoc(),
1386 diag::err_template_param_list_matches_nontemplate)
1388 << ParamLists[Idx]->getSourceRange();
1390 IsExplicitSpecialization = true;
1393 // If there were at least as many template-ids as there were template
1394 // parameter lists, then there are no template parameter lists remaining for
1395 // the declaration itself.
1396 if (Idx >= NumParamLists)
1399 // If there were too many template parameter lists, complain about that now.
1400 if (Idx != NumParamLists - 1) {
1401 while (Idx < NumParamLists - 1) {
1402 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0;
1403 Diag(ParamLists[Idx]->getTemplateLoc(),
1404 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1405 : diag::err_template_spec_extra_headers)
1406 << SourceRange(ParamLists[Idx]->getTemplateLoc(),
1407 ParamLists[Idx]->getRAngleLoc());
1409 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1410 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1411 diag::note_explicit_template_spec_does_not_need_header)
1412 << ExplicitSpecializationsInSpecifier.back();
1413 ExplicitSpecializationsInSpecifier.pop_back();
1420 // Return the last template parameter list, which corresponds to the
1421 // entity being declared.
1422 return ParamLists[NumParamLists - 1];
1425 QualType Sema::CheckTemplateIdType(TemplateName Name,
1426 SourceLocation TemplateLoc,
1427 const TemplateArgumentListInfo &TemplateArgs) {
1428 TemplateDecl *Template = Name.getAsTemplateDecl();
1430 // The template name does not resolve to a template, so we just
1431 // build a dependent template-id type.
1432 return Context.getTemplateSpecializationType(Name, TemplateArgs);
1435 // Check that the template argument list is well-formed for this
1437 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(),
1438 TemplateArgs.size());
1439 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
1443 assert((Converted.structuredSize() ==
1444 Template->getTemplateParameters()->size()) &&
1445 "Converted template argument list is too short!");
1448 bool IsCurrentInstantiation = false;
1450 if (Name.isDependent() ||
1451 TemplateSpecializationType::anyDependentTemplateArguments(
1453 // This class template specialization is a dependent
1454 // type. Therefore, its canonical type is another class template
1455 // specialization type that contains all of the converted
1456 // arguments in canonical form. This ensures that, e.g., A<T> and
1457 // A<T, T> have identical types when A is declared as:
1459 // template<typename T, typename U = T> struct A;
1460 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
1461 CanonType = Context.getTemplateSpecializationType(CanonName,
1462 Converted.getFlatArguments(),
1463 Converted.flatSize());
1465 // FIXME: CanonType is not actually the canonical type, and unfortunately
1466 // it is a TemplateSpecializationType that we will never use again.
1467 // In the future, we need to teach getTemplateSpecializationType to only
1468 // build the canonical type and return that to us.
1469 CanonType = Context.getCanonicalType(CanonType);
1471 // This might work out to be a current instantiation, in which
1472 // case the canonical type needs to be the InjectedClassNameType.
1474 // TODO: in theory this could be a simple hashtable lookup; most
1475 // changes to CurContext don't change the set of current
1477 if (isa<ClassTemplateDecl>(Template)) {
1478 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1479 // If we get out to a namespace, we're done.
1480 if (Ctx->isFileContext()) break;
1482 // If this isn't a record, keep looking.
1483 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
1484 if (!Record) continue;
1486 // Look for one of the two cases with InjectedClassNameTypes
1487 // and check whether it's the same template.
1488 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
1489 !Record->getDescribedClassTemplate())
1492 // Fetch the injected class name type and check whether its
1493 // injected type is equal to the type we just built.
1494 QualType ICNT = Context.getTypeDeclType(Record);
1495 QualType Injected = cast<InjectedClassNameType>(ICNT)
1496 ->getInjectedSpecializationType();
1498 if (CanonType != Injected->getCanonicalTypeInternal())
1501 // If so, the canonical type of this TST is the injected
1502 // class name type of the record we just found.
1503 assert(ICNT.isCanonical());
1505 IsCurrentInstantiation = true;
1509 } else if (ClassTemplateDecl *ClassTemplate
1510 = dyn_cast<ClassTemplateDecl>(Template)) {
1511 // Find the class template specialization declaration that
1512 // corresponds to these arguments.
1513 llvm::FoldingSetNodeID ID;
1514 ClassTemplateSpecializationDecl::Profile(ID,
1515 Converted.getFlatArguments(),
1516 Converted.flatSize(),
1518 void *InsertPos = 0;
1519 ClassTemplateSpecializationDecl *Decl
1520 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
1522 // This is the first time we have referenced this class template
1523 // specialization. Create the canonical declaration and add it to
1524 // the set of specializations.
1525 Decl = ClassTemplateSpecializationDecl::Create(Context,
1526 ClassTemplate->getTemplatedDecl()->getTagKind(),
1527 ClassTemplate->getDeclContext(),
1528 ClassTemplate->getLocation(),
1531 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos);
1532 Decl->setLexicalDeclContext(CurContext);
1535 CanonType = Context.getTypeDeclType(Decl);
1536 assert(isa<RecordType>(CanonType) &&
1537 "type of non-dependent specialization is not a RecordType");
1540 // Build the fully-sugared type for this class template
1541 // specialization, which refers back to the class template
1542 // specialization we created or found.
1543 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType,
1544 IsCurrentInstantiation);
1548 Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
1549 SourceLocation LAngleLoc,
1550 ASTTemplateArgsPtr TemplateArgsIn,
1551 SourceLocation RAngleLoc) {
1552 TemplateName Template = TemplateD.getAsVal<TemplateName>();
1554 // Translate the parser's template argument list in our AST format.
1555 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
1556 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
1558 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
1559 TemplateArgsIn.release();
1561 if (Result.isNull())
1564 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
1565 TemplateSpecializationTypeLoc TL
1566 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1567 TL.setTemplateNameLoc(TemplateLoc);
1568 TL.setLAngleLoc(LAngleLoc);
1569 TL.setRAngleLoc(RAngleLoc);
1570 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1571 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1573 return CreateLocInfoType(Result, DI).getAsOpaquePtr();
1576 Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult,
1578 DeclSpec::TST TagSpec,
1579 SourceLocation TagLoc) {
1580 if (TypeResult.isInvalid())
1581 return Sema::TypeResult();
1583 // FIXME: preserve source info, ideally without copying the DI.
1585 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
1587 // Verify the tag specifier.
1588 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1590 if (const RecordType *RT = Type->getAs<RecordType>()) {
1591 RecordDecl *D = RT->getDecl();
1593 IdentifierInfo *Id = D->getIdentifier();
1594 assert(Id && "templated class must have an identifier");
1596 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1597 Diag(TagLoc, diag::err_use_with_wrong_tag)
1599 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
1600 Diag(D->getLocation(), diag::note_previous_use);
1604 ElaboratedTypeKeyword Keyword
1605 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
1606 QualType ElabType = Context.getElaboratedType(Keyword, /*NNS=*/0, Type);
1608 return ElabType.getAsOpaquePtr();
1611 Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1614 const TemplateArgumentListInfo &TemplateArgs) {
1615 // FIXME: Can we do any checking at this point? I guess we could check the
1616 // template arguments that we have against the template name, if the template
1617 // name refers to a single template. That's not a terribly common case,
1620 // These should be filtered out by our callers.
1621 assert(!R.empty() && "empty lookup results when building templateid");
1622 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1624 NestedNameSpecifier *Qualifier = 0;
1625 SourceRange QualifierRange;
1627 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1628 QualifierRange = SS.getRange();
1631 // We don't want lookup warnings at this point.
1632 R.suppressDiagnostics();
1635 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(),
1637 UnresolvedLookupExpr *ULE
1638 = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
1639 Qualifier, QualifierRange,
1640 R.getLookupName(), R.getNameLoc(),
1641 RequiresADL, TemplateArgs,
1642 R.begin(), R.end());
1647 // We actually only call this from template instantiation.
1648 Sema::OwningExprResult
1649 Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
1650 DeclarationName Name,
1651 SourceLocation NameLoc,
1652 const TemplateArgumentListInfo &TemplateArgs) {
1654 if (!(DC = computeDeclContext(SS, false)) ||
1655 DC->isDependentContext() ||
1656 RequireCompleteDeclContext(SS, DC))
1657 return BuildDependentDeclRefExpr(SS, Name, NameLoc, &TemplateArgs);
1659 bool MemberOfUnknownSpecialization;
1660 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1661 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
1662 MemberOfUnknownSpecialization);
1664 if (R.isAmbiguous())
1668 Diag(NameLoc, diag::err_template_kw_refers_to_non_template)
1669 << Name << SS.getRange();
1673 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
1674 Diag(NameLoc, diag::err_template_kw_refers_to_class_template)
1675 << (NestedNameSpecifier*) SS.getScopeRep() << Name << SS.getRange();
1676 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1680 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
1683 /// \brief Form a dependent template name.
1685 /// This action forms a dependent template name given the template
1686 /// name and its (presumably dependent) scope specifier. For
1687 /// example, given "MetaFun::template apply", the scope specifier \p
1688 /// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1689 /// of the "template" keyword, and "apply" is the \p Name.
1691 Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc,
1693 UnqualifiedId &Name,
1695 bool EnteringContext) {
1696 DeclContext *LookupCtx = 0;
1698 LookupCtx = computeDeclContext(SS, EnteringContext);
1699 if (!LookupCtx && ObjectType)
1700 LookupCtx = computeDeclContext(QualType::getFromOpaquePtr(ObjectType));
1702 // C++0x [temp.names]p5:
1703 // If a name prefixed by the keyword template is not the name of
1704 // a template, the program is ill-formed. [Note: the keyword
1705 // template may not be applied to non-template members of class
1706 // templates. -end note ] [ Note: as is the case with the
1707 // typename prefix, the template prefix is allowed in cases
1708 // where it is not strictly necessary; i.e., when the
1709 // nested-name-specifier or the expression on the left of the ->
1710 // or . is not dependent on a template-parameter, or the use
1711 // does not appear in the scope of a template. -end note]
1713 // Note: C++03 was more strict here, because it banned the use of
1714 // the "template" keyword prior to a template-name that was not a
1715 // dependent name. C++ DR468 relaxed this requirement (the
1716 // "template" keyword is now permitted). We follow the C++0x
1717 // rules, even in C++03 mode, retroactively applying the DR.
1718 TemplateTy Template;
1719 bool MemberOfUnknownSpecialization;
1720 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType,
1721 EnteringContext, Template,
1722 MemberOfUnknownSpecialization);
1723 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1724 isa<CXXRecordDecl>(LookupCtx) &&
1725 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
1726 // This is a dependent template.
1727 } else if (TNK == TNK_Non_template) {
1728 Diag(Name.getSourceRange().getBegin(),
1729 diag::err_template_kw_refers_to_non_template)
1730 << GetNameFromUnqualifiedId(Name)
1731 << Name.getSourceRange()
1733 return TemplateTy();
1735 // We found something; return it.
1740 NestedNameSpecifier *Qualifier
1741 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
1743 switch (Name.getKind()) {
1744 case UnqualifiedId::IK_Identifier:
1745 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1748 case UnqualifiedId::IK_OperatorFunctionId:
1749 return TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1750 Name.OperatorFunctionId.Operator));
1752 case UnqualifiedId::IK_LiteralOperatorId:
1753 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1759 Diag(Name.getSourceRange().getBegin(),
1760 diag::err_template_kw_refers_to_non_template)
1761 << GetNameFromUnqualifiedId(Name)
1762 << Name.getSourceRange()
1764 return TemplateTy();
1767 bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
1768 const TemplateArgumentLoc &AL,
1769 TemplateArgumentListBuilder &Converted) {
1770 const TemplateArgument &Arg = AL.getArgument();
1772 // Check template type parameter.
1773 switch(Arg.getKind()) {
1774 case TemplateArgument::Type:
1775 // C++ [temp.arg.type]p1:
1776 // A template-argument for a template-parameter which is a
1777 // type shall be a type-id.
1779 case TemplateArgument::Template: {
1780 // We have a template type parameter but the template argument
1781 // is a template without any arguments.
1782 SourceRange SR = AL.getSourceRange();
1783 TemplateName Name = Arg.getAsTemplate();
1784 Diag(SR.getBegin(), diag::err_template_missing_args)
1786 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1787 Diag(Decl->getLocation(), diag::note_template_decl_here);
1792 // We have a template type parameter but the template argument
1794 SourceRange SR = AL.getSourceRange();
1795 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
1796 Diag(Param->getLocation(), diag::note_template_param_here);
1802 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
1805 // Add the converted template type argument.
1807 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
1811 /// \brief Substitute template arguments into the default template argument for
1812 /// the given template type parameter.
1814 /// \param SemaRef the semantic analysis object for which we are performing
1815 /// the substitution.
1817 /// \param Template the template that we are synthesizing template arguments
1820 /// \param TemplateLoc the location of the template name that started the
1821 /// template-id we are checking.
1823 /// \param RAngleLoc the location of the right angle bracket ('>') that
1824 /// terminates the template-id.
1826 /// \param Param the template template parameter whose default we are
1827 /// substituting into.
1829 /// \param Converted the list of template arguments provided for template
1830 /// parameters that precede \p Param in the template parameter list.
1832 /// \returns the substituted template argument, or NULL if an error occurred.
1833 static TypeSourceInfo *
1834 SubstDefaultTemplateArgument(Sema &SemaRef,
1835 TemplateDecl *Template,
1836 SourceLocation TemplateLoc,
1837 SourceLocation RAngleLoc,
1838 TemplateTypeParmDecl *Param,
1839 TemplateArgumentListBuilder &Converted) {
1840 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
1842 // If the argument type is dependent, instantiate it now based
1843 // on the previously-computed template arguments.
1844 if (ArgType->getType()->isDependentType()) {
1845 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1846 /*TakeArgs=*/false);
1848 MultiLevelTemplateArgumentList AllTemplateArgs
1849 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1851 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1852 Template, Converted.getFlatArguments(),
1853 Converted.flatSize(),
1854 SourceRange(TemplateLoc, RAngleLoc));
1856 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
1857 Param->getDefaultArgumentLoc(),
1858 Param->getDeclName());
1864 /// \brief Substitute template arguments into the default template argument for
1865 /// the given non-type template parameter.
1867 /// \param SemaRef the semantic analysis object for which we are performing
1868 /// the substitution.
1870 /// \param Template the template that we are synthesizing template arguments
1873 /// \param TemplateLoc the location of the template name that started the
1874 /// template-id we are checking.
1876 /// \param RAngleLoc the location of the right angle bracket ('>') that
1877 /// terminates the template-id.
1879 /// \param Param the non-type template parameter whose default we are
1880 /// substituting into.
1882 /// \param Converted the list of template arguments provided for template
1883 /// parameters that precede \p Param in the template parameter list.
1885 /// \returns the substituted template argument, or NULL if an error occurred.
1886 static Sema::OwningExprResult
1887 SubstDefaultTemplateArgument(Sema &SemaRef,
1888 TemplateDecl *Template,
1889 SourceLocation TemplateLoc,
1890 SourceLocation RAngleLoc,
1891 NonTypeTemplateParmDecl *Param,
1892 TemplateArgumentListBuilder &Converted) {
1893 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1894 /*TakeArgs=*/false);
1896 MultiLevelTemplateArgumentList AllTemplateArgs
1897 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1899 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1900 Template, Converted.getFlatArguments(),
1901 Converted.flatSize(),
1902 SourceRange(TemplateLoc, RAngleLoc));
1904 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
1907 /// \brief Substitute template arguments into the default template argument for
1908 /// the given template template parameter.
1910 /// \param SemaRef the semantic analysis object for which we are performing
1911 /// the substitution.
1913 /// \param Template the template that we are synthesizing template arguments
1916 /// \param TemplateLoc the location of the template name that started the
1917 /// template-id we are checking.
1919 /// \param RAngleLoc the location of the right angle bracket ('>') that
1920 /// terminates the template-id.
1922 /// \param Param the template template parameter whose default we are
1923 /// substituting into.
1925 /// \param Converted the list of template arguments provided for template
1926 /// parameters that precede \p Param in the template parameter list.
1928 /// \returns the substituted template argument, or NULL if an error occurred.
1930 SubstDefaultTemplateArgument(Sema &SemaRef,
1931 TemplateDecl *Template,
1932 SourceLocation TemplateLoc,
1933 SourceLocation RAngleLoc,
1934 TemplateTemplateParmDecl *Param,
1935 TemplateArgumentListBuilder &Converted) {
1936 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted,
1937 /*TakeArgs=*/false);
1939 MultiLevelTemplateArgumentList AllTemplateArgs
1940 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
1942 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
1943 Template, Converted.getFlatArguments(),
1944 Converted.flatSize(),
1945 SourceRange(TemplateLoc, RAngleLoc));
1947 return SemaRef.SubstTemplateName(
1948 Param->getDefaultArgument().getArgument().getAsTemplate(),
1949 Param->getDefaultArgument().getTemplateNameLoc(),
1953 /// \brief If the given template parameter has a default template
1954 /// argument, substitute into that default template argument and
1955 /// return the corresponding template argument.
1957 Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
1958 SourceLocation TemplateLoc,
1959 SourceLocation RAngleLoc,
1961 TemplateArgumentListBuilder &Converted) {
1962 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
1963 if (!TypeParm->hasDefaultArgument())
1964 return TemplateArgumentLoc();
1966 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
1972 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
1974 return TemplateArgumentLoc();
1977 if (NonTypeTemplateParmDecl *NonTypeParm
1978 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
1979 if (!NonTypeParm->hasDefaultArgument())
1980 return TemplateArgumentLoc();
1982 OwningExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
1987 if (Arg.isInvalid())
1988 return TemplateArgumentLoc();
1990 Expr *ArgE = Arg.takeAs<Expr>();
1991 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
1994 TemplateTemplateParmDecl *TempTempParm
1995 = cast<TemplateTemplateParmDecl>(Param);
1996 if (!TempTempParm->hasDefaultArgument())
1997 return TemplateArgumentLoc();
1999 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
2005 return TemplateArgumentLoc();
2007 return TemplateArgumentLoc(TemplateArgument(TName),
2008 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
2009 TempTempParm->getDefaultArgument().getTemplateNameLoc());
2012 /// \brief Check that the given template argument corresponds to the given
2013 /// template parameter.
2014 bool Sema::CheckTemplateArgument(NamedDecl *Param,
2015 const TemplateArgumentLoc &Arg,
2016 TemplateDecl *Template,
2017 SourceLocation TemplateLoc,
2018 SourceLocation RAngleLoc,
2019 TemplateArgumentListBuilder &Converted,
2020 CheckTemplateArgumentKind CTAK) {
2021 // Check template type parameters.
2022 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2023 return CheckTemplateTypeArgument(TTP, Arg, Converted);
2025 // Check non-type template parameters.
2026 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2027 // Do substitution on the type of the non-type template parameter
2028 // with the template arguments we've seen thus far.
2029 QualType NTTPType = NTTP->getType();
2030 if (NTTPType->isDependentType()) {
2031 // Do substitution on the type of the non-type template parameter.
2032 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2033 NTTP, Converted.getFlatArguments(),
2034 Converted.flatSize(),
2035 SourceRange(TemplateLoc, RAngleLoc));
2037 TemplateArgumentList TemplateArgs(Context, Converted,
2038 /*TakeArgs=*/false);
2039 NTTPType = SubstType(NTTPType,
2040 MultiLevelTemplateArgumentList(TemplateArgs),
2041 NTTP->getLocation(),
2042 NTTP->getDeclName());
2043 // If that worked, check the non-type template parameter type
2045 if (!NTTPType.isNull())
2046 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2047 NTTP->getLocation());
2048 if (NTTPType.isNull())
2052 switch (Arg.getArgument().getKind()) {
2053 case TemplateArgument::Null:
2054 assert(false && "Should never see a NULL template argument here");
2057 case TemplateArgument::Expression: {
2058 Expr *E = Arg.getArgument().getAsExpr();
2059 TemplateArgument Result;
2060 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
2063 Converted.Append(Result);
2067 case TemplateArgument::Declaration:
2068 case TemplateArgument::Integral:
2069 // We've already checked this template argument, so just copy
2070 // it to the list of converted arguments.
2071 Converted.Append(Arg.getArgument());
2074 case TemplateArgument::Template:
2075 // We were given a template template argument. It may not be ill-formed;
2077 if (DependentTemplateName *DTN
2078 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) {
2079 // We have a template argument such as \c T::template X, which we
2080 // parsed as a template template argument. However, since we now
2081 // know that we need a non-type template argument, convert this
2082 // template name into an expression.
2083 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2084 DTN->getQualifier(),
2085 Arg.getTemplateQualifierRange(),
2086 DTN->getIdentifier(),
2087 Arg.getTemplateNameLoc());
2089 TemplateArgument Result;
2090 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2093 Converted.Append(Result);
2097 // We have a template argument that actually does refer to a class
2098 // template, template alias, or template template parameter, and
2099 // therefore cannot be a non-type template argument.
2100 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2101 << Arg.getSourceRange();
2103 Diag(Param->getLocation(), diag::note_template_param_here);
2106 case TemplateArgument::Type: {
2107 // We have a non-type template parameter but the template
2108 // argument is a type.
2110 // C++ [temp.arg]p2:
2111 // In a template-argument, an ambiguity between a type-id and
2112 // an expression is resolved to a type-id, regardless of the
2113 // form of the corresponding template-parameter.
2115 // We warn specifically about this case, since it can be rather
2116 // confusing for users.
2117 QualType T = Arg.getArgument().getAsType();
2118 SourceRange SR = Arg.getSourceRange();
2119 if (T->isFunctionType())
2120 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2122 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2123 Diag(Param->getLocation(), diag::note_template_param_here);
2127 case TemplateArgument::Pack:
2128 llvm_unreachable("Caller must expand template argument packs");
2136 // Check template template parameters.
2137 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2139 // Substitute into the template parameter list of the template
2140 // template parameter, since previously-supplied template arguments
2141 // may appear within the template template parameter.
2143 // Set up a template instantiation context.
2144 LocalInstantiationScope Scope(*this);
2145 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2146 TempParm, Converted.getFlatArguments(),
2147 Converted.flatSize(),
2148 SourceRange(TemplateLoc, RAngleLoc));
2150 TemplateArgumentList TemplateArgs(Context, Converted,
2151 /*TakeArgs=*/false);
2152 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2153 SubstDecl(TempParm, CurContext,
2154 MultiLevelTemplateArgumentList(TemplateArgs)));
2158 // FIXME: TempParam is leaked.
2161 switch (Arg.getArgument().getKind()) {
2162 case TemplateArgument::Null:
2163 assert(false && "Should never see a NULL template argument here");
2166 case TemplateArgument::Template:
2167 if (CheckTemplateArgument(TempParm, Arg))
2170 Converted.Append(Arg.getArgument());
2173 case TemplateArgument::Expression:
2174 case TemplateArgument::Type:
2175 // We have a template template parameter but the template
2176 // argument does not refer to a template.
2177 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2180 case TemplateArgument::Declaration:
2182 "Declaration argument with template template parameter");
2184 case TemplateArgument::Integral:
2186 "Integral argument with template template parameter");
2189 case TemplateArgument::Pack:
2190 llvm_unreachable("Caller must expand template argument packs");
2197 /// \brief Check that the given template argument list is well-formed
2198 /// for specializing the given template.
2199 bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2200 SourceLocation TemplateLoc,
2201 const TemplateArgumentListInfo &TemplateArgs,
2202 bool PartialTemplateArgs,
2203 TemplateArgumentListBuilder &Converted) {
2204 TemplateParameterList *Params = Template->getTemplateParameters();
2205 unsigned NumParams = Params->size();
2206 unsigned NumArgs = TemplateArgs.size();
2207 bool Invalid = false;
2209 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2211 bool HasParameterPack =
2212 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
2214 if ((NumArgs > NumParams && !HasParameterPack) ||
2215 (NumArgs < Params->getMinRequiredArguments() &&
2216 !PartialTemplateArgs)) {
2217 // FIXME: point at either the first arg beyond what we can handle,
2218 // or the '>', depending on whether we have too many or too few
2221 if (NumArgs > NumParams)
2222 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
2223 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2224 << (NumArgs > NumParams)
2225 << (isa<ClassTemplateDecl>(Template)? 0 :
2226 isa<FunctionTemplateDecl>(Template)? 1 :
2227 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2228 << Template << Range;
2229 Diag(Template->getLocation(), diag::note_template_decl_here)
2230 << Params->getSourceRange();
2234 // C++ [temp.arg]p1:
2235 // [...] The type and form of each template-argument specified in
2236 // a template-id shall match the type and form specified for the
2237 // corresponding parameter declared by the template in its
2238 // template-parameter-list.
2239 unsigned ArgIdx = 0;
2240 for (TemplateParameterList::iterator Param = Params->begin(),
2241 ParamEnd = Params->end();
2242 Param != ParamEnd; ++Param, ++ArgIdx) {
2243 if (ArgIdx > NumArgs && PartialTemplateArgs)
2246 // If we have a template parameter pack, check every remaining template
2247 // argument against that template parameter pack.
2248 if ((*Param)->isTemplateParameterPack()) {
2249 Converted.BeginPack();
2250 for (; ArgIdx < NumArgs; ++ArgIdx) {
2251 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2252 TemplateLoc, RAngleLoc, Converted)) {
2257 Converted.EndPack();
2261 if (ArgIdx < NumArgs) {
2262 // Check the template argument we were given.
2263 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2264 TemplateLoc, RAngleLoc, Converted))
2270 // We have a default template argument that we will use.
2271 TemplateArgumentLoc Arg;
2273 // Retrieve the default template argument from the template
2274 // parameter. For each kind of template parameter, we substitute the
2275 // template arguments provided thus far and any "outer" template arguments
2276 // (when the template parameter was part of a nested template) into
2277 // the default argument.
2278 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2279 if (!TTP->hasDefaultArgument()) {
2280 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2284 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
2293 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2295 } else if (NonTypeTemplateParmDecl *NTTP
2296 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2297 if (!NTTP->hasDefaultArgument()) {
2298 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2302 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template,
2310 Expr *Ex = E.takeAs<Expr>();
2311 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2313 TemplateTemplateParmDecl *TempParm
2314 = cast<TemplateTemplateParmDecl>(*Param);
2316 if (!TempParm->hasDefaultArgument()) {
2317 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2321 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2329 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2330 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2331 TempParm->getDefaultArgument().getTemplateNameLoc());
2334 // Introduce an instantiation record that describes where we are using
2335 // the default template argument.
2336 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2337 Converted.getFlatArguments(),
2338 Converted.flatSize(),
2339 SourceRange(TemplateLoc, RAngleLoc));
2341 // Check the default template argument.
2342 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
2343 RAngleLoc, Converted))
2350 /// \brief Check a template argument against its corresponding
2351 /// template type parameter.
2353 /// This routine implements the semantics of C++ [temp.arg.type]. It
2354 /// returns true if an error occurred, and false otherwise.
2355 bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
2356 TypeSourceInfo *ArgInfo) {
2357 assert(ArgInfo && "invalid TypeSourceInfo");
2358 QualType Arg = ArgInfo->getType();
2360 // C++ [temp.arg.type]p2:
2361 // A local type, a type with no linkage, an unnamed type or a type
2362 // compounded from any of these types shall not be used as a
2363 // template-argument for a template type-parameter.
2365 // FIXME: Perform the unnamed type check.
2366 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
2367 const TagType *Tag = 0;
2368 if (const EnumType *EnumT = Arg->getAs<EnumType>())
2370 else if (const RecordType *RecordT = Arg->getAs<RecordType>())
2372 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) {
2373 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
2374 return Diag(SR.getBegin(), diag::err_template_arg_local_type)
2375 << QualType(Tag, 0) << SR;
2376 } else if (Tag && !Tag->getDecl()->getDeclName() &&
2377 !Tag->getDecl()->getTypedefForAnonDecl()) {
2378 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR;
2379 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here);
2381 } else if (Arg->isVariablyModifiedType()) {
2382 Diag(SR.getBegin(), diag::err_variably_modified_template_arg)
2385 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
2386 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
2392 /// \brief Checks whether the given template argument is the address
2393 /// of an object or function according to C++ [temp.arg.nontype]p1.
2395 CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2396 NonTypeTemplateParmDecl *Param,
2399 TemplateArgument &Converted) {
2400 bool Invalid = false;
2402 QualType ArgType = Arg->getType();
2404 // See through any implicit casts we added to fix the type.
2405 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
2406 Arg = Cast->getSubExpr();
2408 // C++ [temp.arg.nontype]p1:
2410 // A template-argument for a non-type, non-template
2411 // template-parameter shall be one of: [...]
2413 // -- the address of an object or function with external
2414 // linkage, including function templates and function
2415 // template-ids but excluding non-static class members,
2416 // expressed as & id-expression where the & is optional if
2417 // the name refers to a function or array, or if the
2418 // corresponding template-parameter is a reference; or
2419 DeclRefExpr *DRE = 0;
2421 // Ignore (and complain about) any excess parentheses.
2422 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2424 S.Diag(Arg->getSourceRange().getBegin(),
2425 diag::err_template_arg_extra_parens)
2426 << Arg->getSourceRange();
2430 Arg = Parens->getSubExpr();
2433 bool AddressTaken = false;
2434 SourceLocation AddrOpLoc;
2435 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
2436 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2437 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2438 AddressTaken = true;
2439 AddrOpLoc = UnOp->getOperatorLoc();
2442 DRE = dyn_cast<DeclRefExpr>(Arg);
2445 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2446 << Arg->getSourceRange();
2447 S.Diag(Param->getLocation(), diag::note_template_param_here);
2451 // Stop checking the precise nature of the argument if it is value dependent,
2452 // it should be checked when instantiated.
2453 if (Arg->isValueDependent()) {
2454 Converted = TemplateArgument(ArgIn->Retain());
2458 if (!isa<ValueDecl>(DRE->getDecl())) {
2459 S.Diag(Arg->getSourceRange().getBegin(),
2460 diag::err_template_arg_not_object_or_func_form)
2461 << Arg->getSourceRange();
2462 S.Diag(Param->getLocation(), diag::note_template_param_here);
2466 NamedDecl *Entity = 0;
2468 // Cannot refer to non-static data members
2469 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2470 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
2471 << Field << Arg->getSourceRange();
2472 S.Diag(Param->getLocation(), diag::note_template_param_here);
2476 // Cannot refer to non-static member functions
2477 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
2478 if (!Method->isStatic()) {
2479 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
2480 << Method << Arg->getSourceRange();
2481 S.Diag(Param->getLocation(), diag::note_template_param_here);
2485 // Functions must have external linkage.
2486 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
2487 if (!isExternalLinkage(Func->getLinkage())) {
2488 S.Diag(Arg->getSourceRange().getBegin(),
2489 diag::err_template_arg_function_not_extern)
2490 << Func << Arg->getSourceRange();
2491 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
2496 // Okay: we've named a function with external linkage.
2499 // If the template parameter has pointer type, the function decays.
2500 if (ParamType->isPointerType() && !AddressTaken)
2501 ArgType = S.Context.getPointerType(Func->getType());
2502 else if (AddressTaken && ParamType->isReferenceType()) {
2503 // If we originally had an address-of operator, but the
2504 // parameter has reference type, complain and (if things look
2505 // like they will work) drop the address-of operator.
2506 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
2507 ParamType.getNonReferenceType())) {
2508 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2510 S.Diag(Param->getLocation(), diag::note_template_param_here);
2514 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2516 << FixItHint::CreateRemoval(AddrOpLoc);
2517 S.Diag(Param->getLocation(), diag::note_template_param_here);
2519 ArgType = Func->getType();
2521 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
2522 if (!isExternalLinkage(Var->getLinkage())) {
2523 S.Diag(Arg->getSourceRange().getBegin(),
2524 diag::err_template_arg_object_not_extern)
2525 << Var << Arg->getSourceRange();
2526 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
2531 // A value of reference type is not an object.
2532 if (Var->getType()->isReferenceType()) {
2533 S.Diag(Arg->getSourceRange().getBegin(),
2534 diag::err_template_arg_reference_var)
2535 << Var->getType() << Arg->getSourceRange();
2536 S.Diag(Param->getLocation(), diag::note_template_param_here);
2540 // Okay: we've named an object with external linkage
2543 // If the template parameter has pointer type, we must have taken
2544 // the address of this object.
2545 if (ParamType->isReferenceType()) {
2547 // If we originally had an address-of operator, but the
2548 // parameter has reference type, complain and (if things look
2549 // like they will work) drop the address-of operator.
2550 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
2551 ParamType.getNonReferenceType())) {
2552 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2554 S.Diag(Param->getLocation(), diag::note_template_param_here);
2558 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
2560 << FixItHint::CreateRemoval(AddrOpLoc);
2561 S.Diag(Param->getLocation(), diag::note_template_param_here);
2563 ArgType = Var->getType();
2565 } else if (!AddressTaken && ParamType->isPointerType()) {
2566 if (Var->getType()->isArrayType()) {
2567 // Array-to-pointer decay.
2568 ArgType = S.Context.getArrayDecayedType(Var->getType());
2570 // If the template parameter has pointer type but the address of
2571 // this object was not taken, complain and (possibly) recover by
2572 // taking the address of the entity.
2573 ArgType = S.Context.getPointerType(Var->getType());
2574 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
2575 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2577 S.Diag(Param->getLocation(), diag::note_template_param_here);
2581 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
2583 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
2585 S.Diag(Param->getLocation(), diag::note_template_param_here);
2589 // We found something else, but we don't know specifically what it is.
2590 S.Diag(Arg->getSourceRange().getBegin(),
2591 diag::err_template_arg_not_object_or_func)
2592 << Arg->getSourceRange();
2593 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
2597 if (ParamType->isPointerType() &&
2598 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
2599 S.IsQualificationConversion(ArgType, ParamType)) {
2600 // For pointer-to-object types, qualification conversions are
2603 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
2604 if (!ParamRef->getPointeeType()->isFunctionType()) {
2605 // C++ [temp.arg.nontype]p5b3:
2606 // For a non-type template-parameter of type reference to
2607 // object, no conversions apply. The type referred to by the
2608 // reference may be more cv-qualified than the (otherwise
2609 // identical) type of the template- argument. The
2610 // template-parameter is bound directly to the
2611 // template-argument, which shall be an lvalue.
2613 // FIXME: Other qualifiers?
2614 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
2615 unsigned ArgQuals = ArgType.getCVRQualifiers();
2617 if ((ParamQuals | ArgQuals) != ParamQuals) {
2618 S.Diag(Arg->getSourceRange().getBegin(),
2619 diag::err_template_arg_ref_bind_ignores_quals)
2620 << ParamType << Arg->getType()
2621 << Arg->getSourceRange();
2622 S.Diag(Param->getLocation(), diag::note_template_param_here);
2628 // At this point, the template argument refers to an object or
2629 // function with external linkage. We now need to check whether the
2630 // argument and parameter types are compatible.
2631 if (!S.Context.hasSameUnqualifiedType(ArgType,
2632 ParamType.getNonReferenceType())) {
2633 // We can't perform this conversion or binding.
2634 if (ParamType->isReferenceType())
2635 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
2636 << ParamType << Arg->getType() << Arg->getSourceRange();
2638 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
2639 << Arg->getType() << ParamType << Arg->getSourceRange();
2640 S.Diag(Param->getLocation(), diag::note_template_param_here);
2645 // Create the template argument.
2646 Converted = TemplateArgument(Entity->getCanonicalDecl());
2647 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
2651 /// \brief Checks whether the given template argument is a pointer to
2652 /// member constant according to C++ [temp.arg.nontype]p1.
2653 bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
2654 TemplateArgument &Converted) {
2655 bool Invalid = false;
2657 // See through any implicit casts we added to fix the type.
2658 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
2659 Arg = Cast->getSubExpr();
2661 // C++ [temp.arg.nontype]p1:
2663 // A template-argument for a non-type, non-template
2664 // template-parameter shall be one of: [...]
2666 // -- a pointer to member expressed as described in 5.3.1.
2667 DeclRefExpr *DRE = 0;
2669 // Ignore (and complain about) any excess parentheses.
2670 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2672 Diag(Arg->getSourceRange().getBegin(),
2673 diag::err_template_arg_extra_parens)
2674 << Arg->getSourceRange();
2678 Arg = Parens->getSubExpr();
2681 // A pointer-to-member constant written &Class::member.
2682 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
2683 if (UnOp->getOpcode() == UnaryOperator::AddrOf) {
2684 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2685 if (DRE && !DRE->getQualifier())
2689 // A constant of pointer-to-member type.
2690 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
2691 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
2692 if (VD->getType()->isMemberPointerType()) {
2693 if (isa<NonTypeTemplateParmDecl>(VD) ||
2694 (isa<VarDecl>(VD) &&
2695 Context.getCanonicalType(VD->getType()).isConstQualified())) {
2696 if (Arg->isTypeDependent() || Arg->isValueDependent())
2697 Converted = TemplateArgument(Arg->Retain());
2699 Converted = TemplateArgument(VD->getCanonicalDecl());
2709 return Diag(Arg->getSourceRange().getBegin(),
2710 diag::err_template_arg_not_pointer_to_member_form)
2711 << Arg->getSourceRange();
2713 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
2714 assert((isa<FieldDecl>(DRE->getDecl()) ||
2715 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
2716 "Only non-static member pointers can make it here");
2718 // Okay: this is the address of a non-static member, and therefore
2719 // a member pointer constant.
2720 if (Arg->isTypeDependent() || Arg->isValueDependent())
2721 Converted = TemplateArgument(Arg->Retain());
2723 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
2727 // We found something else, but we don't know specifically what it is.
2728 Diag(Arg->getSourceRange().getBegin(),
2729 diag::err_template_arg_not_pointer_to_member_form)
2730 << Arg->getSourceRange();
2731 Diag(DRE->getDecl()->getLocation(),
2732 diag::note_template_arg_refers_here);
2736 /// \brief Check a template argument against its corresponding
2737 /// non-type template parameter.
2739 /// This routine implements the semantics of C++ [temp.arg.nontype].
2740 /// It returns true if an error occurred, and false otherwise. \p
2741 /// InstantiatedParamType is the type of the non-type template
2742 /// parameter after it has been instantiated.
2744 /// If no error was detected, Converted receives the converted template argument.
2745 bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
2746 QualType InstantiatedParamType, Expr *&Arg,
2747 TemplateArgument &Converted,
2748 CheckTemplateArgumentKind CTAK) {
2749 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
2751 // If either the parameter has a dependent type or the argument is
2752 // type-dependent, there's nothing we can check now.
2753 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
2754 // FIXME: Produce a cloned, canonical expression?
2755 Converted = TemplateArgument(Arg);
2759 // C++ [temp.arg.nontype]p5:
2760 // The following conversions are performed on each expression used
2761 // as a non-type template-argument. If a non-type
2762 // template-argument cannot be converted to the type of the
2763 // corresponding template-parameter then the program is
2766 // -- for a non-type template-parameter of integral or
2767 // enumeration type, integral promotions (4.5) and integral
2768 // conversions (4.7) are applied.
2769 QualType ParamType = InstantiatedParamType;
2770 QualType ArgType = Arg->getType();
2771 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) {
2772 // C++ [temp.arg.nontype]p1:
2773 // A template-argument for a non-type, non-template
2774 // template-parameter shall be one of:
2776 // -- an integral constant-expression of integral or enumeration
2778 // -- the name of a non-type template-parameter; or
2779 SourceLocation NonConstantLoc;
2781 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) {
2782 Diag(Arg->getSourceRange().getBegin(),
2783 diag::err_template_arg_not_integral_or_enumeral)
2784 << ArgType << Arg->getSourceRange();
2785 Diag(Param->getLocation(), diag::note_template_param_here);
2787 } else if (!Arg->isValueDependent() &&
2788 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
2789 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
2790 << ArgType << Arg->getSourceRange();
2794 // From here on out, all we care about are the unqualified forms
2795 // of the parameter and argument types.
2796 ParamType = ParamType.getUnqualifiedType();
2797 ArgType = ArgType.getUnqualifiedType();
2799 // Try to convert the argument to the parameter's type.
2800 if (Context.hasSameType(ParamType, ArgType)) {
2801 // Okay: no conversion necessary
2802 } else if (CTAK == CTAK_Deduced) {
2803 // C++ [temp.deduct.type]p17:
2804 // If, in the declaration of a function template with a non-type
2805 // template-parameter, the non-type template- parameter is used
2806 // in an expression in the function parameter-list and, if the
2807 // corresponding template-argument is deduced, the
2808 // template-argument type shall match the type of the
2809 // template-parameter exactly, except that a template-argument
2810 // deduced from an array bound may be of any integral type.
2811 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
2812 << ArgType << ParamType;
2813 Diag(Param->getLocation(), diag::note_template_param_here);
2815 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
2816 !ParamType->isEnumeralType()) {
2817 // This is an integral promotion or conversion.
2818 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast);
2820 // We can't perform this conversion.
2821 Diag(Arg->getSourceRange().getBegin(),
2822 diag::err_template_arg_not_convertible)
2823 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
2824 Diag(Param->getLocation(), diag::note_template_param_here);
2828 QualType IntegerType = Context.getCanonicalType(ParamType);
2829 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
2830 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
2832 if (!Arg->isValueDependent()) {
2833 llvm::APSInt OldValue = Value;
2835 // Coerce the template argument's value to the value it will have
2836 // based on the template parameter's type.
2837 unsigned AllowedBits = Context.getTypeSize(IntegerType);
2838 if (Value.getBitWidth() != AllowedBits)
2839 Value.extOrTrunc(AllowedBits);
2840 Value.setIsSigned(IntegerType->isSignedIntegerType());
2842 // Complain if an unsigned parameter received a negative value.
2843 if (IntegerType->isUnsignedIntegerType()
2844 && (OldValue.isSigned() && OldValue.isNegative())) {
2845 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
2846 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2847 << Arg->getSourceRange();
2848 Diag(Param->getLocation(), diag::note_template_param_here);
2851 // Complain if we overflowed the template parameter's type.
2852 unsigned RequiredBits;
2853 if (IntegerType->isUnsignedIntegerType())
2854 RequiredBits = OldValue.getActiveBits();
2855 else if (OldValue.isUnsigned())
2856 RequiredBits = OldValue.getActiveBits() + 1;
2858 RequiredBits = OldValue.getMinSignedBits();
2859 if (RequiredBits > AllowedBits) {
2860 Diag(Arg->getSourceRange().getBegin(),
2861 diag::warn_template_arg_too_large)
2862 << OldValue.toString(10) << Value.toString(10) << Param->getType()
2863 << Arg->getSourceRange();
2864 Diag(Param->getLocation(), diag::note_template_param_here);
2868 // Add the value of this argument to the list of converted
2869 // arguments. We use the bitwidth and signedness of the template
2871 if (Arg->isValueDependent()) {
2872 // The argument is value-dependent. Create a new
2873 // TemplateArgument with the converted expression.
2874 Converted = TemplateArgument(Arg);
2878 Converted = TemplateArgument(Value,
2879 ParamType->isEnumeralType() ? ParamType
2884 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
2886 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
2887 // from a template argument of type std::nullptr_t to a non-type
2888 // template parameter of type pointer to object, pointer to
2889 // function, or pointer-to-member, respectively.
2890 if (ArgType->isNullPtrType() &&
2891 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
2892 Converted = TemplateArgument((NamedDecl *)0);
2896 // Handle pointer-to-function, reference-to-function, and
2897 // pointer-to-member-function all in (roughly) the same way.
2898 if (// -- For a non-type template-parameter of type pointer to
2899 // function, only the function-to-pointer conversion (4.3) is
2900 // applied. If the template-argument represents a set of
2901 // overloaded functions (or a pointer to such), the matching
2902 // function is selected from the set (13.4).
2903 (ParamType->isPointerType() &&
2904 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
2905 // -- For a non-type template-parameter of type reference to
2906 // function, no conversions apply. If the template-argument
2907 // represents a set of overloaded functions, the matching
2908 // function is selected from the set (13.4).
2909 (ParamType->isReferenceType() &&
2910 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
2911 // -- For a non-type template-parameter of type pointer to
2912 // member function, no conversions apply. If the
2913 // template-argument represents a set of overloaded member
2914 // functions, the matching member function is selected from
2916 (ParamType->isMemberPointerType() &&
2917 ParamType->getAs<MemberPointerType>()->getPointeeType()
2918 ->isFunctionType())) {
2920 if (Arg->getType() == Context.OverloadTy) {
2921 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
2924 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2927 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2928 ArgType = Arg->getType();
2933 if (!ParamType->isMemberPointerType())
2934 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2938 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType())) {
2939 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp,
2940 Arg->isLvalue(Context) == Expr::LV_Valid);
2941 } else if (!Context.hasSameUnqualifiedType(ArgType,
2942 ParamType.getNonReferenceType())) {
2943 // We can't perform this conversion.
2944 Diag(Arg->getSourceRange().getBegin(),
2945 diag::err_template_arg_not_convertible)
2946 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
2947 Diag(Param->getLocation(), diag::note_template_param_here);
2951 return CheckTemplateArgumentPointerToMember(Arg, Converted);
2954 if (ParamType->isPointerType()) {
2955 // -- for a non-type template-parameter of type pointer to
2956 // object, qualification conversions (4.4) and the
2957 // array-to-pointer conversion (4.2) are applied.
2958 // C++0x also allows a value of std::nullptr_t.
2959 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() &&
2960 "Only object pointers allowed here");
2962 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2967 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
2968 // -- For a non-type template-parameter of type reference to
2969 // object, no conversions apply. The type referred to by the
2970 // reference may be more cv-qualified than the (otherwise
2971 // identical) type of the template-argument. The
2972 // template-parameter is bound directly to the
2973 // template-argument, which must be an lvalue.
2974 assert(ParamRefType->getPointeeType()->isObjectType() &&
2975 "Only object references allowed here");
2977 if (Arg->getType() == Context.OverloadTy) {
2978 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
2979 ParamRefType->getPointeeType(),
2982 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
2985 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
2986 ArgType = Arg->getType();
2991 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
2996 // -- For a non-type template-parameter of type pointer to data
2997 // member, qualification conversions (4.4) are applied.
2998 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
3000 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
3001 // Types match exactly: nothing more to do here.
3002 } else if (IsQualificationConversion(ArgType, ParamType)) {
3003 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp,
3004 Arg->isLvalue(Context) == Expr::LV_Valid);
3006 // We can't perform this conversion.
3007 Diag(Arg->getSourceRange().getBegin(),
3008 diag::err_template_arg_not_convertible)
3009 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
3010 Diag(Param->getLocation(), diag::note_template_param_here);
3014 return CheckTemplateArgumentPointerToMember(Arg, Converted);
3017 /// \brief Check a template argument against its corresponding
3018 /// template template parameter.
3020 /// This routine implements the semantics of C++ [temp.arg.template].
3021 /// It returns true if an error occurred, and false otherwise.
3022 bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
3023 const TemplateArgumentLoc &Arg) {
3024 TemplateName Name = Arg.getArgument().getAsTemplate();
3025 TemplateDecl *Template = Name.getAsTemplateDecl();
3027 // Any dependent template name is fine.
3028 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
3032 // C++ [temp.arg.template]p1:
3033 // A template-argument for a template template-parameter shall be
3034 // the name of a class template, expressed as id-expression. Only
3035 // primary class templates are considered when matching the
3036 // template template argument with the corresponding parameter;
3037 // partial specializations are not considered even if their
3038 // parameter lists match that of the template template parameter.
3040 // Note that we also allow template template parameters here, which
3041 // will happen when we are dealing with, e.g., class template
3042 // partial specializations.
3043 if (!isa<ClassTemplateDecl>(Template) &&
3044 !isa<TemplateTemplateParmDecl>(Template)) {
3045 assert(isa<FunctionTemplateDecl>(Template) &&
3046 "Only function templates are possible here");
3047 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
3048 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
3052 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
3053 Param->getTemplateParameters(),
3055 TPL_TemplateTemplateArgumentMatch,
3059 /// \brief Given a non-type template argument that refers to a
3060 /// declaration and the type of its corresponding non-type template
3061 /// parameter, produce an expression that properly refers to that
3063 Sema::OwningExprResult
3064 Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3066 SourceLocation Loc) {
3067 assert(Arg.getKind() == TemplateArgument::Declaration &&
3068 "Only declaration template arguments permitted here");
3069 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
3071 if (VD->getDeclContext()->isRecord() &&
3072 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
3073 // If the value is a class member, we might have a pointer-to-member.
3074 // Determine whether the non-type template template parameter is of
3075 // pointer-to-member type. If so, we need to build an appropriate
3076 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3077 // would refer to the member itself.
3078 if (ParamType->isMemberPointerType()) {
3080 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3081 NestedNameSpecifier *Qualifier
3082 = NestedNameSpecifier::Create(Context, 0, false, ClassType.getTypePtr());
3084 SS.setScopeRep(Qualifier);
3085 OwningExprResult RefExpr = BuildDeclRefExpr(VD,
3086 VD->getType().getNonReferenceType(),
3089 if (RefExpr.isInvalid())
3092 RefExpr = CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
3094 // We might need to perform a trailing qualification conversion, since
3095 // the element type on the parameter could be more qualified than the
3096 // element type in the expression we constructed.
3097 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
3098 ParamType.getUnqualifiedType())) {
3099 Expr *RefE = RefExpr.takeAs<Expr>();
3100 ImpCastExprToType(RefE, ParamType.getUnqualifiedType(),
3102 RefExpr = Owned(RefE);
3105 assert(!RefExpr.isInvalid() &&
3106 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
3107 ParamType.getUnqualifiedType()));
3108 return move(RefExpr);
3112 QualType T = VD->getType().getNonReferenceType();
3113 if (ParamType->isPointerType()) {
3114 // When the non-type template parameter is a pointer, take the
3115 // address of the declaration.
3116 OwningExprResult RefExpr = BuildDeclRefExpr(VD, T, Loc);
3117 if (RefExpr.isInvalid())
3120 if (T->isFunctionType() || T->isArrayType()) {
3121 // Decay functions and arrays.
3122 Expr *RefE = (Expr *)RefExpr.get();
3123 DefaultFunctionArrayConversion(RefE);
3124 if (RefE != RefExpr.get()) {
3126 RefExpr = Owned(RefE);
3129 return move(RefExpr);
3132 // Take the address of everything else
3133 return CreateBuiltinUnaryOp(Loc, UnaryOperator::AddrOf, move(RefExpr));
3136 // If the non-type template parameter has reference type, qualify the
3137 // resulting declaration reference with the extra qualifiers on the
3138 // type that the reference refers to.
3139 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>())
3140 T = Context.getQualifiedType(T, TargetRef->getPointeeType().getQualifiers());
3142 return BuildDeclRefExpr(VD, T, Loc);
3145 /// \brief Construct a new expression that refers to the given
3146 /// integral template argument with the given source-location
3149 /// This routine takes care of the mapping from an integral template
3150 /// argument (which may have any integral type) to the appropriate
3152 Sema::OwningExprResult
3153 Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3154 SourceLocation Loc) {
3155 assert(Arg.getKind() == TemplateArgument::Integral &&
3156 "Operation is only value for integral template arguments");
3157 QualType T = Arg.getIntegralType();
3158 if (T->isCharType() || T->isWideCharType())
3159 return Owned(new (Context) CharacterLiteral(
3160 Arg.getAsIntegral()->getZExtValue(),
3161 T->isWideCharType(),
3164 if (T->isBooleanType())
3165 return Owned(new (Context) CXXBoolLiteralExpr(
3166 Arg.getAsIntegral()->getBoolValue(),
3170 return Owned(new (Context) IntegerLiteral(*Arg.getAsIntegral(), T, Loc));
3174 /// \brief Determine whether the given template parameter lists are
3177 /// \param New The new template parameter list, typically written in the
3178 /// source code as part of a new template declaration.
3180 /// \param Old The old template parameter list, typically found via
3181 /// name lookup of the template declared with this template parameter
3184 /// \param Complain If true, this routine will produce a diagnostic if
3185 /// the template parameter lists are not equivalent.
3187 /// \param Kind describes how we are to match the template parameter lists.
3189 /// \param TemplateArgLoc If this source location is valid, then we
3190 /// are actually checking the template parameter list of a template
3191 /// argument (New) against the template parameter list of its
3192 /// corresponding template template parameter (Old). We produce
3193 /// slightly different diagnostics in this scenario.
3195 /// \returns True if the template parameter lists are equal, false
3198 Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3199 TemplateParameterList *Old,
3201 TemplateParameterListEqualKind Kind,
3202 SourceLocation TemplateArgLoc) {
3203 if (Old->size() != New->size()) {
3205 unsigned NextDiag = diag::err_template_param_list_different_arity;
3206 if (TemplateArgLoc.isValid()) {
3207 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3208 NextDiag = diag::note_template_param_list_different_arity;
3210 Diag(New->getTemplateLoc(), NextDiag)
3211 << (New->size() > Old->size())
3212 << (Kind != TPL_TemplateMatch)
3213 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
3214 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
3215 << (Kind != TPL_TemplateMatch)
3216 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3222 for (TemplateParameterList::iterator OldParm = Old->begin(),
3223 OldParmEnd = Old->end(), NewParm = New->begin();
3224 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
3225 if ((*OldParm)->getKind() != (*NewParm)->getKind()) {
3227 unsigned NextDiag = diag::err_template_param_different_kind;
3228 if (TemplateArgLoc.isValid()) {
3229 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3230 NextDiag = diag::note_template_param_different_kind;
3232 Diag((*NewParm)->getLocation(), NextDiag)
3233 << (Kind != TPL_TemplateMatch);
3234 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration)
3235 << (Kind != TPL_TemplateMatch);
3240 if (isa<TemplateTypeParmDecl>(*OldParm)) {
3241 // Okay; all template type parameters are equivalent (since we
3242 // know we're at the same index).
3243 } else if (NonTypeTemplateParmDecl *OldNTTP
3244 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) {
3245 // The types of non-type template parameters must agree.
3246 NonTypeTemplateParmDecl *NewNTTP
3247 = cast<NonTypeTemplateParmDecl>(*NewParm);
3249 // If we are matching a template template argument to a template
3250 // template parameter and one of the non-type template parameter types
3251 // is dependent, then we must wait until template instantiation time
3252 // to actually compare the arguments.
3253 if (Kind == TPL_TemplateTemplateArgumentMatch &&
3254 (OldNTTP->getType()->isDependentType() ||
3255 NewNTTP->getType()->isDependentType()))
3258 if (Context.getCanonicalType(OldNTTP->getType()) !=
3259 Context.getCanonicalType(NewNTTP->getType())) {
3261 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3262 if (TemplateArgLoc.isValid()) {
3263 Diag(TemplateArgLoc,
3264 diag::err_template_arg_template_params_mismatch);
3265 NextDiag = diag::note_template_nontype_parm_different_type;
3267 Diag(NewNTTP->getLocation(), NextDiag)
3268 << NewNTTP->getType()
3269 << (Kind != TPL_TemplateMatch);
3270 Diag(OldNTTP->getLocation(),
3271 diag::note_template_nontype_parm_prev_declaration)
3272 << OldNTTP->getType();
3277 // The template parameter lists of template template
3278 // parameters must agree.
3279 assert(isa<TemplateTemplateParmDecl>(*OldParm) &&
3280 "Only template template parameters handled here");
3281 TemplateTemplateParmDecl *OldTTP
3282 = cast<TemplateTemplateParmDecl>(*OldParm);
3283 TemplateTemplateParmDecl *NewTTP
3284 = cast<TemplateTemplateParmDecl>(*NewParm);
3285 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3286 OldTTP->getTemplateParameters(),
3288 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind),
3297 /// \brief Check whether a template can be declared within this scope.
3299 /// If the template declaration is valid in this scope, returns
3300 /// false. Otherwise, issues a diagnostic and returns true.
3302 Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
3303 // Find the nearest enclosing declaration scope.
3304 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3305 (S->getFlags() & Scope::TemplateParamScope) != 0)
3309 // A template-declaration can appear only as a namespace scope or
3310 // class scope declaration.
3311 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
3312 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3313 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
3314 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
3315 << TemplateParams->getSourceRange();
3317 while (Ctx && isa<LinkageSpecDecl>(Ctx))
3318 Ctx = Ctx->getParent();
3320 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3323 return Diag(TemplateParams->getTemplateLoc(),
3324 diag::err_template_outside_namespace_or_class_scope)
3325 << TemplateParams->getSourceRange();
3328 /// \brief Determine what kind of template specialization the given declaration
3330 static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3332 return TSK_Undeclared;
3334 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3335 return Record->getTemplateSpecializationKind();
3336 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3337 return Function->getTemplateSpecializationKind();
3338 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3339 return Var->getTemplateSpecializationKind();
3341 return TSK_Undeclared;
3344 /// \brief Check whether a specialization is well-formed in the current
3347 /// This routine determines whether a template specialization can be declared
3348 /// in the current context (C++ [temp.expl.spec]p2).
3350 /// \param S the semantic analysis object for which this check is being
3353 /// \param Specialized the entity being specialized or instantiated, which
3354 /// may be a kind of template (class template, function template, etc.) or
3355 /// a member of a class template (member function, static data member,
3358 /// \param PrevDecl the previous declaration of this entity, if any.
3360 /// \param Loc the location of the explicit specialization or instantiation of
3363 /// \param IsPartialSpecialization whether this is a partial specialization of
3364 /// a class template.
3366 /// \returns true if there was an error that we cannot recover from, false
3368 static bool CheckTemplateSpecializationScope(Sema &S,
3369 NamedDecl *Specialized,
3370 NamedDecl *PrevDecl,
3372 bool IsPartialSpecialization) {
3373 // Keep these "kind" numbers in sync with the %select statements in the
3374 // various diagnostics emitted by this routine.
3376 bool isTemplateSpecialization = false;
3377 if (isa<ClassTemplateDecl>(Specialized)) {
3378 EntityKind = IsPartialSpecialization? 1 : 0;
3379 isTemplateSpecialization = true;
3380 } else if (isa<FunctionTemplateDecl>(Specialized)) {
3382 isTemplateSpecialization = true;
3383 } else if (isa<CXXMethodDecl>(Specialized))
3385 else if (isa<VarDecl>(Specialized))
3387 else if (isa<RecordDecl>(Specialized))
3390 S.Diag(Loc, diag::err_template_spec_unknown_kind);
3391 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3395 // C++ [temp.expl.spec]p2:
3396 // An explicit specialization shall be declared in the namespace
3397 // of which the template is a member, or, for member templates, in
3398 // the namespace of which the enclosing class or enclosing class
3399 // template is a member. An explicit specialization of a member
3400 // function, member class or static data member of a class
3401 // template shall be declared in the namespace of which the class
3402 // template is a member. Such a declaration may also be a
3403 // definition. If the declaration is not a definition, the
3404 // specialization may be defined later in the name- space in which
3405 // the explicit specialization was declared, or in a namespace
3406 // that encloses the one in which the explicit specialization was
3408 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) {
3409 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
3414 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
3415 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
3420 // C++ [temp.class.spec]p6:
3421 // A class template partial specialization may be declared or redeclared
3422 // in any namespace scope in which its definition may be defined (14.5.1
3424 bool ComplainedAboutScope = false;
3425 DeclContext *SpecializedContext
3426 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
3427 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
3429 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
3430 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
3431 // There is no prior declaration of this entity, so this
3432 // specialization must be in the same context as the template
3434 if (!DC->Equals(SpecializedContext)) {
3435 if (isa<TranslationUnitDecl>(SpecializedContext))
3436 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
3437 << EntityKind << Specialized;
3438 else if (isa<NamespaceDecl>(SpecializedContext))
3439 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope)
3440 << EntityKind << Specialized
3441 << cast<NamedDecl>(SpecializedContext);
3443 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3444 ComplainedAboutScope = true;
3448 // Make sure that this redeclaration (or definition) occurs in an enclosing
3450 // Note that HandleDeclarator() performs this check for explicit
3451 // specializations of function templates, static data members, and member
3452 // functions, so we skip the check here for those kinds of entities.
3453 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
3454 // Should we refactor that check, so that it occurs later?
3455 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
3456 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
3457 isa<FunctionDecl>(Specialized))) {
3458 if (isa<TranslationUnitDecl>(SpecializedContext))
3459 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
3460 << EntityKind << Specialized;
3461 else if (isa<NamespaceDecl>(SpecializedContext))
3462 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
3463 << EntityKind << Specialized
3464 << cast<NamedDecl>(SpecializedContext);
3466 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
3469 // FIXME: check for specialization-after-instantiation errors and such.
3474 /// \brief Check the non-type template arguments of a class template
3475 /// partial specialization according to C++ [temp.class.spec]p9.
3477 /// \param TemplateParams the template parameters of the primary class
3480 /// \param TemplateArg the template arguments of the class template
3481 /// partial specialization.
3483 /// \param MirrorsPrimaryTemplate will be set true if the class
3484 /// template partial specialization arguments are identical to the
3485 /// implicit template arguments of the primary template. This is not
3486 /// necessarily an error (C++0x), and it is left to the caller to diagnose
3487 /// this condition when it is an error.
3489 /// \returns true if there was an error, false otherwise.
3490 bool Sema::CheckClassTemplatePartialSpecializationArgs(
3491 TemplateParameterList *TemplateParams,
3492 const TemplateArgumentListBuilder &TemplateArgs,
3493 bool &MirrorsPrimaryTemplate) {
3494 // FIXME: the interface to this function will have to change to
3495 // accommodate variadic templates.
3496 MirrorsPrimaryTemplate = true;
3498 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments();
3500 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3501 // Determine whether the template argument list of the partial
3502 // specialization is identical to the implicit argument list of
3503 // the primary template. The caller may need to diagnostic this as
3504 // an error per C++ [temp.class.spec]p9b3.
3505 if (MirrorsPrimaryTemplate) {
3506 if (TemplateTypeParmDecl *TTP
3507 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) {
3508 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) !=
3509 Context.getCanonicalType(ArgList[I].getAsType()))
3510 MirrorsPrimaryTemplate = false;
3511 } else if (TemplateTemplateParmDecl *TTP
3512 = dyn_cast<TemplateTemplateParmDecl>(
3513 TemplateParams->getParam(I))) {
3514 TemplateName Name = ArgList[I].getAsTemplate();
3515 TemplateTemplateParmDecl *ArgDecl
3516 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
3518 ArgDecl->getIndex() != TTP->getIndex() ||
3519 ArgDecl->getDepth() != TTP->getDepth())
3520 MirrorsPrimaryTemplate = false;
3524 NonTypeTemplateParmDecl *Param
3525 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
3530 Expr *ArgExpr = ArgList[I].getAsExpr();
3532 MirrorsPrimaryTemplate = false;
3536 // C++ [temp.class.spec]p8:
3537 // A non-type argument is non-specialized if it is the name of a
3538 // non-type parameter. All other non-type arguments are
3541 // Below, we check the two conditions that only apply to
3542 // specialized non-type arguments, so skip any non-specialized
3544 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
3545 if (NonTypeTemplateParmDecl *NTTP
3546 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) {
3547 if (MirrorsPrimaryTemplate &&
3548 (Param->getIndex() != NTTP->getIndex() ||
3549 Param->getDepth() != NTTP->getDepth()))
3550 MirrorsPrimaryTemplate = false;
3555 // C++ [temp.class.spec]p9:
3556 // Within the argument list of a class template partial
3557 // specialization, the following restrictions apply:
3558 // -- A partially specialized non-type argument expression
3559 // shall not involve a template parameter of the partial
3560 // specialization except when the argument expression is a
3561 // simple identifier.
3562 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
3563 Diag(ArgExpr->getLocStart(),
3564 diag::err_dependent_non_type_arg_in_partial_spec)
3565 << ArgExpr->getSourceRange();
3569 // -- The type of a template parameter corresponding to a
3570 // specialized non-type argument shall not be dependent on a
3571 // parameter of the specialization.
3572 if (Param->getType()->isDependentType()) {
3573 Diag(ArgExpr->getLocStart(),
3574 diag::err_dependent_typed_non_type_arg_in_partial_spec)
3576 << ArgExpr->getSourceRange();
3577 Diag(Param->getLocation(), diag::note_template_param_here);
3581 MirrorsPrimaryTemplate = false;
3587 /// \brief Retrieve the previous declaration of the given declaration.
3588 static NamedDecl *getPreviousDecl(NamedDecl *ND) {
3589 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
3590 return VD->getPreviousDeclaration();
3591 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
3592 return FD->getPreviousDeclaration();
3593 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
3594 return TD->getPreviousDeclaration();
3595 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
3596 return TD->getPreviousDeclaration();
3597 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
3598 return FTD->getPreviousDeclaration();
3599 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
3600 return CTD->getPreviousDeclaration();
3605 Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
3607 SourceLocation KWLoc,
3609 TemplateTy TemplateD,
3610 SourceLocation TemplateNameLoc,
3611 SourceLocation LAngleLoc,
3612 ASTTemplateArgsPtr TemplateArgsIn,
3613 SourceLocation RAngleLoc,
3614 AttributeList *Attr,
3615 MultiTemplateParamsArg TemplateParameterLists) {
3616 assert(TUK != TUK_Reference && "References are not specializations");
3618 // Find the class template we're specializing
3619 TemplateName Name = TemplateD.getAsVal<TemplateName>();
3620 ClassTemplateDecl *ClassTemplate
3621 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
3623 if (!ClassTemplate) {
3624 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
3625 << (Name.getAsTemplateDecl() &&
3626 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
3630 bool isExplicitSpecialization = false;
3631 bool isPartialSpecialization = false;
3633 // Check the validity of the template headers that introduce this
3635 // FIXME: We probably shouldn't complain about these headers for
3636 // friend declarations.
3637 TemplateParameterList *TemplateParams
3638 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
3639 (TemplateParameterList**)TemplateParameterLists.get(),
3640 TemplateParameterLists.size(),
3642 isExplicitSpecialization);
3643 if (TemplateParams && TemplateParams->size() > 0) {
3644 isPartialSpecialization = true;
3646 // C++ [temp.class.spec]p10:
3647 // The template parameter list of a specialization shall not
3648 // contain default template argument values.
3649 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
3650 Decl *Param = TemplateParams->getParam(I);
3651 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
3652 if (TTP->hasDefaultArgument()) {
3653 Diag(TTP->getDefaultArgumentLoc(),
3654 diag::err_default_arg_in_partial_spec);
3655 TTP->removeDefaultArgument();
3657 } else if (NonTypeTemplateParmDecl *NTTP
3658 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3659 if (Expr *DefArg = NTTP->getDefaultArgument()) {
3660 Diag(NTTP->getDefaultArgumentLoc(),
3661 diag::err_default_arg_in_partial_spec)
3662 << DefArg->getSourceRange();
3663 NTTP->setDefaultArgument(0);
3664 DefArg->Destroy(Context);
3667 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
3668 if (TTP->hasDefaultArgument()) {
3669 Diag(TTP->getDefaultArgument().getLocation(),
3670 diag::err_default_arg_in_partial_spec)
3671 << TTP->getDefaultArgument().getSourceRange();
3672 TTP->setDefaultArgument(TemplateArgumentLoc());
3676 } else if (TemplateParams) {
3677 if (TUK == TUK_Friend)
3678 Diag(KWLoc, diag::err_template_spec_friend)
3679 << FixItHint::CreateRemoval(
3680 SourceRange(TemplateParams->getTemplateLoc(),
3681 TemplateParams->getRAngleLoc()))
3682 << SourceRange(LAngleLoc, RAngleLoc);
3684 isExplicitSpecialization = true;
3685 } else if (TUK != TUK_Friend) {
3686 Diag(KWLoc, diag::err_template_spec_needs_header)
3687 << FixItHint::CreateInsertion(KWLoc, "template<> ");
3688 isExplicitSpecialization = true;
3691 // Check that the specialization uses the same tag kind as the
3692 // original template.
3693 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3694 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
3695 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
3697 *ClassTemplate->getIdentifier())) {
3698 Diag(KWLoc, diag::err_use_with_wrong_tag)
3700 << FixItHint::CreateReplacement(KWLoc,
3701 ClassTemplate->getTemplatedDecl()->getKindName());
3702 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
3703 diag::note_previous_use);
3704 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
3707 // Translate the parser's template argument list in our AST format.
3708 TemplateArgumentListInfo TemplateArgs;
3709 TemplateArgs.setLAngleLoc(LAngleLoc);
3710 TemplateArgs.setRAngleLoc(RAngleLoc);
3711 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3713 // Check that the template argument list is well-formed for this
3715 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
3716 TemplateArgs.size());
3717 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
3718 TemplateArgs, false, Converted))
3721 assert((Converted.structuredSize() ==
3722 ClassTemplate->getTemplateParameters()->size()) &&
3723 "Converted template argument list is too short!");
3725 // Find the class template (partial) specialization declaration that
3726 // corresponds to these arguments.
3727 llvm::FoldingSetNodeID ID;
3728 if (isPartialSpecialization) {
3729 bool MirrorsPrimaryTemplate;
3730 if (CheckClassTemplatePartialSpecializationArgs(
3731 ClassTemplate->getTemplateParameters(),
3732 Converted, MirrorsPrimaryTemplate))
3735 if (MirrorsPrimaryTemplate) {
3736 // C++ [temp.class.spec]p9b3:
3738 // -- The argument list of the specialization shall not be identical
3739 // to the implicit argument list of the primary template.
3740 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
3741 << (TUK == TUK_Definition)
3742 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
3743 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
3744 ClassTemplate->getIdentifier(),
3751 // FIXME: Diagnose friend partial specializations
3753 if (!Name.isDependent() &&
3754 !TemplateSpecializationType::anyDependentTemplateArguments(
3755 TemplateArgs.getArgumentArray(),
3756 TemplateArgs.size())) {
3757 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3758 << ClassTemplate->getDeclName();
3759 isPartialSpecialization = false;
3761 // FIXME: Template parameter list matters, too
3762 ClassTemplatePartialSpecializationDecl::Profile(ID,
3763 Converted.getFlatArguments(),
3764 Converted.flatSize(),
3769 if (!isPartialSpecialization)
3770 ClassTemplateSpecializationDecl::Profile(ID,
3771 Converted.getFlatArguments(),
3772 Converted.flatSize(),
3774 void *InsertPos = 0;
3775 ClassTemplateSpecializationDecl *PrevDecl = 0;
3777 if (isPartialSpecialization)
3779 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
3783 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
3785 ClassTemplateSpecializationDecl *Specialization = 0;
3787 // Check whether we can declare a class template specialization in
3788 // the current scope.
3789 if (TUK != TUK_Friend &&
3790 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
3792 isPartialSpecialization))
3795 // The canonical type
3798 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
3799 TUK == TUK_Friend)) {
3800 // Since the only prior class template specialization with these
3801 // arguments was referenced but not declared, or we're only
3802 // referencing this specialization as a friend, reuse that
3803 // declaration node as our own, updating its source location to
3804 // reflect our new declaration.
3805 Specialization = PrevDecl;
3806 Specialization->setLocation(TemplateNameLoc);
3808 CanonType = Context.getTypeDeclType(Specialization);
3809 } else if (isPartialSpecialization) {
3810 // Build the canonical type that describes the converted template
3811 // arguments of the class template partial specialization.
3812 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
3813 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
3814 Converted.getFlatArguments(),
3815 Converted.flatSize());
3817 // Create a new class template partial specialization declaration node.
3818 ClassTemplatePartialSpecializationDecl *PrevPartial
3819 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
3820 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
3821 : ClassTemplate->getPartialSpecializations().size();
3822 ClassTemplatePartialSpecializationDecl *Partial
3823 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
3824 ClassTemplate->getDeclContext(),
3833 SetNestedNameSpecifier(Partial, SS);
3836 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial);
3837 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial);
3839 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos);
3841 Specialization = Partial;
3843 // If we are providing an explicit specialization of a member class
3844 // template specialization, make a note of that.
3845 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3846 PrevPartial->setMemberSpecialization();
3848 // Check that all of the template parameters of the class template
3849 // partial specialization are deducible from the template
3850 // arguments. If not, this class template partial specialization
3851 // will never be used.
3852 llvm::SmallVector<bool, 8> DeducibleParams;
3853 DeducibleParams.resize(TemplateParams->size());
3854 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3855 TemplateParams->getDepth(),
3857 unsigned NumNonDeducible = 0;
3858 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
3859 if (!DeducibleParams[I])
3862 if (NumNonDeducible) {
3863 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
3864 << (NumNonDeducible > 1)
3865 << SourceRange(TemplateNameLoc, RAngleLoc);
3866 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3867 if (!DeducibleParams[I]) {
3868 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3869 if (Param->getDeclName())
3870 Diag(Param->getLocation(),
3871 diag::note_partial_spec_unused_parameter)
3872 << Param->getDeclName();
3874 Diag(Param->getLocation(),
3875 diag::note_partial_spec_unused_parameter)
3876 << std::string("<anonymous>");
3881 // Create a new class template specialization declaration node for
3882 // this explicit specialization or friend declaration.
3884 = ClassTemplateSpecializationDecl::Create(Context, Kind,
3885 ClassTemplate->getDeclContext(),
3890 SetNestedNameSpecifier(Specialization, SS);
3893 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
3894 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization);
3896 ClassTemplate->getSpecializations().InsertNode(Specialization,
3900 CanonType = Context.getTypeDeclType(Specialization);
3903 // C++ [temp.expl.spec]p6:
3904 // If a template, a member template or the member of a class template is
3905 // explicitly specialized then that specialization shall be declared
3906 // before the first use of that specialization that would cause an implicit
3907 // instantiation to take place, in every translation unit in which such a
3908 // use occurs; no diagnostic is required.
3909 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3911 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
3912 // Is there any previous explicit specialization declaration?
3913 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3920 SourceRange Range(TemplateNameLoc, RAngleLoc);
3921 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3922 << Context.getTypeDeclType(Specialization) << Range;
3924 Diag(PrevDecl->getPointOfInstantiation(),
3925 diag::note_instantiation_required_here)
3926 << (PrevDecl->getTemplateSpecializationKind()
3927 != TSK_ImplicitInstantiation);
3932 // If this is not a friend, note that this is an explicit specialization.
3933 if (TUK != TUK_Friend)
3934 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
3936 // Check that this isn't a redefinition of this specialization.
3937 if (TUK == TUK_Definition) {
3938 if (RecordDecl *Def = Specialization->getDefinition()) {
3939 SourceRange Range(TemplateNameLoc, RAngleLoc);
3940 Diag(TemplateNameLoc, diag::err_redefinition)
3941 << Context.getTypeDeclType(Specialization) << Range;
3942 Diag(Def->getLocation(), diag::note_previous_definition);
3943 Specialization->setInvalidDecl();
3948 // Build the fully-sugared type for this class template
3949 // specialization as the user wrote in the specialization
3950 // itself. This means that we'll pretty-print the type retrieved
3951 // from the specialization's declaration the way that the user
3952 // actually wrote the specialization, rather than formatting the
3953 // name based on the "canonical" representation used to store the
3954 // template arguments in the specialization.
3955 TypeSourceInfo *WrittenTy
3956 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
3957 TemplateArgs, CanonType);
3958 if (TUK != TUK_Friend)
3959 Specialization->setTypeAsWritten(WrittenTy);
3960 TemplateArgsIn.release();
3962 // C++ [temp.expl.spec]p9:
3963 // A template explicit specialization is in the scope of the
3964 // namespace in which the template was defined.
3966 // We actually implement this paragraph where we set the semantic
3967 // context (in the creation of the ClassTemplateSpecializationDecl),
3968 // but we also maintain the lexical context where the actual
3969 // definition occurs.
3970 Specialization->setLexicalDeclContext(CurContext);
3972 // We may be starting the definition of this specialization.
3973 if (TUK == TUK_Definition)
3974 Specialization->startDefinition();
3976 if (TUK == TUK_Friend) {
3977 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
3981 Friend->setAccess(AS_public);
3982 CurContext->addDecl(Friend);
3984 // Add the specialization into its lexical context, so that it can
3985 // be seen when iterating through the list of declarations in that
3986 // context. However, specializations are not found by name lookup.
3987 CurContext->addDecl(Specialization);
3989 return DeclPtrTy::make(Specialization);
3993 Sema::ActOnTemplateDeclarator(Scope *S,
3994 MultiTemplateParamsArg TemplateParameterLists,
3996 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
4000 Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
4001 MultiTemplateParamsArg TemplateParameterLists,
4003 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
4004 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4005 "Not a function declarator!");
4006 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
4008 if (FTI.hasPrototype) {
4009 // FIXME: Diagnose arguments without names in C.
4012 Scope *ParentScope = FnBodyScope->getParent();
4014 DeclPtrTy DP = HandleDeclarator(ParentScope, D,
4015 move(TemplateParameterLists),
4016 /*IsFunctionDefinition=*/true);
4017 if (FunctionTemplateDecl *FunctionTemplate
4018 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>()))
4019 return ActOnStartOfFunctionDef(FnBodyScope,
4020 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl()));
4021 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>()))
4022 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function));
4026 /// \brief Strips various properties off an implicit instantiation
4027 /// that has just been explicitly specialized.
4028 static void StripImplicitInstantiation(NamedDecl *D) {
4029 D->invalidateAttrs();
4031 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4032 FD->setInlineSpecified(false);
4036 /// \brief Diagnose cases where we have an explicit template specialization
4037 /// before/after an explicit template instantiation, producing diagnostics
4038 /// for those cases where they are required and determining whether the
4039 /// new specialization/instantiation will have any effect.
4041 /// \param NewLoc the location of the new explicit specialization or
4044 /// \param NewTSK the kind of the new explicit specialization or instantiation.
4046 /// \param PrevDecl the previous declaration of the entity.
4048 /// \param PrevTSK the kind of the old explicit specialization or instantiatin.
4050 /// \param PrevPointOfInstantiation if valid, indicates where the previus
4051 /// declaration was instantiated (either implicitly or explicitly).
4053 /// \param SuppressNew will be set to true to indicate that the new
4054 /// specialization or instantiation has no effect and should be ignored.
4056 /// \returns true if there was an error that should prevent the introduction of
4057 /// the new declaration into the AST, false otherwise.
4059 Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4060 TemplateSpecializationKind NewTSK,
4061 NamedDecl *PrevDecl,
4062 TemplateSpecializationKind PrevTSK,
4063 SourceLocation PrevPointOfInstantiation,
4064 bool &SuppressNew) {
4065 SuppressNew = false;
4068 case TSK_Undeclared:
4069 case TSK_ImplicitInstantiation:
4070 assert(false && "Don't check implicit instantiations here");
4073 case TSK_ExplicitSpecialization:
4075 case TSK_Undeclared:
4076 case TSK_ExplicitSpecialization:
4077 // Okay, we're just specializing something that is either already
4078 // explicitly specialized or has merely been mentioned without any
4082 case TSK_ImplicitInstantiation:
4083 if (PrevPointOfInstantiation.isInvalid()) {
4084 // The declaration itself has not actually been instantiated, so it is
4085 // still okay to specialize it.
4086 StripImplicitInstantiation(PrevDecl);
4091 case TSK_ExplicitInstantiationDeclaration:
4092 case TSK_ExplicitInstantiationDefinition:
4093 assert((PrevTSK == TSK_ImplicitInstantiation ||
4094 PrevPointOfInstantiation.isValid()) &&
4095 "Explicit instantiation without point of instantiation?");
4097 // C++ [temp.expl.spec]p6:
4098 // If a template, a member template or the member of a class template
4099 // is explicitly specialized then that specialization shall be declared
4100 // before the first use of that specialization that would cause an
4101 // implicit instantiation to take place, in every translation unit in
4102 // which such a use occurs; no diagnostic is required.
4103 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4104 // Is there any previous explicit specialization declaration?
4105 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4109 Diag(NewLoc, diag::err_specialization_after_instantiation)
4111 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
4112 << (PrevTSK != TSK_ImplicitInstantiation);
4118 case TSK_ExplicitInstantiationDeclaration:
4120 case TSK_ExplicitInstantiationDeclaration:
4121 // This explicit instantiation declaration is redundant (that's okay).
4125 case TSK_Undeclared:
4126 case TSK_ImplicitInstantiation:
4127 // We're explicitly instantiating something that may have already been
4128 // implicitly instantiated; that's fine.
4131 case TSK_ExplicitSpecialization:
4132 // C++0x [temp.explicit]p4:
4133 // For a given set of template parameters, if an explicit instantiation
4134 // of a template appears after a declaration of an explicit
4135 // specialization for that template, the explicit instantiation has no
4140 case TSK_ExplicitInstantiationDefinition:
4141 // C++0x [temp.explicit]p10:
4142 // If an entity is the subject of both an explicit instantiation
4143 // declaration and an explicit instantiation definition in the same
4144 // translation unit, the definition shall follow the declaration.
4146 diag::err_explicit_instantiation_declaration_after_definition);
4147 Diag(PrevPointOfInstantiation,
4148 diag::note_explicit_instantiation_definition_here);
4149 assert(PrevPointOfInstantiation.isValid() &&
4150 "Explicit instantiation without point of instantiation?");
4156 case TSK_ExplicitInstantiationDefinition:
4158 case TSK_Undeclared:
4159 case TSK_ImplicitInstantiation:
4160 // We're explicitly instantiating something that may have already been
4161 // implicitly instantiated; that's fine.
4164 case TSK_ExplicitSpecialization:
4165 // C++ DR 259, C++0x [temp.explicit]p4:
4166 // For a given set of template parameters, if an explicit
4167 // instantiation of a template appears after a declaration of
4168 // an explicit specialization for that template, the explicit
4169 // instantiation has no effect.
4171 // In C++98/03 mode, we only give an extension warning here, because it
4172 // is not harmful to try to explicitly instantiate something that
4173 // has been explicitly specialized.
4174 if (!getLangOptions().CPlusPlus0x) {
4175 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
4177 Diag(PrevDecl->getLocation(),
4178 diag::note_previous_template_specialization);
4183 case TSK_ExplicitInstantiationDeclaration:
4184 // We're explicity instantiating a definition for something for which we
4185 // were previously asked to suppress instantiations. That's fine.
4188 case TSK_ExplicitInstantiationDefinition:
4189 // C++0x [temp.spec]p5:
4190 // For a given template and a given set of template-arguments,
4191 // - an explicit instantiation definition shall appear at most once
4193 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
4195 Diag(PrevPointOfInstantiation,
4196 diag::note_previous_explicit_instantiation);
4203 assert(false && "Missing specialization/instantiation case?");
4208 /// \brief Perform semantic analysis for the given dependent function
4209 /// template specialization. The only possible way to get a dependent
4210 /// function template specialization is with a friend declaration,
4213 /// template <class T> void foo(T);
4214 /// template <class T> class A {
4215 /// friend void foo<>(T);
4218 /// There really isn't any useful analysis we can do here, so we
4219 /// just store the information.
4221 Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4222 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4223 LookupResult &Previous) {
4224 // Remove anything from Previous that isn't a function template in
4225 // the correct context.
4226 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
4227 LookupResult::Filter F = Previous.makeFilter();
4228 while (F.hasNext()) {
4229 NamedDecl *D = F.next()->getUnderlyingDecl();
4230 if (!isa<FunctionTemplateDecl>(D) ||
4231 !FDLookupContext->Equals(D->getDeclContext()->getLookupContext()))
4236 // Should this be diagnosed here?
4237 if (Previous.empty()) return true;
4239 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4240 ExplicitTemplateArgs);
4244 /// \brief Perform semantic analysis for the given function template
4247 /// This routine performs all of the semantic analysis required for an
4248 /// explicit function template specialization. On successful completion,
4249 /// the function declaration \p FD will become a function template
4252 /// \param FD the function declaration, which will be updated to become a
4253 /// function template specialization.
4255 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4256 /// if any. Note that this may be valid info even when 0 arguments are
4257 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
4258 /// as it anyway contains info on the angle brackets locations.
4260 /// \param PrevDecl the set of declarations that may be specialized by
4261 /// this function specialization.
4263 Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
4264 const TemplateArgumentListInfo *ExplicitTemplateArgs,
4265 LookupResult &Previous) {
4266 // The set of function template specializations that could match this
4267 // explicit function template specialization.
4268 UnresolvedSet<8> Candidates;
4270 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext();
4271 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4273 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4274 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
4275 // Only consider templates found within the same semantic lookup scope as
4277 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext()))
4280 // C++ [temp.expl.spec]p11:
4281 // A trailing template-argument can be left unspecified in the
4282 // template-id naming an explicit function template specialization
4283 // provided it can be deduced from the function argument type.
4284 // Perform template argument deduction to determine whether we may be
4285 // specializing this template.
4286 // FIXME: It is somewhat wasteful to build
4287 TemplateDeductionInfo Info(Context, FD->getLocation());
4288 FunctionDecl *Specialization = 0;
4289 if (TemplateDeductionResult TDK
4290 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
4294 // FIXME: Template argument deduction failed; record why it failed, so
4295 // that we can provide nifty diagnostics.
4300 // Record this candidate.
4301 Candidates.addDecl(Specialization, I.getAccess());
4305 // Find the most specialized function template.
4306 UnresolvedSetIterator Result
4307 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4308 TPOC_Other, FD->getLocation(),
4309 PDiag(diag::err_function_template_spec_no_match)
4310 << FD->getDeclName(),
4311 PDiag(diag::err_function_template_spec_ambiguous)
4312 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
4313 PDiag(diag::note_function_template_spec_matched));
4314 if (Result == Candidates.end())
4317 // Ignore access information; it doesn't figure into redeclaration checking.
4318 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
4319 Specialization->setLocation(FD->getLocation());
4321 // FIXME: Check if the prior specialization has a point of instantiation.
4322 // If so, we have run afoul of .
4324 // If this is a friend declaration, then we're not really declaring
4325 // an explicit specialization.
4326 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
4328 // Check the scope of this explicit specialization.
4330 CheckTemplateSpecializationScope(*this,
4331 Specialization->getPrimaryTemplate(),
4332 Specialization, FD->getLocation(),
4336 // C++ [temp.expl.spec]p6:
4337 // If a template, a member template or the member of a class template is
4338 // explicitly specialized then that specialization shall be declared
4339 // before the first use of that specialization that would cause an implicit
4340 // instantiation to take place, in every translation unit in which such a
4341 // use occurs; no diagnostic is required.
4342 FunctionTemplateSpecializationInfo *SpecInfo
4343 = Specialization->getTemplateSpecializationInfo();
4344 assert(SpecInfo && "Function template specialization info missing?");
4346 bool SuppressNew = false;
4348 CheckSpecializationInstantiationRedecl(FD->getLocation(),
4349 TSK_ExplicitSpecialization,
4351 SpecInfo->getTemplateSpecializationKind(),
4352 SpecInfo->getPointOfInstantiation(),
4356 // Mark the prior declaration as an explicit specialization, so that later
4357 // clients know that this is an explicit specialization.
4359 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
4361 // Turn the given function declaration into a function template
4362 // specialization, with the template arguments from the previous
4364 // Take copies of (semantic and syntactic) template argument lists.
4365 const TemplateArgumentList* TemplArgs = new (Context)
4366 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
4367 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs
4368 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0;
4369 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
4370 TemplArgs, /*InsertPos=*/0,
4371 SpecInfo->getTemplateSpecializationKind(),
4372 TemplArgsAsWritten);
4374 // The "previous declaration" for this function template specialization is
4375 // the prior function template specialization.
4377 Previous.addDecl(Specialization);
4381 /// \brief Perform semantic analysis for the given non-template member
4384 /// This routine performs all of the semantic analysis required for an
4385 /// explicit member function specialization. On successful completion,
4386 /// the function declaration \p FD will become a member function
4389 /// \param Member the member declaration, which will be updated to become a
4392 /// \param Previous the set of declarations, one of which may be specialized
4393 /// by this function specialization; the set will be modified to contain the
4394 /// redeclared member.
4396 Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
4397 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
4399 // Try to find the member we are instantiating.
4400 NamedDecl *Instantiation = 0;
4401 NamedDecl *InstantiatedFrom = 0;
4402 MemberSpecializationInfo *MSInfo = 0;
4404 if (Previous.empty()) {
4405 // Nowhere to look anyway.
4406 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
4407 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4409 NamedDecl *D = (*I)->getUnderlyingDecl();
4410 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
4411 if (Context.hasSameType(Function->getType(), Method->getType())) {
4412 Instantiation = Method;
4413 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
4414 MSInfo = Method->getMemberSpecializationInfo();
4419 } else if (isa<VarDecl>(Member)) {
4421 if (Previous.isSingleResult() &&
4422 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
4423 if (PrevVar->isStaticDataMember()) {
4424 Instantiation = PrevVar;
4425 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
4426 MSInfo = PrevVar->getMemberSpecializationInfo();
4428 } else if (isa<RecordDecl>(Member)) {
4429 CXXRecordDecl *PrevRecord;
4430 if (Previous.isSingleResult() &&
4431 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
4432 Instantiation = PrevRecord;
4433 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
4434 MSInfo = PrevRecord->getMemberSpecializationInfo();
4438 if (!Instantiation) {
4439 // There is no previous declaration that matches. Since member
4440 // specializations are always out-of-line, the caller will complain about
4441 // this mismatch later.
4445 // If this is a friend, just bail out here before we start turning
4446 // things into explicit specializations.
4447 if (Member->getFriendObjectKind() != Decl::FOK_None) {
4448 // Preserve instantiation information.
4449 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
4450 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
4451 cast<CXXMethodDecl>(InstantiatedFrom),
4452 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
4453 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
4454 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4455 cast<CXXRecordDecl>(InstantiatedFrom),
4456 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
4460 Previous.addDecl(Instantiation);
4464 // Make sure that this is a specialization of a member.
4465 if (!InstantiatedFrom) {
4466 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
4468 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
4472 // C++ [temp.expl.spec]p6:
4473 // If a template, a member template or the member of a class template is
4474 // explicitly specialized then that spe- cialization shall be declared
4475 // before the first use of that specialization that would cause an implicit
4476 // instantiation to take place, in every translation unit in which such a
4477 // use occurs; no diagnostic is required.
4478 assert(MSInfo && "Member specialization info missing?");
4480 bool SuppressNew = false;
4481 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
4482 TSK_ExplicitSpecialization,
4484 MSInfo->getTemplateSpecializationKind(),
4485 MSInfo->getPointOfInstantiation(),
4489 // Check the scope of this explicit specialization.
4490 if (CheckTemplateSpecializationScope(*this,
4492 Instantiation, Member->getLocation(),
4496 // Note that this is an explicit instantiation of a member.
4497 // the original declaration to note that it is an explicit specialization
4498 // (if it was previously an implicit instantiation). This latter step
4499 // makes bookkeeping easier.
4500 if (isa<FunctionDecl>(Member)) {
4501 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
4502 if (InstantiationFunction->getTemplateSpecializationKind() ==
4503 TSK_ImplicitInstantiation) {
4504 InstantiationFunction->setTemplateSpecializationKind(
4505 TSK_ExplicitSpecialization);
4506 InstantiationFunction->setLocation(Member->getLocation());
4509 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
4510 cast<CXXMethodDecl>(InstantiatedFrom),
4511 TSK_ExplicitSpecialization);
4512 } else if (isa<VarDecl>(Member)) {
4513 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
4514 if (InstantiationVar->getTemplateSpecializationKind() ==
4515 TSK_ImplicitInstantiation) {
4516 InstantiationVar->setTemplateSpecializationKind(
4517 TSK_ExplicitSpecialization);
4518 InstantiationVar->setLocation(Member->getLocation());
4521 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
4522 cast<VarDecl>(InstantiatedFrom),
4523 TSK_ExplicitSpecialization);
4525 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
4526 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
4527 if (InstantiationClass->getTemplateSpecializationKind() ==
4528 TSK_ImplicitInstantiation) {
4529 InstantiationClass->setTemplateSpecializationKind(
4530 TSK_ExplicitSpecialization);
4531 InstantiationClass->setLocation(Member->getLocation());
4534 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
4535 cast<CXXRecordDecl>(InstantiatedFrom),
4536 TSK_ExplicitSpecialization);
4539 // Save the caller the trouble of having to figure out which declaration
4540 // this specialization matches.
4542 Previous.addDecl(Instantiation);
4546 /// \brief Check the scope of an explicit instantiation.
4547 static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
4548 SourceLocation InstLoc,
4549 bool WasQualifiedName) {
4550 DeclContext *ExpectedContext
4551 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext();
4552 DeclContext *CurContext = S.CurContext->getLookupContext();
4554 // C++0x [temp.explicit]p2:
4555 // An explicit instantiation shall appear in an enclosing namespace of its
4558 // This is DR275, which we do not retroactively apply to C++98/03.
4559 if (S.getLangOptions().CPlusPlus0x &&
4560 !CurContext->Encloses(ExpectedContext)) {
4561 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext))
4563 S.getLangOptions().CPlusPlus0x?
4564 diag::err_explicit_instantiation_out_of_scope
4565 : diag::warn_explicit_instantiation_out_of_scope_0x)
4569 S.getLangOptions().CPlusPlus0x?
4570 diag::err_explicit_instantiation_must_be_global
4571 : diag::warn_explicit_instantiation_out_of_scope_0x)
4573 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4577 // C++0x [temp.explicit]p2:
4578 // If the name declared in the explicit instantiation is an unqualified
4579 // name, the explicit instantiation shall appear in the namespace where
4580 // its template is declared or, if that namespace is inline (7.3.1), any
4581 // namespace from its enclosing namespace set.
4582 if (WasQualifiedName)
4585 if (CurContext->Equals(ExpectedContext))
4589 S.getLangOptions().CPlusPlus0x?
4590 diag::err_explicit_instantiation_unqualified_wrong_namespace
4591 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
4592 << D << ExpectedContext;
4593 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
4596 /// \brief Determine whether the given scope specifier has a template-id in it.
4597 static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
4601 // C++0x [temp.explicit]p2:
4602 // If the explicit instantiation is for a member function, a member class
4603 // or a static data member of a class template specialization, the name of
4604 // the class template specialization in the qualified-id for the member
4605 // name shall be a simple-template-id.
4607 // C++98 has the same restriction, just worded differently.
4608 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
4609 NNS; NNS = NNS->getPrefix())
4610 if (Type *T = NNS->getAsType())
4611 if (isa<TemplateSpecializationType>(T))
4617 // Explicit instantiation of a class template specialization
4619 Sema::ActOnExplicitInstantiation(Scope *S,
4620 SourceLocation ExternLoc,
4621 SourceLocation TemplateLoc,
4623 SourceLocation KWLoc,
4624 const CXXScopeSpec &SS,
4625 TemplateTy TemplateD,
4626 SourceLocation TemplateNameLoc,
4627 SourceLocation LAngleLoc,
4628 ASTTemplateArgsPtr TemplateArgsIn,
4629 SourceLocation RAngleLoc,
4630 AttributeList *Attr) {
4631 // Find the class template we're specializing
4632 TemplateName Name = TemplateD.getAsVal<TemplateName>();
4633 ClassTemplateDecl *ClassTemplate
4634 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
4636 // Check that the specialization uses the same tag kind as the
4637 // original template.
4638 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4639 assert(Kind != TTK_Enum &&
4640 "Invalid enum tag in class template explicit instantiation!");
4641 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
4643 *ClassTemplate->getIdentifier())) {
4644 Diag(KWLoc, diag::err_use_with_wrong_tag)
4646 << FixItHint::CreateReplacement(KWLoc,
4647 ClassTemplate->getTemplatedDecl()->getKindName());
4648 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
4649 diag::note_previous_use);
4650 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4653 // C++0x [temp.explicit]p2:
4654 // There are two forms of explicit instantiation: an explicit instantiation
4655 // definition and an explicit instantiation declaration. An explicit
4656 // instantiation declaration begins with the extern keyword. [...]
4657 TemplateSpecializationKind TSK
4658 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4659 : TSK_ExplicitInstantiationDeclaration;
4661 // Translate the parser's template argument list in our AST format.
4662 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4663 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4665 // Check that the template argument list is well-formed for this
4667 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
4668 TemplateArgs.size());
4669 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4670 TemplateArgs, false, Converted))
4673 assert((Converted.structuredSize() ==
4674 ClassTemplate->getTemplateParameters()->size()) &&
4675 "Converted template argument list is too short!");
4677 // Find the class template specialization declaration that
4678 // corresponds to these arguments.
4679 llvm::FoldingSetNodeID ID;
4680 ClassTemplateSpecializationDecl::Profile(ID,
4681 Converted.getFlatArguments(),
4682 Converted.flatSize(),
4684 void *InsertPos = 0;
4685 ClassTemplateSpecializationDecl *PrevDecl
4686 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4688 // C++0x [temp.explicit]p2:
4689 // [...] An explicit instantiation shall appear in an enclosing
4690 // namespace of its template. [...]
4692 // This is C++ DR 275.
4693 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
4696 ClassTemplateSpecializationDecl *Specialization = 0;
4698 bool ReusedDecl = false;
4700 bool SuppressNew = false;
4701 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
4703 PrevDecl->getSpecializationKind(),
4704 PrevDecl->getPointOfInstantiation(),
4706 return DeclPtrTy::make(PrevDecl);
4709 return DeclPtrTy::make(PrevDecl);
4711 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation ||
4712 PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4713 // Since the only prior class template specialization with these
4714 // arguments was referenced but not declared, reuse that
4715 // declaration node as our own, updating its source location to
4716 // reflect our new declaration.
4717 Specialization = PrevDecl;
4718 Specialization->setLocation(TemplateNameLoc);
4724 if (!Specialization) {
4725 // Create a new class template specialization declaration node for
4726 // this explicit specialization.
4728 = ClassTemplateSpecializationDecl::Create(Context, Kind,
4729 ClassTemplate->getDeclContext(),
4732 Converted, PrevDecl);
4733 SetNestedNameSpecifier(Specialization, SS);
4736 // Remove the previous declaration from the folding set, since we want
4737 // to introduce a new declaration.
4738 ClassTemplate->getSpecializations().RemoveNode(PrevDecl);
4739 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
4742 // Insert the new specialization.
4743 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos);
4746 // Build the fully-sugared type for this explicit instantiation as
4747 // the user wrote in the explicit instantiation itself. This means
4748 // that we'll pretty-print the type retrieved from the
4749 // specialization's declaration the way that the user actually wrote
4750 // the explicit instantiation, rather than formatting the name based
4751 // on the "canonical" representation used to store the template
4752 // arguments in the specialization.
4753 TypeSourceInfo *WrittenTy
4754 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4756 Context.getTypeDeclType(Specialization));
4757 Specialization->setTypeAsWritten(WrittenTy);
4758 TemplateArgsIn.release();
4761 // Add the explicit instantiation into its lexical context. However,
4762 // since explicit instantiations are never found by name lookup, we
4763 // just put it into the declaration context directly.
4764 Specialization->setLexicalDeclContext(CurContext);
4765 CurContext->addDecl(Specialization);
4768 // C++ [temp.explicit]p3:
4769 // A definition of a class template or class member template
4770 // shall be in scope at the point of the explicit instantiation of
4771 // the class template or class member template.
4773 // This check comes when we actually try to perform the
4775 ClassTemplateSpecializationDecl *Def
4776 = cast_or_null<ClassTemplateSpecializationDecl>(
4777 Specialization->getDefinition());
4779 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
4780 else if (TSK == TSK_ExplicitInstantiationDefinition)
4781 MarkVTableUsed(TemplateNameLoc, Specialization, true);
4783 // Instantiate the members of this class template specialization.
4784 Def = cast_or_null<ClassTemplateSpecializationDecl>(
4785 Specialization->getDefinition());
4787 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
4789 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
4790 // TSK_ExplicitInstantiationDefinition
4791 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
4792 TSK == TSK_ExplicitInstantiationDefinition)
4793 Def->setTemplateSpecializationKind(TSK);
4795 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
4798 return DeclPtrTy::make(Specialization);
4801 // Explicit instantiation of a member class of a class template.
4803 Sema::ActOnExplicitInstantiation(Scope *S,
4804 SourceLocation ExternLoc,
4805 SourceLocation TemplateLoc,
4807 SourceLocation KWLoc,
4809 IdentifierInfo *Name,
4810 SourceLocation NameLoc,
4811 AttributeList *Attr) {
4814 bool IsDependent = false;
4815 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference,
4816 KWLoc, SS, Name, NameLoc, Attr, AS_none,
4817 MultiTemplateParamsArg(*this, 0, 0),
4818 Owned, IsDependent);
4819 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
4824 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>());
4825 if (Tag->isEnum()) {
4826 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
4827 << Context.getTypeDeclType(Tag);
4831 if (Tag->isInvalidDecl())
4834 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
4835 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4837 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
4838 << Context.getTypeDeclType(Record);
4839 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
4843 // C++0x [temp.explicit]p2:
4844 // If the explicit instantiation is for a class or member class, the
4845 // elaborated-type-specifier in the declaration shall include a
4846 // simple-template-id.
4848 // C++98 has the same restriction, just worded differently.
4849 if (!ScopeSpecifierHasTemplateId(SS))
4850 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id)
4851 << Record << SS.getRange();
4853 // C++0x [temp.explicit]p2:
4854 // There are two forms of explicit instantiation: an explicit instantiation
4855 // definition and an explicit instantiation declaration. An explicit
4856 // instantiation declaration begins with the extern keyword. [...]
4857 TemplateSpecializationKind TSK
4858 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4859 : TSK_ExplicitInstantiationDeclaration;
4861 // C++0x [temp.explicit]p2:
4862 // [...] An explicit instantiation shall appear in an enclosing
4863 // namespace of its template. [...]
4865 // This is C++ DR 275.
4866 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
4868 // Verify that it is okay to explicitly instantiate here.
4869 CXXRecordDecl *PrevDecl
4870 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
4871 if (!PrevDecl && Record->getDefinition())
4874 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
4875 bool SuppressNew = false;
4876 assert(MSInfo && "No member specialization information?");
4877 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
4879 MSInfo->getTemplateSpecializationKind(),
4880 MSInfo->getPointOfInstantiation(),
4887 CXXRecordDecl *RecordDef
4888 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
4890 // C++ [temp.explicit]p3:
4891 // A definition of a member class of a class template shall be in scope
4892 // at the point of an explicit instantiation of the member class.
4894 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
4896 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
4897 << 0 << Record->getDeclName() << Record->getDeclContext();
4898 Diag(Pattern->getLocation(), diag::note_forward_declaration)
4902 if (InstantiateClass(NameLoc, Record, Def,
4903 getTemplateInstantiationArgs(Record),
4907 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
4913 // Instantiate all of the members of the class.
4914 InstantiateClassMembers(NameLoc, RecordDef,
4915 getTemplateInstantiationArgs(Record), TSK);
4917 if (TSK == TSK_ExplicitInstantiationDefinition)
4918 MarkVTableUsed(NameLoc, RecordDef, true);
4920 // FIXME: We don't have any representation for explicit instantiations of
4921 // member classes. Such a representation is not needed for compilation, but it
4922 // should be available for clients that want to see all of the declarations in
4927 Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
4928 SourceLocation ExternLoc,
4929 SourceLocation TemplateLoc,
4931 // Explicit instantiations always require a name.
4932 DeclarationName Name = GetNameForDeclarator(D);
4934 if (!D.isInvalidType())
4935 Diag(D.getDeclSpec().getSourceRange().getBegin(),
4936 diag::err_explicit_instantiation_requires_name)
4937 << D.getDeclSpec().getSourceRange()
4938 << D.getSourceRange();
4943 // The scope passed in may not be a decl scope. Zip up the scope tree until
4944 // we find one that is.
4945 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4946 (S->getFlags() & Scope::TemplateParamScope) != 0)
4949 // Determine the type of the declaration.
4950 QualType R = GetTypeForDeclarator(D, S, 0);
4954 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4955 // Cannot explicitly instantiate a typedef.
4956 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
4961 // C++0x [temp.explicit]p1:
4962 // [...] An explicit instantiation of a function template shall not use the
4963 // inline or constexpr specifiers.
4964 // Presumably, this also applies to member functions of class templates as
4966 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
4967 Diag(D.getDeclSpec().getInlineSpecLoc(),
4968 diag::err_explicit_instantiation_inline)
4969 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
4971 // FIXME: check for constexpr specifier.
4973 // C++0x [temp.explicit]p2:
4974 // There are two forms of explicit instantiation: an explicit instantiation
4975 // definition and an explicit instantiation declaration. An explicit
4976 // instantiation declaration begins with the extern keyword. [...]
4977 TemplateSpecializationKind TSK
4978 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
4979 : TSK_ExplicitInstantiationDeclaration;
4981 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName);
4982 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
4984 if (!R->isFunctionType()) {
4985 // C++ [temp.explicit]p1:
4986 // A [...] static data member of a class template can be explicitly
4987 // instantiated from the member definition associated with its class
4989 if (Previous.isAmbiguous())
4992 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
4993 if (!Prev || !Prev->isStaticDataMember()) {
4994 // We expect to see a data data member here.
4995 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
4997 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
4999 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
5003 if (!Prev->getInstantiatedFromStaticDataMember()) {
5004 // FIXME: Check for explicit specialization?
5005 Diag(D.getIdentifierLoc(),
5006 diag::err_explicit_instantiation_data_member_not_instantiated)
5008 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
5009 // FIXME: Can we provide a note showing where this was declared?
5013 // C++0x [temp.explicit]p2:
5014 // If the explicit instantiation is for a member function, a member class
5015 // or a static data member of a class template specialization, the name of
5016 // the class template specialization in the qualified-id for the member
5017 // name shall be a simple-template-id.
5019 // C++98 has the same restriction, just worded differently.
5020 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5021 Diag(D.getIdentifierLoc(),
5022 diag::err_explicit_instantiation_without_qualified_id)
5023 << Prev << D.getCXXScopeSpec().getRange();
5025 // Check the scope of this explicit instantiation.
5026 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
5028 // Verify that it is okay to explicitly instantiate here.
5029 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
5030 assert(MSInfo && "Missing static data member specialization info?");
5031 bool SuppressNew = false;
5032 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
5033 MSInfo->getTemplateSpecializationKind(),
5034 MSInfo->getPointOfInstantiation(),
5040 // Instantiate static data member.
5041 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
5042 if (TSK == TSK_ExplicitInstantiationDefinition)
5043 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false,
5044 /*DefinitionRequired=*/true);
5046 // FIXME: Create an ExplicitInstantiation node?
5050 // If the declarator is a template-id, translate the parser's template
5051 // argument list into our AST format.
5052 bool HasExplicitTemplateArgs = false;
5053 TemplateArgumentListInfo TemplateArgs;
5054 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5055 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5056 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5057 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
5058 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5059 TemplateId->getTemplateArgs(),
5060 TemplateId->NumArgs);
5061 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
5062 HasExplicitTemplateArgs = true;
5063 TemplateArgsPtr.release();
5066 // C++ [temp.explicit]p1:
5067 // A [...] function [...] can be explicitly instantiated from its template.
5068 // A member function [...] of a class template can be explicitly
5069 // instantiated from the member definition associated with its class
5071 UnresolvedSet<8> Matches;
5072 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5074 NamedDecl *Prev = *P;
5075 if (!HasExplicitTemplateArgs) {
5076 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
5077 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
5080 Matches.addDecl(Method, P.getAccess());
5081 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
5087 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5091 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
5092 FunctionDecl *Specialization = 0;
5093 if (TemplateDeductionResult TDK
5094 = DeduceTemplateArguments(FunTmpl,
5095 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
5096 R, Specialization, Info)) {
5097 // FIXME: Keep track of almost-matches?
5102 Matches.addDecl(Specialization, P.getAccess());
5105 // Find the most specialized function template specialization.
5106 UnresolvedSetIterator Result
5107 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other,
5108 D.getIdentifierLoc(),
5109 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5110 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5111 PDiag(diag::note_explicit_instantiation_candidate));
5113 if (Result == Matches.end())
5116 // Ignore access control bits, we don't need them for redeclaration checking.
5117 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
5119 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
5120 Diag(D.getIdentifierLoc(),
5121 diag::err_explicit_instantiation_member_function_not_instantiated)
5123 << (Specialization->getTemplateSpecializationKind() ==
5124 TSK_ExplicitSpecialization);
5125 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5129 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
5130 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5131 PrevDecl = Specialization;
5134 bool SuppressNew = false;
5135 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
5137 PrevDecl->getTemplateSpecializationKind(),
5138 PrevDecl->getPointOfInstantiation(),
5142 // FIXME: We may still want to build some representation of this
5143 // explicit specialization.
5148 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
5150 if (TSK == TSK_ExplicitInstantiationDefinition)
5151 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization,
5152 false, /*DefinitionRequired=*/true);
5154 // C++0x [temp.explicit]p2:
5155 // If the explicit instantiation is for a member function, a member class
5156 // or a static data member of a class template specialization, the name of
5157 // the class template specialization in the qualified-id for the member
5158 // name shall be a simple-template-id.
5160 // C++98 has the same restriction, just worded differently.
5161 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
5162 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
5163 D.getCXXScopeSpec().isSet() &&
5164 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5165 Diag(D.getIdentifierLoc(),
5166 diag::err_explicit_instantiation_without_qualified_id)
5167 << Specialization << D.getCXXScopeSpec().getRange();
5169 CheckExplicitInstantiationScope(*this,
5170 FunTmpl? (NamedDecl *)FunTmpl
5171 : Specialization->getInstantiatedFromMemberFunction(),
5172 D.getIdentifierLoc(),
5173 D.getCXXScopeSpec().isSet());
5175 // FIXME: Create some kind of ExplicitInstantiationDecl here.
5180 Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5181 const CXXScopeSpec &SS, IdentifierInfo *Name,
5182 SourceLocation TagLoc, SourceLocation NameLoc) {
5183 // This has to hold, because SS is expected to be defined.
5184 assert(Name && "Expected a name in a dependent tag");
5186 NestedNameSpecifier *NNS
5187 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5191 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
5193 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
5194 Diag(NameLoc, diag::err_dependent_tag_decl)
5195 << (TUK == TUK_Definition) << Kind << SS.getRange();
5199 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
5200 return Context.getDependentNameType(Kwd, NNS, Name).getAsOpaquePtr();
5203 static void FillTypeLoc(DependentNameTypeLoc TL,
5204 SourceLocation TypenameLoc,
5205 SourceRange QualifierRange,
5206 SourceLocation NameLoc) {
5207 TL.setKeywordLoc(TypenameLoc);
5208 TL.setQualifierRange(QualifierRange);
5209 TL.setNameLoc(NameLoc);
5212 static void FillTypeLoc(ElaboratedTypeLoc TL,
5213 SourceLocation TypenameLoc,
5214 SourceRange QualifierRange) {
5215 // FIXME: inner locations.
5216 TL.setKeywordLoc(TypenameLoc);
5217 TL.setQualifierRange(QualifierRange);
5221 Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
5222 const IdentifierInfo &II, SourceLocation IdLoc) {
5223 NestedNameSpecifier *NNS
5224 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5228 QualType T = CheckTypenameType(ETK_Typename, NNS, II,
5229 TypenameLoc, SS.getRange(), IdLoc);
5233 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5234 if (isa<DependentNameType>(T)) {
5235 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
5236 // FIXME: fill inner type loc
5237 FillTypeLoc(TL, TypenameLoc, SS.getRange(), IdLoc);
5239 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
5240 // FIXME: fill inner type loc
5241 FillTypeLoc(TL, TypenameLoc, SS.getRange());
5244 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
5248 Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS,
5249 SourceLocation TemplateLoc, TypeTy *Ty) {
5250 QualType T = GetTypeFromParser(Ty);
5251 NestedNameSpecifier *NNS
5252 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5253 const TemplateSpecializationType *TemplateId
5254 = T->getAs<TemplateSpecializationType>();
5255 assert(TemplateId && "Expected a template specialization type");
5257 if (computeDeclContext(SS, false)) {
5258 // If we can compute a declaration context, then the "typename"
5259 // keyword was superfluous. Just build an ElaboratedType to keep
5260 // track of the nested-name-specifier.
5261 T = Context.getElaboratedType(ETK_Typename, NNS, T);
5262 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5263 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
5264 // FIXME: fill inner type loc
5265 FillTypeLoc(TL, TypenameLoc, SS.getRange());
5266 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
5269 T = Context.getDependentNameType(ETK_Typename, NNS, TemplateId);
5270 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5271 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
5272 // FIXME: fill inner type loc
5273 FillTypeLoc(TL, TypenameLoc, SS.getRange(), TemplateLoc);
5274 return CreateLocInfoType(T, TSI).getAsOpaquePtr();
5277 /// \brief Build the type that describes a C++ typename specifier,
5278 /// e.g., "typename T::type".
5280 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
5281 NestedNameSpecifier *NNS, const IdentifierInfo &II,
5282 SourceLocation KeywordLoc, SourceRange NNSRange,
5283 SourceLocation IILoc) {
5285 SS.setScopeRep(NNS);
5286 SS.setRange(NNSRange);
5288 DeclContext *Ctx = computeDeclContext(SS);
5290 // If the nested-name-specifier is dependent and couldn't be
5291 // resolved to a type, build a typename type.
5292 assert(NNS->isDependent());
5293 return Context.getDependentNameType(Keyword, NNS, &II);
5296 // If the nested-name-specifier refers to the current instantiation,
5297 // the "typename" keyword itself is superfluous. In C++03, the
5298 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
5299 // allows such extraneous "typename" keywords, and we retroactively
5300 // apply this DR to C++03 code. In any case we continue.
5302 if (RequireCompleteDeclContext(SS, Ctx))
5305 DeclarationName Name(&II);
5306 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
5307 LookupQualifiedName(Result, Ctx);
5308 unsigned DiagID = 0;
5309 Decl *Referenced = 0;
5310 switch (Result.getResultKind()) {
5311 case LookupResult::NotFound:
5312 DiagID = diag::err_typename_nested_not_found;
5315 case LookupResult::NotFoundInCurrentInstantiation:
5316 // Okay, it's a member of an unknown instantiation.
5317 return Context.getDependentNameType(Keyword, NNS, &II);
5319 case LookupResult::Found:
5320 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
5321 // We found a type. Build an ElaboratedType, since the
5322 // typename-specifier was just sugar.
5323 return Context.getElaboratedType(ETK_Typename, NNS,
5324 Context.getTypeDeclType(Type));
5327 DiagID = diag::err_typename_nested_not_type;
5328 Referenced = Result.getFoundDecl();
5331 case LookupResult::FoundUnresolvedValue:
5332 llvm_unreachable("unresolved using decl in non-dependent context");
5335 case LookupResult::FoundOverloaded:
5336 DiagID = diag::err_typename_nested_not_type;
5337 Referenced = *Result.begin();
5340 case LookupResult::Ambiguous:
5344 // If we get here, it's because name lookup did not find a
5345 // type. Emit an appropriate diagnostic and return an error.
5346 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
5348 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
5350 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
5356 // See Sema::RebuildTypeInCurrentInstantiation
5357 class CurrentInstantiationRebuilder
5358 : public TreeTransform<CurrentInstantiationRebuilder> {
5360 DeclarationName Entity;
5363 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
5365 CurrentInstantiationRebuilder(Sema &SemaRef,
5367 DeclarationName Entity)
5368 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
5369 Loc(Loc), Entity(Entity) { }
5371 /// \brief Determine whether the given type \p T has already been
5374 /// For the purposes of type reconstruction, a type has already been
5375 /// transformed if it is NULL or if it is not dependent.
5376 bool AlreadyTransformed(QualType T) {
5377 return T.isNull() || !T->isDependentType();
5380 /// \brief Returns the location of the entity whose type is being
5382 SourceLocation getBaseLocation() { return Loc; }
5384 /// \brief Returns the name of the entity whose type is being rebuilt.
5385 DeclarationName getBaseEntity() { return Entity; }
5387 /// \brief Sets the "base" location and entity when that
5388 /// information is known based on another transformation.
5389 void setBase(SourceLocation Loc, DeclarationName Entity) {
5391 this->Entity = Entity;
5394 /// \brief Transforms an expression by returning the expression itself
5395 /// (an identity function).
5397 /// FIXME: This is completely unsafe; we will need to actually clone the
5399 Sema::OwningExprResult TransformExpr(Expr *E) {
5400 return getSema().Owned(E->Retain());
5403 /// \brief Transforms a typename type by determining whether the type now
5404 /// refers to a member of the current instantiation, and then
5405 /// type-checking and building an ElaboratedType (when possible).
5406 QualType TransformDependentNameType(TypeLocBuilder &TLB,
5407 DependentNameTypeLoc TL,
5408 QualType ObjectType);
5413 CurrentInstantiationRebuilder::TransformDependentNameType(TypeLocBuilder &TLB,
5414 DependentNameTypeLoc TL,
5415 QualType ObjectType) {
5416 DependentNameType *T = TL.getTypePtr();
5418 NestedNameSpecifier *NNS
5419 = TransformNestedNameSpecifier(T->getQualifier(),
5420 TL.getQualifierRange(),
5425 // If the nested-name-specifier did not change, and we cannot compute the
5426 // context corresponding to the nested-name-specifier, then this
5427 // typename type will not change; exit early.
5429 SS.setRange(TL.getQualifierRange());
5430 SS.setScopeRep(NNS);
5433 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0)
5434 Result = QualType(T, 0);
5436 // Rebuild the typename type, which will probably turn into a
5438 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) {
5439 QualType NewTemplateId
5440 = TransformType(QualType(TemplateId, 0));
5441 if (NewTemplateId.isNull())
5444 if (NNS == T->getQualifier() &&
5445 NewTemplateId == QualType(TemplateId, 0))
5446 Result = QualType(T, 0);
5448 Result = getDerived().RebuildDependentNameType(T->getKeyword(),
5449 NNS, NewTemplateId);
5451 Result = getDerived().RebuildDependentNameType(T->getKeyword(), NNS,
5454 TL.getQualifierRange(),
5457 if (Result.isNull())
5460 if (const ElaboratedType* ElabT = Result->getAs<ElaboratedType>()) {
5461 QualType NamedT = ElabT->getNamedType();
5462 if (isa<TemplateSpecializationType>(NamedT)) {
5463 TemplateSpecializationTypeLoc NamedTLoc
5464 = TLB.push<TemplateSpecializationTypeLoc>(NamedT);
5465 // FIXME: fill locations
5466 NamedTLoc.initializeLocal(TL.getNameLoc());
5468 TLB.pushTypeSpec(NamedT).setNameLoc(TL.getNameLoc());
5470 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
5471 NewTL.setKeywordLoc(TL.getKeywordLoc());
5472 NewTL.setQualifierRange(TL.getQualifierRange());
5475 DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
5476 NewTL.setKeywordLoc(TL.getKeywordLoc());
5477 NewTL.setQualifierRange(TL.getQualifierRange());
5478 NewTL.setNameLoc(TL.getNameLoc());
5483 /// \brief Rebuilds a type within the context of the current instantiation.
5485 /// The type \p T is part of the type of an out-of-line member definition of
5486 /// a class template (or class template partial specialization) that was parsed
5487 /// and constructed before we entered the scope of the class template (or
5488 /// partial specialization thereof). This routine will rebuild that type now
5489 /// that we have entered the declarator's scope, which may produce different
5490 /// canonical types, e.g.,
5493 /// template<typename T>
5495 /// typedef T* pointer;
5499 /// template<typename T>
5500 /// typename X<T>::pointer X<T>::data() { ... }
5503 /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
5504 /// since we do not know that we can look into X<T> when we parsed the type.
5505 /// This function will rebuild the type, performing the lookup of "pointer"
5506 /// in X<T> and returning an ElaboratedType whose canonical type is the same
5507 /// as the canonical type of T*, allowing the return types of the out-of-line
5508 /// definition and the declaration to match.
5509 TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
5511 DeclarationName Name) {
5512 if (!T || !T->getType()->isDependentType())
5515 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
5516 return Rebuilder.TransformType(T);
5519 bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
5520 if (SS.isInvalid()) return true;
5522 NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
5523 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
5525 NestedNameSpecifier *Rebuilt =
5526 Rebuilder.TransformNestedNameSpecifier(NNS, SS.getRange());
5527 if (!Rebuilt) return true;
5529 SS.setScopeRep(Rebuilt);
5533 /// \brief Produces a formatted string that describes the binding of
5534 /// template parameters to template arguments.
5536 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5537 const TemplateArgumentList &Args) {
5538 // FIXME: For variadic templates, we'll need to get the structured list.
5539 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(),
5544 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
5545 const TemplateArgument *Args,
5549 if (!Params || Params->size() == 0 || NumArgs == 0)
5552 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
5561 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
5562 Result += Id->getName();
5565 Result += llvm::utostr(I);
5570 switch (Args[I].getKind()) {
5571 case TemplateArgument::Null:
5572 Result += "<no value>";
5575 case TemplateArgument::Type: {
5576 std::string TypeStr;
5577 Args[I].getAsType().getAsStringInternal(TypeStr,
5578 Context.PrintingPolicy);
5583 case TemplateArgument::Declaration: {
5584 bool Unnamed = true;
5585 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) {
5586 if (ND->getDeclName()) {
5588 Result += ND->getNameAsString();
5593 Result += "<anonymous>";
5598 case TemplateArgument::Template: {
5600 llvm::raw_string_ostream OS(Str);
5601 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy);
5606 case TemplateArgument::Integral: {
5607 Result += Args[I].getAsIntegral()->toString(10);
5611 case TemplateArgument::Expression: {
5612 // FIXME: This is non-optimal, since we're regurgitating the
5613 // expression we were given.
5616 llvm::raw_string_ostream OS(Str);
5617 Args[I].getAsExpr()->printPretty(OS, Context, 0,
5618 Context.PrintingPolicy);
5624 case TemplateArgument::Pack:
5625 // FIXME: Format template argument packs
5626 Result += "<template argument pack>";