[Heikki Kultala] This patch contains the ABI changes for the TCE target.
[clang.git] / lib / Sema / SemaTemplate.cpp
blob12ed3732e714a9c03e7d8cb63c525d35610acad7
1 //===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //===----------------------------------------------------------------------===/
8 //
9 // This file implements semantic analysis for C++ templates.
10 //===----------------------------------------------------------------------===/
12 #include "clang/Sema/SemaInternal.h"
13 #include "clang/Sema/Lookup.h"
14 #include "clang/Sema/Scope.h"
15 #include "clang/Sema/Template.h"
16 #include "clang/Sema/TemplateDeduction.h"
17 #include "TreeTransform.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/DeclFriend.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/RecursiveASTVisitor.h"
24 #include "clang/AST/TypeVisitor.h"
25 #include "clang/Sema/DeclSpec.h"
26 #include "clang/Sema/ParsedTemplate.h"
27 #include "clang/Basic/LangOptions.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "llvm/ADT/StringExtras.h"
30 using namespace clang;
31 using namespace sema;
33 // Exported for use by Parser.
34 SourceRange
35 clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
36 unsigned N) {
37 if (!N) return SourceRange();
38 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
41 /// \brief Determine whether the declaration found is acceptable as the name
42 /// of a template and, if so, return that template declaration. Otherwise,
43 /// returns NULL.
44 static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
45 NamedDecl *Orig) {
46 NamedDecl *D = Orig->getUnderlyingDecl();
48 if (isa<TemplateDecl>(D))
49 return Orig;
51 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
52 // C++ [temp.local]p1:
53 // Like normal (non-template) classes, class templates have an
54 // injected-class-name (Clause 9). The injected-class-name
55 // can be used with or without a template-argument-list. When
56 // it is used without a template-argument-list, it is
57 // equivalent to the injected-class-name followed by the
58 // template-parameters of the class template enclosed in
59 // <>. When it is used with a template-argument-list, it
60 // refers to the specified class template specialization,
61 // which could be the current specialization or another
62 // specialization.
63 if (Record->isInjectedClassName()) {
64 Record = cast<CXXRecordDecl>(Record->getDeclContext());
65 if (Record->getDescribedClassTemplate())
66 return Record->getDescribedClassTemplate();
68 if (ClassTemplateSpecializationDecl *Spec
69 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
70 return Spec->getSpecializedTemplate();
73 return 0;
76 return 0;
79 static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) {
80 // The set of class templates we've already seen.
81 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
82 LookupResult::Filter filter = R.makeFilter();
83 while (filter.hasNext()) {
84 NamedDecl *Orig = filter.next();
85 NamedDecl *Repl = isAcceptableTemplateName(C, Orig);
86 if (!Repl)
87 filter.erase();
88 else if (Repl != Orig) {
90 // C++ [temp.local]p3:
91 // A lookup that finds an injected-class-name (10.2) can result in an
92 // ambiguity in certain cases (for example, if it is found in more than
93 // one base class). If all of the injected-class-names that are found
94 // refer to specializations of the same class template, and if the name
95 // is followed by a template-argument-list, the reference refers to the
96 // class template itself and not a specialization thereof, and is not
97 // ambiguous.
99 // FIXME: Will we eventually have to do the same for alias templates?
100 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
101 if (!ClassTemplates.insert(ClassTmpl)) {
102 filter.erase();
103 continue;
106 // FIXME: we promote access to public here as a workaround to
107 // the fact that LookupResult doesn't let us remember that we
108 // found this template through a particular injected class name,
109 // which means we end up doing nasty things to the invariants.
110 // Pretending that access is public is *much* safer.
111 filter.replace(Repl, AS_public);
114 filter.done();
117 TemplateNameKind Sema::isTemplateName(Scope *S,
118 CXXScopeSpec &SS,
119 bool hasTemplateKeyword,
120 UnqualifiedId &Name,
121 ParsedType ObjectTypePtr,
122 bool EnteringContext,
123 TemplateTy &TemplateResult,
124 bool &MemberOfUnknownSpecialization) {
125 assert(getLangOptions().CPlusPlus && "No template names in C!");
127 DeclarationName TName;
128 MemberOfUnknownSpecialization = false;
130 switch (Name.getKind()) {
131 case UnqualifiedId::IK_Identifier:
132 TName = DeclarationName(Name.Identifier);
133 break;
135 case UnqualifiedId::IK_OperatorFunctionId:
136 TName = Context.DeclarationNames.getCXXOperatorName(
137 Name.OperatorFunctionId.Operator);
138 break;
140 case UnqualifiedId::IK_LiteralOperatorId:
141 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
142 break;
144 default:
145 return TNK_Non_template;
148 QualType ObjectType = ObjectTypePtr.get();
150 LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
151 LookupOrdinaryName);
152 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
153 MemberOfUnknownSpecialization);
154 if (R.empty()) return TNK_Non_template;
155 if (R.isAmbiguous()) {
156 // Suppress diagnostics; we'll redo this lookup later.
157 R.suppressDiagnostics();
159 // FIXME: we might have ambiguous templates, in which case we
160 // should at least parse them properly!
161 return TNK_Non_template;
164 TemplateName Template;
165 TemplateNameKind TemplateKind;
167 unsigned ResultCount = R.end() - R.begin();
168 if (ResultCount > 1) {
169 // We assume that we'll preserve the qualifier from a function
170 // template name in other ways.
171 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
172 TemplateKind = TNK_Function_template;
174 // We'll do this lookup again later.
175 R.suppressDiagnostics();
176 } else {
177 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
179 if (SS.isSet() && !SS.isInvalid()) {
180 NestedNameSpecifier *Qualifier
181 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
182 Template = Context.getQualifiedTemplateName(Qualifier,
183 hasTemplateKeyword, TD);
184 } else {
185 Template = TemplateName(TD);
188 if (isa<FunctionTemplateDecl>(TD)) {
189 TemplateKind = TNK_Function_template;
191 // We'll do this lookup again later.
192 R.suppressDiagnostics();
193 } else {
194 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD));
195 TemplateKind = TNK_Type_template;
199 TemplateResult = TemplateTy::make(Template);
200 return TemplateKind;
203 bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
204 SourceLocation IILoc,
205 Scope *S,
206 const CXXScopeSpec *SS,
207 TemplateTy &SuggestedTemplate,
208 TemplateNameKind &SuggestedKind) {
209 // We can't recover unless there's a dependent scope specifier preceding the
210 // template name.
211 // FIXME: Typo correction?
212 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
213 computeDeclContext(*SS))
214 return false;
216 // The code is missing a 'template' keyword prior to the dependent template
217 // name.
218 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
219 Diag(IILoc, diag::err_template_kw_missing)
220 << Qualifier << II.getName()
221 << FixItHint::CreateInsertion(IILoc, "template ");
222 SuggestedTemplate
223 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
224 SuggestedKind = TNK_Dependent_template_name;
225 return true;
228 void Sema::LookupTemplateName(LookupResult &Found,
229 Scope *S, CXXScopeSpec &SS,
230 QualType ObjectType,
231 bool EnteringContext,
232 bool &MemberOfUnknownSpecialization) {
233 // Determine where to perform name lookup
234 MemberOfUnknownSpecialization = false;
235 DeclContext *LookupCtx = 0;
236 bool isDependent = false;
237 if (!ObjectType.isNull()) {
238 // This nested-name-specifier occurs in a member access expression, e.g.,
239 // x->B::f, and we are looking into the type of the object.
240 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
241 LookupCtx = computeDeclContext(ObjectType);
242 isDependent = ObjectType->isDependentType();
243 assert((isDependent || !ObjectType->isIncompleteType()) &&
244 "Caller should have completed object type");
245 } else if (SS.isSet()) {
246 // This nested-name-specifier occurs after another nested-name-specifier,
247 // so long into the context associated with the prior nested-name-specifier.
248 LookupCtx = computeDeclContext(SS, EnteringContext);
249 isDependent = isDependentScopeSpecifier(SS);
251 // The declaration context must be complete.
252 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
253 return;
256 bool ObjectTypeSearchedInScope = false;
257 if (LookupCtx) {
258 // Perform "qualified" name lookup into the declaration context we
259 // computed, which is either the type of the base of a member access
260 // expression or the declaration context associated with a prior
261 // nested-name-specifier.
262 LookupQualifiedName(Found, LookupCtx);
264 if (!ObjectType.isNull() && Found.empty()) {
265 // C++ [basic.lookup.classref]p1:
266 // In a class member access expression (5.2.5), if the . or -> token is
267 // immediately followed by an identifier followed by a <, the
268 // identifier must be looked up to determine whether the < is the
269 // beginning of a template argument list (14.2) or a less-than operator.
270 // The identifier is first looked up in the class of the object
271 // expression. If the identifier is not found, it is then looked up in
272 // the context of the entire postfix-expression and shall name a class
273 // or function template.
274 if (S) LookupName(Found, S);
275 ObjectTypeSearchedInScope = true;
277 } else if (isDependent && (!S || ObjectType.isNull())) {
278 // We cannot look into a dependent object type or nested nme
279 // specifier.
280 MemberOfUnknownSpecialization = true;
281 return;
282 } else {
283 // Perform unqualified name lookup in the current scope.
284 LookupName(Found, S);
287 if (Found.empty() && !isDependent) {
288 // If we did not find any names, attempt to correct any typos.
289 DeclarationName Name = Found.getLookupName();
290 if (DeclarationName Corrected = CorrectTypo(Found, S, &SS, LookupCtx,
291 false, CTC_CXXCasts)) {
292 FilterAcceptableTemplateNames(Context, Found);
293 if (!Found.empty()) {
294 if (LookupCtx)
295 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
296 << Name << LookupCtx << Found.getLookupName() << SS.getRange()
297 << FixItHint::CreateReplacement(Found.getNameLoc(),
298 Found.getLookupName().getAsString());
299 else
300 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
301 << Name << Found.getLookupName()
302 << FixItHint::CreateReplacement(Found.getNameLoc(),
303 Found.getLookupName().getAsString());
304 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
305 Diag(Template->getLocation(), diag::note_previous_decl)
306 << Template->getDeclName();
308 } else {
309 Found.clear();
310 Found.setLookupName(Name);
314 FilterAcceptableTemplateNames(Context, Found);
315 if (Found.empty()) {
316 if (isDependent)
317 MemberOfUnknownSpecialization = true;
318 return;
321 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
322 // C++ [basic.lookup.classref]p1:
323 // [...] If the lookup in the class of the object expression finds a
324 // template, the name is also looked up in the context of the entire
325 // postfix-expression and [...]
327 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
328 LookupOrdinaryName);
329 LookupName(FoundOuter, S);
330 FilterAcceptableTemplateNames(Context, FoundOuter);
332 if (FoundOuter.empty()) {
333 // - if the name is not found, the name found in the class of the
334 // object expression is used, otherwise
335 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
336 // - if the name is found in the context of the entire
337 // postfix-expression and does not name a class template, the name
338 // found in the class of the object expression is used, otherwise
339 } else if (!Found.isSuppressingDiagnostics()) {
340 // - if the name found is a class template, it must refer to the same
341 // entity as the one found in the class of the object expression,
342 // otherwise the program is ill-formed.
343 if (!Found.isSingleResult() ||
344 Found.getFoundDecl()->getCanonicalDecl()
345 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
346 Diag(Found.getNameLoc(),
347 diag::ext_nested_name_member_ref_lookup_ambiguous)
348 << Found.getLookupName()
349 << ObjectType;
350 Diag(Found.getRepresentativeDecl()->getLocation(),
351 diag::note_ambig_member_ref_object_type)
352 << ObjectType;
353 Diag(FoundOuter.getFoundDecl()->getLocation(),
354 diag::note_ambig_member_ref_scope);
356 // Recover by taking the template that we found in the object
357 // expression's type.
363 /// ActOnDependentIdExpression - Handle a dependent id-expression that
364 /// was just parsed. This is only possible with an explicit scope
365 /// specifier naming a dependent type.
366 ExprResult
367 Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
368 const DeclarationNameInfo &NameInfo,
369 bool isAddressOfOperand,
370 const TemplateArgumentListInfo *TemplateArgs) {
371 NestedNameSpecifier *Qualifier
372 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
374 DeclContext *DC = getFunctionLevelDeclContext();
376 if (!isAddressOfOperand &&
377 isa<CXXMethodDecl>(DC) &&
378 cast<CXXMethodDecl>(DC)->isInstance()) {
379 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
381 // Since the 'this' expression is synthesized, we don't need to
382 // perform the double-lookup check.
383 NamedDecl *FirstQualifierInScope = 0;
385 return Owned(CXXDependentScopeMemberExpr::Create(Context,
386 /*This*/ 0, ThisType,
387 /*IsArrow*/ true,
388 /*Op*/ SourceLocation(),
389 Qualifier, SS.getRange(),
390 FirstQualifierInScope,
391 NameInfo,
392 TemplateArgs));
395 return BuildDependentDeclRefExpr(SS, NameInfo, TemplateArgs);
398 ExprResult
399 Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
400 const DeclarationNameInfo &NameInfo,
401 const TemplateArgumentListInfo *TemplateArgs) {
402 return Owned(DependentScopeDeclRefExpr::Create(Context,
403 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
404 SS.getRange(),
405 NameInfo,
406 TemplateArgs));
409 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
410 /// that the template parameter 'PrevDecl' is being shadowed by a new
411 /// declaration at location Loc. Returns true to indicate that this is
412 /// an error, and false otherwise.
413 bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
414 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
416 // Microsoft Visual C++ permits template parameters to be shadowed.
417 if (getLangOptions().Microsoft)
418 return false;
420 // C++ [temp.local]p4:
421 // A template-parameter shall not be redeclared within its
422 // scope (including nested scopes).
423 Diag(Loc, diag::err_template_param_shadow)
424 << cast<NamedDecl>(PrevDecl)->getDeclName();
425 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
426 return true;
429 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
430 /// the parameter D to reference the templated declaration and return a pointer
431 /// to the template declaration. Otherwise, do nothing to D and return null.
432 TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
433 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
434 D = Temp->getTemplatedDecl();
435 return Temp;
437 return 0;
440 ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
441 SourceLocation EllipsisLoc) const {
442 assert(Kind == Template &&
443 "Only template template arguments can be pack expansions here");
444 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
445 "Template template argument pack expansion without packs");
446 ParsedTemplateArgument Result(*this);
447 Result.EllipsisLoc = EllipsisLoc;
448 return Result;
451 static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
452 const ParsedTemplateArgument &Arg) {
454 switch (Arg.getKind()) {
455 case ParsedTemplateArgument::Type: {
456 TypeSourceInfo *DI;
457 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
458 if (!DI)
459 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
460 return TemplateArgumentLoc(TemplateArgument(T), DI);
463 case ParsedTemplateArgument::NonType: {
464 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
465 return TemplateArgumentLoc(TemplateArgument(E), E);
468 case ParsedTemplateArgument::Template: {
469 TemplateName Template = Arg.getAsTemplate().get();
470 TemplateArgument TArg;
471 if (Arg.getEllipsisLoc().isValid())
472 TArg = TemplateArgument(Template, llvm::Optional<unsigned int>());
473 else
474 TArg = Template;
475 return TemplateArgumentLoc(TArg,
476 Arg.getScopeSpec().getRange(),
477 Arg.getLocation(),
478 Arg.getEllipsisLoc());
482 llvm_unreachable("Unhandled parsed template argument");
483 return TemplateArgumentLoc();
486 /// \brief Translates template arguments as provided by the parser
487 /// into template arguments used by semantic analysis.
488 void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
489 TemplateArgumentListInfo &TemplateArgs) {
490 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
491 TemplateArgs.addArgument(translateTemplateArgument(*this,
492 TemplateArgsIn[I]));
495 /// ActOnTypeParameter - Called when a C++ template type parameter
496 /// (e.g., "typename T") has been parsed. Typename specifies whether
497 /// the keyword "typename" was used to declare the type parameter
498 /// (otherwise, "class" was used), and KeyLoc is the location of the
499 /// "class" or "typename" keyword. ParamName is the name of the
500 /// parameter (NULL indicates an unnamed template parameter) and
501 /// ParamName is the location of the parameter name (if any).
502 /// If the type parameter has a default argument, it will be added
503 /// later via ActOnTypeParameterDefault.
504 Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
505 SourceLocation EllipsisLoc,
506 SourceLocation KeyLoc,
507 IdentifierInfo *ParamName,
508 SourceLocation ParamNameLoc,
509 unsigned Depth, unsigned Position,
510 SourceLocation EqualLoc,
511 ParsedType DefaultArg) {
512 assert(S->isTemplateParamScope() &&
513 "Template type parameter not in template parameter scope!");
514 bool Invalid = false;
516 if (ParamName) {
517 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
518 LookupOrdinaryName,
519 ForRedeclaration);
520 if (PrevDecl && PrevDecl->isTemplateParameter())
521 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
522 PrevDecl);
525 SourceLocation Loc = ParamNameLoc;
526 if (!ParamName)
527 Loc = KeyLoc;
529 TemplateTypeParmDecl *Param
530 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
531 Loc, Depth, Position, ParamName, Typename,
532 Ellipsis);
533 if (Invalid)
534 Param->setInvalidDecl();
536 if (ParamName) {
537 // Add the template parameter into the current scope.
538 S->AddDecl(Param);
539 IdResolver.AddDecl(Param);
542 // C++0x [temp.param]p9:
543 // A default template-argument may be specified for any kind of
544 // template-parameter that is not a template parameter pack.
545 if (DefaultArg && Ellipsis) {
546 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
547 DefaultArg = ParsedType();
550 // Handle the default argument, if provided.
551 if (DefaultArg) {
552 TypeSourceInfo *DefaultTInfo;
553 GetTypeFromParser(DefaultArg, &DefaultTInfo);
555 assert(DefaultTInfo && "expected source information for type");
557 // Check for unexpanded parameter packs.
558 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
559 UPPC_DefaultArgument))
560 return Param;
562 // Check the template argument itself.
563 if (CheckTemplateArgument(Param, DefaultTInfo)) {
564 Param->setInvalidDecl();
565 return Param;
568 Param->setDefaultArgument(DefaultTInfo, false);
571 return Param;
574 /// \brief Check that the type of a non-type template parameter is
575 /// well-formed.
577 /// \returns the (possibly-promoted) parameter type if valid;
578 /// otherwise, produces a diagnostic and returns a NULL type.
579 QualType
580 Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
581 // We don't allow variably-modified types as the type of non-type template
582 // parameters.
583 if (T->isVariablyModifiedType()) {
584 Diag(Loc, diag::err_variably_modified_nontype_template_param)
585 << T;
586 return QualType();
589 // C++ [temp.param]p4:
591 // A non-type template-parameter shall have one of the following
592 // (optionally cv-qualified) types:
594 // -- integral or enumeration type,
595 if (T->isIntegralOrEnumerationType() ||
596 // -- pointer to object or pointer to function,
597 T->isPointerType() ||
598 // -- reference to object or reference to function,
599 T->isReferenceType() ||
600 // -- pointer to member.
601 T->isMemberPointerType() ||
602 // If T is a dependent type, we can't do the check now, so we
603 // assume that it is well-formed.
604 T->isDependentType())
605 return T;
606 // C++ [temp.param]p8:
608 // A non-type template-parameter of type "array of T" or
609 // "function returning T" is adjusted to be of type "pointer to
610 // T" or "pointer to function returning T", respectively.
611 else if (T->isArrayType())
612 // FIXME: Keep the type prior to promotion?
613 return Context.getArrayDecayedType(T);
614 else if (T->isFunctionType())
615 // FIXME: Keep the type prior to promotion?
616 return Context.getPointerType(T);
618 Diag(Loc, diag::err_template_nontype_parm_bad_type)
619 << T;
621 return QualType();
624 Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
625 unsigned Depth,
626 unsigned Position,
627 SourceLocation EqualLoc,
628 Expr *Default) {
629 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
630 QualType T = TInfo->getType();
632 assert(S->isTemplateParamScope() &&
633 "Non-type template parameter not in template parameter scope!");
634 bool Invalid = false;
636 IdentifierInfo *ParamName = D.getIdentifier();
637 if (ParamName) {
638 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
639 LookupOrdinaryName,
640 ForRedeclaration);
641 if (PrevDecl && PrevDecl->isTemplateParameter())
642 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
643 PrevDecl);
646 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
647 if (T.isNull()) {
648 T = Context.IntTy; // Recover with an 'int' type.
649 Invalid = true;
652 bool IsParameterPack = D.hasEllipsis();
653 NonTypeTemplateParmDecl *Param
654 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
655 D.getIdentifierLoc(),
656 Depth, Position, ParamName, T,
657 IsParameterPack, TInfo);
658 if (Invalid)
659 Param->setInvalidDecl();
661 if (D.getIdentifier()) {
662 // Add the template parameter into the current scope.
663 S->AddDecl(Param);
664 IdResolver.AddDecl(Param);
667 // C++0x [temp.param]p9:
668 // A default template-argument may be specified for any kind of
669 // template-parameter that is not a template parameter pack.
670 if (Default && IsParameterPack) {
671 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
672 Default = 0;
675 // Check the well-formedness of the default template argument, if provided.
676 if (Default) {
677 // Check for unexpanded parameter packs.
678 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
679 return Param;
681 TemplateArgument Converted;
682 if (CheckTemplateArgument(Param, Param->getType(), Default, Converted)) {
683 Param->setInvalidDecl();
684 return Param;
687 Param->setDefaultArgument(Default, false);
690 return Param;
693 /// ActOnTemplateTemplateParameter - Called when a C++ template template
694 /// parameter (e.g. T in template <template <typename> class T> class array)
695 /// has been parsed. S is the current scope.
696 Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
697 SourceLocation TmpLoc,
698 TemplateParamsTy *Params,
699 SourceLocation EllipsisLoc,
700 IdentifierInfo *Name,
701 SourceLocation NameLoc,
702 unsigned Depth,
703 unsigned Position,
704 SourceLocation EqualLoc,
705 ParsedTemplateArgument Default) {
706 assert(S->isTemplateParamScope() &&
707 "Template template parameter not in template parameter scope!");
709 // Construct the parameter object.
710 bool IsParameterPack = EllipsisLoc.isValid();
711 // FIXME: Pack-ness is dropped
712 TemplateTemplateParmDecl *Param =
713 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
714 NameLoc.isInvalid()? TmpLoc : NameLoc,
715 Depth, Position, IsParameterPack,
716 Name, Params);
718 // If the template template parameter has a name, then link the identifier
719 // into the scope and lookup mechanisms.
720 if (Name) {
721 S->AddDecl(Param);
722 IdResolver.AddDecl(Param);
725 if (Params->size() == 0) {
726 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
727 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
728 Param->setInvalidDecl();
731 // C++0x [temp.param]p9:
732 // A default template-argument may be specified for any kind of
733 // template-parameter that is not a template parameter pack.
734 if (IsParameterPack && !Default.isInvalid()) {
735 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
736 Default = ParsedTemplateArgument();
739 if (!Default.isInvalid()) {
740 // Check only that we have a template template argument. We don't want to
741 // try to check well-formedness now, because our template template parameter
742 // might have dependent types in its template parameters, which we wouldn't
743 // be able to match now.
745 // If none of the template template parameter's template arguments mention
746 // other template parameters, we could actually perform more checking here.
747 // However, it isn't worth doing.
748 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
749 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
750 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
751 << DefaultArg.getSourceRange();
752 return Param;
755 // Check for unexpanded parameter packs.
756 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
757 DefaultArg.getArgument().getAsTemplate(),
758 UPPC_DefaultArgument))
759 return Param;
761 Param->setDefaultArgument(DefaultArg, false);
764 return Param;
767 /// ActOnTemplateParameterList - Builds a TemplateParameterList that
768 /// contains the template parameters in Params/NumParams.
769 Sema::TemplateParamsTy *
770 Sema::ActOnTemplateParameterList(unsigned Depth,
771 SourceLocation ExportLoc,
772 SourceLocation TemplateLoc,
773 SourceLocation LAngleLoc,
774 Decl **Params, unsigned NumParams,
775 SourceLocation RAngleLoc) {
776 if (ExportLoc.isValid())
777 Diag(ExportLoc, diag::warn_template_export_unsupported);
779 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
780 (NamedDecl**)Params, NumParams,
781 RAngleLoc);
784 static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
785 if (SS.isSet())
786 T->setQualifierInfo(static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
787 SS.getRange());
790 DeclResult
791 Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
792 SourceLocation KWLoc, CXXScopeSpec &SS,
793 IdentifierInfo *Name, SourceLocation NameLoc,
794 AttributeList *Attr,
795 TemplateParameterList *TemplateParams,
796 AccessSpecifier AS) {
797 assert(TemplateParams && TemplateParams->size() > 0 &&
798 "No template parameters");
799 assert(TUK != TUK_Reference && "Can only declare or define class templates");
800 bool Invalid = false;
802 // Check that we can declare a template here.
803 if (CheckTemplateDeclScope(S, TemplateParams))
804 return true;
806 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
807 assert(Kind != TTK_Enum && "can't build template of enumerated type");
809 // There is no such thing as an unnamed class template.
810 if (!Name) {
811 Diag(KWLoc, diag::err_template_unnamed_class);
812 return true;
815 // Find any previous declaration with this name.
816 DeclContext *SemanticContext;
817 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
818 ForRedeclaration);
819 if (SS.isNotEmpty() && !SS.isInvalid()) {
820 SemanticContext = computeDeclContext(SS, true);
821 if (!SemanticContext) {
822 // FIXME: Produce a reasonable diagnostic here
823 return true;
826 if (RequireCompleteDeclContext(SS, SemanticContext))
827 return true;
829 LookupQualifiedName(Previous, SemanticContext);
830 } else {
831 SemanticContext = CurContext;
832 LookupName(Previous, S);
835 if (Previous.isAmbiguous())
836 return true;
838 NamedDecl *PrevDecl = 0;
839 if (Previous.begin() != Previous.end())
840 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
842 // If there is a previous declaration with the same name, check
843 // whether this is a valid redeclaration.
844 ClassTemplateDecl *PrevClassTemplate
845 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
847 // We may have found the injected-class-name of a class template,
848 // class template partial specialization, or class template specialization.
849 // In these cases, grab the template that is being defined or specialized.
850 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
851 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
852 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
853 PrevClassTemplate
854 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
855 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
856 PrevClassTemplate
857 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
858 ->getSpecializedTemplate();
862 if (TUK == TUK_Friend) {
863 // C++ [namespace.memdef]p3:
864 // [...] When looking for a prior declaration of a class or a function
865 // declared as a friend, and when the name of the friend class or
866 // function is neither a qualified name nor a template-id, scopes outside
867 // the innermost enclosing namespace scope are not considered.
868 if (!SS.isSet()) {
869 DeclContext *OutermostContext = CurContext;
870 while (!OutermostContext->isFileContext())
871 OutermostContext = OutermostContext->getLookupParent();
873 if (PrevDecl &&
874 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
875 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
876 SemanticContext = PrevDecl->getDeclContext();
877 } else {
878 // Declarations in outer scopes don't matter. However, the outermost
879 // context we computed is the semantic context for our new
880 // declaration.
881 PrevDecl = PrevClassTemplate = 0;
882 SemanticContext = OutermostContext;
886 if (CurContext->isDependentContext()) {
887 // If this is a dependent context, we don't want to link the friend
888 // class template to the template in scope, because that would perform
889 // checking of the template parameter lists that can't be performed
890 // until the outer context is instantiated.
891 PrevDecl = PrevClassTemplate = 0;
893 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
894 PrevDecl = PrevClassTemplate = 0;
896 if (PrevClassTemplate) {
897 // Ensure that the template parameter lists are compatible.
898 if (!TemplateParameterListsAreEqual(TemplateParams,
899 PrevClassTemplate->getTemplateParameters(),
900 /*Complain=*/true,
901 TPL_TemplateMatch))
902 return true;
904 // C++ [temp.class]p4:
905 // In a redeclaration, partial specialization, explicit
906 // specialization or explicit instantiation of a class template,
907 // the class-key shall agree in kind with the original class
908 // template declaration (7.1.5.3).
909 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
910 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) {
911 Diag(KWLoc, diag::err_use_with_wrong_tag)
912 << Name
913 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
914 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
915 Kind = PrevRecordDecl->getTagKind();
918 // Check for redefinition of this class template.
919 if (TUK == TUK_Definition) {
920 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
921 Diag(NameLoc, diag::err_redefinition) << Name;
922 Diag(Def->getLocation(), diag::note_previous_definition);
923 // FIXME: Would it make sense to try to "forget" the previous
924 // definition, as part of error recovery?
925 return true;
928 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
929 // Maybe we will complain about the shadowed template parameter.
930 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
931 // Just pretend that we didn't see the previous declaration.
932 PrevDecl = 0;
933 } else if (PrevDecl) {
934 // C++ [temp]p5:
935 // A class template shall not have the same name as any other
936 // template, class, function, object, enumeration, enumerator,
937 // namespace, or type in the same scope (3.3), except as specified
938 // in (14.5.4).
939 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
940 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
941 return true;
944 // Check the template parameter list of this declaration, possibly
945 // merging in the template parameter list from the previous class
946 // template declaration.
947 if (CheckTemplateParameterList(TemplateParams,
948 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
949 (SS.isSet() && SemanticContext &&
950 SemanticContext->isRecord() &&
951 SemanticContext->isDependentContext())
952 ? TPC_ClassTemplateMember
953 : TPC_ClassTemplate))
954 Invalid = true;
956 if (SS.isSet()) {
957 // If the name of the template was qualified, we must be defining the
958 // template out-of-line.
959 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
960 !(TUK == TUK_Friend && CurContext->isDependentContext()))
961 Diag(NameLoc, diag::err_member_def_does_not_match)
962 << Name << SemanticContext << SS.getRange();
965 CXXRecordDecl *NewClass =
966 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc,
967 PrevClassTemplate?
968 PrevClassTemplate->getTemplatedDecl() : 0,
969 /*DelayTypeCreation=*/true);
970 SetNestedNameSpecifier(NewClass, SS);
972 ClassTemplateDecl *NewTemplate
973 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
974 DeclarationName(Name), TemplateParams,
975 NewClass, PrevClassTemplate);
976 NewClass->setDescribedClassTemplate(NewTemplate);
978 // Build the type for the class template declaration now.
979 QualType T = NewTemplate->getInjectedClassNameSpecialization();
980 T = Context.getInjectedClassNameType(NewClass, T);
981 assert(T->isDependentType() && "Class template type is not dependent?");
982 (void)T;
984 // If we are providing an explicit specialization of a member that is a
985 // class template, make a note of that.
986 if (PrevClassTemplate &&
987 PrevClassTemplate->getInstantiatedFromMemberTemplate())
988 PrevClassTemplate->setMemberSpecialization();
990 // Set the access specifier.
991 if (!Invalid && TUK != TUK_Friend)
992 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
994 // Set the lexical context of these templates
995 NewClass->setLexicalDeclContext(CurContext);
996 NewTemplate->setLexicalDeclContext(CurContext);
998 if (TUK == TUK_Definition)
999 NewClass->startDefinition();
1001 if (Attr)
1002 ProcessDeclAttributeList(S, NewClass, Attr);
1004 if (TUK != TUK_Friend)
1005 PushOnScopeChains(NewTemplate, S);
1006 else {
1007 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
1008 NewTemplate->setAccess(PrevClassTemplate->getAccess());
1009 NewClass->setAccess(PrevClassTemplate->getAccess());
1012 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
1013 PrevClassTemplate != NULL);
1015 // Friend templates are visible in fairly strange ways.
1016 if (!CurContext->isDependentContext()) {
1017 DeclContext *DC = SemanticContext->getRedeclContext();
1018 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
1019 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1020 PushOnScopeChains(NewTemplate, EnclosingScope,
1021 /* AddToContext = */ false);
1024 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
1025 NewClass->getLocation(),
1026 NewTemplate,
1027 /*FIXME:*/NewClass->getLocation());
1028 Friend->setAccess(AS_public);
1029 CurContext->addDecl(Friend);
1032 if (Invalid) {
1033 NewTemplate->setInvalidDecl();
1034 NewClass->setInvalidDecl();
1036 return NewTemplate;
1039 /// \brief Diagnose the presence of a default template argument on a
1040 /// template parameter, which is ill-formed in certain contexts.
1042 /// \returns true if the default template argument should be dropped.
1043 static bool DiagnoseDefaultTemplateArgument(Sema &S,
1044 Sema::TemplateParamListContext TPC,
1045 SourceLocation ParamLoc,
1046 SourceRange DefArgRange) {
1047 switch (TPC) {
1048 case Sema::TPC_ClassTemplate:
1049 return false;
1051 case Sema::TPC_FunctionTemplate:
1052 case Sema::TPC_FriendFunctionTemplateDefinition:
1053 // C++ [temp.param]p9:
1054 // A default template-argument shall not be specified in a
1055 // function template declaration or a function template
1056 // definition [...]
1057 // If a friend function template declaration specifies a default
1058 // template-argument, that declaration shall be a definition and shall be
1059 // the only declaration of the function template in the translation unit.
1060 // (C++98/03 doesn't have this wording; see DR226).
1061 if (!S.getLangOptions().CPlusPlus0x)
1062 S.Diag(ParamLoc,
1063 diag::ext_template_parameter_default_in_function_template)
1064 << DefArgRange;
1065 return false;
1067 case Sema::TPC_ClassTemplateMember:
1068 // C++0x [temp.param]p9:
1069 // A default template-argument shall not be specified in the
1070 // template-parameter-lists of the definition of a member of a
1071 // class template that appears outside of the member's class.
1072 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1073 << DefArgRange;
1074 return true;
1076 case Sema::TPC_FriendFunctionTemplate:
1077 // C++ [temp.param]p9:
1078 // A default template-argument shall not be specified in a
1079 // friend template declaration.
1080 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1081 << DefArgRange;
1082 return true;
1084 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1085 // for friend function templates if there is only a single
1086 // declaration (and it is a definition). Strange!
1089 return false;
1092 /// \brief Check for unexpanded parameter packs within the template parameters
1093 /// of a template template parameter, recursively.
1094 bool DiagnoseUnexpandedParameterPacks(Sema &S, TemplateTemplateParmDecl *TTP){
1095 TemplateParameterList *Params = TTP->getTemplateParameters();
1096 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1097 NamedDecl *P = Params->getParam(I);
1098 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
1099 if (S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
1100 NTTP->getTypeSourceInfo(),
1101 Sema::UPPC_NonTypeTemplateParameterType))
1102 return true;
1104 continue;
1107 if (TemplateTemplateParmDecl *InnerTTP
1108 = dyn_cast<TemplateTemplateParmDecl>(P))
1109 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1110 return true;
1113 return false;
1116 /// \brief Checks the validity of a template parameter list, possibly
1117 /// considering the template parameter list from a previous
1118 /// declaration.
1120 /// If an "old" template parameter list is provided, it must be
1121 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
1122 /// template parameter list.
1124 /// \param NewParams Template parameter list for a new template
1125 /// declaration. This template parameter list will be updated with any
1126 /// default arguments that are carried through from the previous
1127 /// template parameter list.
1129 /// \param OldParams If provided, template parameter list from a
1130 /// previous declaration of the same template. Default template
1131 /// arguments will be merged from the old template parameter list to
1132 /// the new template parameter list.
1134 /// \param TPC Describes the context in which we are checking the given
1135 /// template parameter list.
1137 /// \returns true if an error occurred, false otherwise.
1138 bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
1139 TemplateParameterList *OldParams,
1140 TemplateParamListContext TPC) {
1141 bool Invalid = false;
1143 // C++ [temp.param]p10:
1144 // The set of default template-arguments available for use with a
1145 // template declaration or definition is obtained by merging the
1146 // default arguments from the definition (if in scope) and all
1147 // declarations in scope in the same way default function
1148 // arguments are (8.3.6).
1149 bool SawDefaultArgument = false;
1150 SourceLocation PreviousDefaultArgLoc;
1152 bool SawParameterPack = false;
1153 SourceLocation ParameterPackLoc;
1155 // Dummy initialization to avoid warnings.
1156 TemplateParameterList::iterator OldParam = NewParams->end();
1157 if (OldParams)
1158 OldParam = OldParams->begin();
1160 bool RemoveDefaultArguments = false;
1161 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1162 NewParamEnd = NewParams->end();
1163 NewParam != NewParamEnd; ++NewParam) {
1164 // Variables used to diagnose redundant default arguments
1165 bool RedundantDefaultArg = false;
1166 SourceLocation OldDefaultLoc;
1167 SourceLocation NewDefaultLoc;
1169 // Variables used to diagnose missing default arguments
1170 bool MissingDefaultArg = false;
1172 // C++0x [temp.param]p11:
1173 // If a template parameter of a primary class template is a template
1174 // parameter pack, it shall be the last template parameter.
1175 if (SawParameterPack && TPC == TPC_ClassTemplate) {
1176 Diag(ParameterPackLoc,
1177 diag::err_template_param_pack_must_be_last_template_parameter);
1178 Invalid = true;
1181 if (TemplateTypeParmDecl *NewTypeParm
1182 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
1183 // Check the presence of a default argument here.
1184 if (NewTypeParm->hasDefaultArgument() &&
1185 DiagnoseDefaultTemplateArgument(*this, TPC,
1186 NewTypeParm->getLocation(),
1187 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1188 .getSourceRange()))
1189 NewTypeParm->removeDefaultArgument();
1191 // Merge default arguments for template type parameters.
1192 TemplateTypeParmDecl *OldTypeParm
1193 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
1195 if (NewTypeParm->isParameterPack()) {
1196 assert(!NewTypeParm->hasDefaultArgument() &&
1197 "Parameter packs can't have a default argument!");
1198 SawParameterPack = true;
1199 ParameterPackLoc = NewTypeParm->getLocation();
1200 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
1201 NewTypeParm->hasDefaultArgument()) {
1202 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1203 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1204 SawDefaultArgument = true;
1205 RedundantDefaultArg = true;
1206 PreviousDefaultArgLoc = NewDefaultLoc;
1207 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1208 // Merge the default argument from the old declaration to the
1209 // new declaration.
1210 SawDefaultArgument = true;
1211 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
1212 true);
1213 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1214 } else if (NewTypeParm->hasDefaultArgument()) {
1215 SawDefaultArgument = true;
1216 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1217 } else if (SawDefaultArgument)
1218 MissingDefaultArg = true;
1219 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
1220 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
1221 // Check for unexpanded parameter packs.
1222 if (DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
1223 NewNonTypeParm->getTypeSourceInfo(),
1224 UPPC_NonTypeTemplateParameterType)) {
1225 Invalid = true;
1226 continue;
1229 // Check the presence of a default argument here.
1230 if (NewNonTypeParm->hasDefaultArgument() &&
1231 DiagnoseDefaultTemplateArgument(*this, TPC,
1232 NewNonTypeParm->getLocation(),
1233 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1234 NewNonTypeParm->removeDefaultArgument();
1237 // Merge default arguments for non-type template parameters
1238 NonTypeTemplateParmDecl *OldNonTypeParm
1239 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
1240 if (NewNonTypeParm->isParameterPack()) {
1241 assert(!NewNonTypeParm->hasDefaultArgument() &&
1242 "Parameter packs can't have a default argument!");
1243 SawParameterPack = true;
1244 ParameterPackLoc = NewNonTypeParm->getLocation();
1245 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
1246 NewNonTypeParm->hasDefaultArgument()) {
1247 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1248 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1249 SawDefaultArgument = true;
1250 RedundantDefaultArg = true;
1251 PreviousDefaultArgLoc = NewDefaultLoc;
1252 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1253 // Merge the default argument from the old declaration to the
1254 // new declaration.
1255 SawDefaultArgument = true;
1256 // FIXME: We need to create a new kind of "default argument"
1257 // expression that points to a previous non-type template
1258 // parameter.
1259 NewNonTypeParm->setDefaultArgument(
1260 OldNonTypeParm->getDefaultArgument(),
1261 /*Inherited=*/ true);
1262 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1263 } else if (NewNonTypeParm->hasDefaultArgument()) {
1264 SawDefaultArgument = true;
1265 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1266 } else if (SawDefaultArgument)
1267 MissingDefaultArg = true;
1268 } else {
1269 // Check the presence of a default argument here.
1270 TemplateTemplateParmDecl *NewTemplateParm
1271 = cast<TemplateTemplateParmDecl>(*NewParam);
1273 // Check for unexpanded parameter packs, recursively.
1274 if (DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
1275 Invalid = true;
1276 continue;
1279 if (NewTemplateParm->hasDefaultArgument() &&
1280 DiagnoseDefaultTemplateArgument(*this, TPC,
1281 NewTemplateParm->getLocation(),
1282 NewTemplateParm->getDefaultArgument().getSourceRange()))
1283 NewTemplateParm->removeDefaultArgument();
1285 // Merge default arguments for template template parameters
1286 TemplateTemplateParmDecl *OldTemplateParm
1287 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
1288 if (NewTemplateParm->isParameterPack()) {
1289 assert(!NewTemplateParm->hasDefaultArgument() &&
1290 "Parameter packs can't have a default argument!");
1291 SawParameterPack = true;
1292 ParameterPackLoc = NewTemplateParm->getLocation();
1293 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
1294 NewTemplateParm->hasDefaultArgument()) {
1295 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1296 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
1297 SawDefaultArgument = true;
1298 RedundantDefaultArg = true;
1299 PreviousDefaultArgLoc = NewDefaultLoc;
1300 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1301 // Merge the default argument from the old declaration to the
1302 // new declaration.
1303 SawDefaultArgument = true;
1304 // FIXME: We need to create a new kind of "default argument" expression
1305 // that points to a previous template template parameter.
1306 NewTemplateParm->setDefaultArgument(
1307 OldTemplateParm->getDefaultArgument(),
1308 /*Inherited=*/ true);
1309 PreviousDefaultArgLoc
1310 = OldTemplateParm->getDefaultArgument().getLocation();
1311 } else if (NewTemplateParm->hasDefaultArgument()) {
1312 SawDefaultArgument = true;
1313 PreviousDefaultArgLoc
1314 = NewTemplateParm->getDefaultArgument().getLocation();
1315 } else if (SawDefaultArgument)
1316 MissingDefaultArg = true;
1319 if (RedundantDefaultArg) {
1320 // C++ [temp.param]p12:
1321 // A template-parameter shall not be given default arguments
1322 // by two different declarations in the same scope.
1323 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1324 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1325 Invalid = true;
1326 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
1327 // C++ [temp.param]p11:
1328 // If a template-parameter of a class template has a default
1329 // template-argument, each subsequent template-parameter shall either
1330 // have a default template-argument supplied or be a template parameter
1331 // pack.
1332 Diag((*NewParam)->getLocation(),
1333 diag::err_template_param_default_arg_missing);
1334 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1335 Invalid = true;
1336 RemoveDefaultArguments = true;
1339 // If we have an old template parameter list that we're merging
1340 // in, move on to the next parameter.
1341 if (OldParams)
1342 ++OldParam;
1345 // We were missing some default arguments at the end of the list, so remove
1346 // all of the default arguments.
1347 if (RemoveDefaultArguments) {
1348 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1349 NewParamEnd = NewParams->end();
1350 NewParam != NewParamEnd; ++NewParam) {
1351 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1352 TTP->removeDefaultArgument();
1353 else if (NonTypeTemplateParmDecl *NTTP
1354 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1355 NTTP->removeDefaultArgument();
1356 else
1357 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1361 return Invalid;
1364 namespace {
1366 /// A class which looks for a use of a certain level of template
1367 /// parameter.
1368 struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1369 typedef RecursiveASTVisitor<DependencyChecker> super;
1371 unsigned Depth;
1372 bool Match;
1374 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1375 NamedDecl *ND = Params->getParam(0);
1376 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1377 Depth = PD->getDepth();
1378 } else if (NonTypeTemplateParmDecl *PD =
1379 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1380 Depth = PD->getDepth();
1381 } else {
1382 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1386 bool Matches(unsigned ParmDepth) {
1387 if (ParmDepth >= Depth) {
1388 Match = true;
1389 return true;
1391 return false;
1394 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1395 return !Matches(T->getDepth());
1398 bool TraverseTemplateName(TemplateName N) {
1399 if (TemplateTemplateParmDecl *PD =
1400 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
1401 if (Matches(PD->getDepth())) return false;
1402 return super::TraverseTemplateName(N);
1405 bool VisitDeclRefExpr(DeclRefExpr *E) {
1406 if (NonTypeTemplateParmDecl *PD =
1407 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl())) {
1408 if (PD->getDepth() == Depth) {
1409 Match = true;
1410 return false;
1413 return super::VisitDeclRefExpr(E);
1418 /// Determines whether a template-id depends on the given parameter
1419 /// list.
1420 static bool
1421 DependsOnTemplateParameters(const TemplateSpecializationType *TemplateId,
1422 TemplateParameterList *Params) {
1423 DependencyChecker Checker(Params);
1424 Checker.TraverseType(QualType(TemplateId, 0));
1425 return Checker.Match;
1428 /// \brief Match the given template parameter lists to the given scope
1429 /// specifier, returning the template parameter list that applies to the
1430 /// name.
1432 /// \param DeclStartLoc the start of the declaration that has a scope
1433 /// specifier or a template parameter list.
1435 /// \param SS the scope specifier that will be matched to the given template
1436 /// parameter lists. This scope specifier precedes a qualified name that is
1437 /// being declared.
1439 /// \param ParamLists the template parameter lists, from the outermost to the
1440 /// innermost template parameter lists.
1442 /// \param NumParamLists the number of template parameter lists in ParamLists.
1444 /// \param IsFriend Whether to apply the slightly different rules for
1445 /// matching template parameters to scope specifiers in friend
1446 /// declarations.
1448 /// \param IsExplicitSpecialization will be set true if the entity being
1449 /// declared is an explicit specialization, false otherwise.
1451 /// \returns the template parameter list, if any, that corresponds to the
1452 /// name that is preceded by the scope specifier @p SS. This template
1453 /// parameter list may be have template parameters (if we're declaring a
1454 /// template) or may have no template parameters (if we're declaring a
1455 /// template specialization), or may be NULL (if we were's declaring isn't
1456 /// itself a template).
1457 TemplateParameterList *
1458 Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1459 const CXXScopeSpec &SS,
1460 TemplateParameterList **ParamLists,
1461 unsigned NumParamLists,
1462 bool IsFriend,
1463 bool &IsExplicitSpecialization,
1464 bool &Invalid) {
1465 IsExplicitSpecialization = false;
1467 // Find the template-ids that occur within the nested-name-specifier. These
1468 // template-ids will match up with the template parameter lists.
1469 llvm::SmallVector<const TemplateSpecializationType *, 4>
1470 TemplateIdsInSpecifier;
1471 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4>
1472 ExplicitSpecializationsInSpecifier;
1473 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
1474 NNS; NNS = NNS->getPrefix()) {
1475 const Type *T = NNS->getAsType();
1476 if (!T) break;
1478 // C++0x [temp.expl.spec]p17:
1479 // A member or a member template may be nested within many
1480 // enclosing class templates. In an explicit specialization for
1481 // such a member, the member declaration shall be preceded by a
1482 // template<> for each enclosing class template that is
1483 // explicitly specialized.
1485 // Following the existing practice of GNU and EDG, we allow a typedef of a
1486 // template specialization type.
1487 while (const TypedefType *TT = dyn_cast<TypedefType>(T))
1488 T = TT->getDecl()->getUnderlyingType().getTypePtr();
1490 if (const TemplateSpecializationType *SpecType
1491 = dyn_cast<TemplateSpecializationType>(T)) {
1492 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl();
1493 if (!Template)
1494 continue; // FIXME: should this be an error? probably...
1496 if (const RecordType *Record = SpecType->getAs<RecordType>()) {
1497 ClassTemplateSpecializationDecl *SpecDecl
1498 = cast<ClassTemplateSpecializationDecl>(Record->getDecl());
1499 // If the nested name specifier refers to an explicit specialization,
1500 // we don't need a template<> header.
1501 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) {
1502 ExplicitSpecializationsInSpecifier.push_back(SpecDecl);
1503 continue;
1507 TemplateIdsInSpecifier.push_back(SpecType);
1511 // Reverse the list of template-ids in the scope specifier, so that we can
1512 // more easily match up the template-ids and the template parameter lists.
1513 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end());
1515 SourceLocation FirstTemplateLoc = DeclStartLoc;
1516 if (NumParamLists)
1517 FirstTemplateLoc = ParamLists[0]->getTemplateLoc();
1519 // Match the template-ids found in the specifier to the template parameter
1520 // lists.
1521 unsigned ParamIdx = 0, TemplateIdx = 0;
1522 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size();
1523 TemplateIdx != NumTemplateIds; ++TemplateIdx) {
1524 const TemplateSpecializationType *TemplateId
1525 = TemplateIdsInSpecifier[TemplateIdx];
1526 bool DependentTemplateId = TemplateId->isDependentType();
1528 // In friend declarations we can have template-ids which don't
1529 // depend on the corresponding template parameter lists. But
1530 // assume that empty parameter lists are supposed to match this
1531 // template-id.
1532 if (IsFriend && ParamIdx < NumParamLists && ParamLists[ParamIdx]->size()) {
1533 if (!DependentTemplateId ||
1534 !DependsOnTemplateParameters(TemplateId, ParamLists[ParamIdx]))
1535 continue;
1538 if (ParamIdx >= NumParamLists) {
1539 // We have a template-id without a corresponding template parameter
1540 // list.
1542 // ...which is fine if this is a friend declaration.
1543 if (IsFriend) {
1544 IsExplicitSpecialization = true;
1545 break;
1548 if (DependentTemplateId) {
1549 // FIXME: the location information here isn't great.
1550 Diag(SS.getRange().getBegin(),
1551 diag::err_template_spec_needs_template_parameters)
1552 << QualType(TemplateId, 0)
1553 << SS.getRange();
1554 Invalid = true;
1555 } else {
1556 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header)
1557 << SS.getRange()
1558 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> ");
1559 IsExplicitSpecialization = true;
1561 return 0;
1564 // Check the template parameter list against its corresponding template-id.
1565 if (DependentTemplateId) {
1566 TemplateParameterList *ExpectedTemplateParams = 0;
1568 // Are there cases in (e.g.) friends where this won't match?
1569 if (const InjectedClassNameType *Injected
1570 = TemplateId->getAs<InjectedClassNameType>()) {
1571 CXXRecordDecl *Record = Injected->getDecl();
1572 if (ClassTemplatePartialSpecializationDecl *Partial =
1573 dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
1574 ExpectedTemplateParams = Partial->getTemplateParameters();
1575 else
1576 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1577 ->getTemplateParameters();
1580 if (ExpectedTemplateParams)
1581 TemplateParameterListsAreEqual(ParamLists[ParamIdx],
1582 ExpectedTemplateParams,
1583 true, TPL_TemplateMatch);
1585 CheckTemplateParameterList(ParamLists[ParamIdx], 0,
1586 TPC_ClassTemplateMember);
1587 } else if (ParamLists[ParamIdx]->size() > 0)
1588 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1589 diag::err_template_param_list_matches_nontemplate)
1590 << TemplateId
1591 << ParamLists[ParamIdx]->getSourceRange();
1592 else
1593 IsExplicitSpecialization = true;
1595 ++ParamIdx;
1598 // If there were at least as many template-ids as there were template
1599 // parameter lists, then there are no template parameter lists remaining for
1600 // the declaration itself.
1601 if (ParamIdx >= NumParamLists)
1602 return 0;
1604 // If there were too many template parameter lists, complain about that now.
1605 if (ParamIdx != NumParamLists - 1) {
1606 while (ParamIdx < NumParamLists - 1) {
1607 bool isExplicitSpecHeader = ParamLists[ParamIdx]->size() == 0;
1608 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1609 isExplicitSpecHeader? diag::warn_template_spec_extra_headers
1610 : diag::err_template_spec_extra_headers)
1611 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1612 ParamLists[ParamIdx]->getRAngleLoc());
1614 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) {
1615 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(),
1616 diag::note_explicit_template_spec_does_not_need_header)
1617 << ExplicitSpecializationsInSpecifier.back();
1618 ExplicitSpecializationsInSpecifier.pop_back();
1621 // We have a template parameter list with no corresponding scope, which
1622 // means that the resulting template declaration can't be instantiated
1623 // properly (we'll end up with dependent nodes when we shouldn't).
1624 if (!isExplicitSpecHeader)
1625 Invalid = true;
1627 ++ParamIdx;
1631 // Return the last template parameter list, which corresponds to the
1632 // entity being declared.
1633 return ParamLists[NumParamLists - 1];
1636 QualType Sema::CheckTemplateIdType(TemplateName Name,
1637 SourceLocation TemplateLoc,
1638 const TemplateArgumentListInfo &TemplateArgs) {
1639 TemplateDecl *Template = Name.getAsTemplateDecl();
1640 if (!Template) {
1641 // The template name does not resolve to a template, so we just
1642 // build a dependent template-id type.
1643 return Context.getTemplateSpecializationType(Name, TemplateArgs);
1646 // Check that the template argument list is well-formed for this
1647 // template.
1648 llvm::SmallVector<TemplateArgument, 4> Converted;
1649 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
1650 false, Converted))
1651 return QualType();
1653 assert((Converted.size() == Template->getTemplateParameters()->size()) &&
1654 "Converted template argument list is too short!");
1656 QualType CanonType;
1658 if (Name.isDependent() ||
1659 TemplateSpecializationType::anyDependentTemplateArguments(
1660 TemplateArgs)) {
1661 // This class template specialization is a dependent
1662 // type. Therefore, its canonical type is another class template
1663 // specialization type that contains all of the converted
1664 // arguments in canonical form. This ensures that, e.g., A<T> and
1665 // A<T, T> have identical types when A is declared as:
1667 // template<typename T, typename U = T> struct A;
1668 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
1669 CanonType = Context.getTemplateSpecializationType(CanonName,
1670 Converted.data(),
1671 Converted.size());
1673 // FIXME: CanonType is not actually the canonical type, and unfortunately
1674 // it is a TemplateSpecializationType that we will never use again.
1675 // In the future, we need to teach getTemplateSpecializationType to only
1676 // build the canonical type and return that to us.
1677 CanonType = Context.getCanonicalType(CanonType);
1679 // This might work out to be a current instantiation, in which
1680 // case the canonical type needs to be the InjectedClassNameType.
1682 // TODO: in theory this could be a simple hashtable lookup; most
1683 // changes to CurContext don't change the set of current
1684 // instantiations.
1685 if (isa<ClassTemplateDecl>(Template)) {
1686 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1687 // If we get out to a namespace, we're done.
1688 if (Ctx->isFileContext()) break;
1690 // If this isn't a record, keep looking.
1691 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
1692 if (!Record) continue;
1694 // Look for one of the two cases with InjectedClassNameTypes
1695 // and check whether it's the same template.
1696 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
1697 !Record->getDescribedClassTemplate())
1698 continue;
1700 // Fetch the injected class name type and check whether its
1701 // injected type is equal to the type we just built.
1702 QualType ICNT = Context.getTypeDeclType(Record);
1703 QualType Injected = cast<InjectedClassNameType>(ICNT)
1704 ->getInjectedSpecializationType();
1706 if (CanonType != Injected->getCanonicalTypeInternal())
1707 continue;
1709 // If so, the canonical type of this TST is the injected
1710 // class name type of the record we just found.
1711 assert(ICNT.isCanonical());
1712 CanonType = ICNT;
1713 break;
1716 } else if (ClassTemplateDecl *ClassTemplate
1717 = dyn_cast<ClassTemplateDecl>(Template)) {
1718 // Find the class template specialization declaration that
1719 // corresponds to these arguments.
1720 void *InsertPos = 0;
1721 ClassTemplateSpecializationDecl *Decl
1722 = ClassTemplate->findSpecialization(Converted.data(), Converted.size(),
1723 InsertPos);
1724 if (!Decl) {
1725 // This is the first time we have referenced this class template
1726 // specialization. Create the canonical declaration and add it to
1727 // the set of specializations.
1728 Decl = ClassTemplateSpecializationDecl::Create(Context,
1729 ClassTemplate->getTemplatedDecl()->getTagKind(),
1730 ClassTemplate->getDeclContext(),
1731 ClassTemplate->getLocation(),
1732 ClassTemplate,
1733 Converted.data(),
1734 Converted.size(), 0);
1735 ClassTemplate->AddSpecialization(Decl, InsertPos);
1736 Decl->setLexicalDeclContext(CurContext);
1739 CanonType = Context.getTypeDeclType(Decl);
1740 assert(isa<RecordType>(CanonType) &&
1741 "type of non-dependent specialization is not a RecordType");
1744 // Build the fully-sugared type for this class template
1745 // specialization, which refers back to the class template
1746 // specialization we created or found.
1747 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
1750 TypeResult
1751 Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc,
1752 SourceLocation LAngleLoc,
1753 ASTTemplateArgsPtr TemplateArgsIn,
1754 SourceLocation RAngleLoc) {
1755 TemplateName Template = TemplateD.getAsVal<TemplateName>();
1757 // Translate the parser's template argument list in our AST format.
1758 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
1759 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
1761 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
1762 TemplateArgsIn.release();
1764 if (Result.isNull())
1765 return true;
1767 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result);
1768 TemplateSpecializationTypeLoc TL
1769 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1770 TL.setTemplateNameLoc(TemplateLoc);
1771 TL.setLAngleLoc(LAngleLoc);
1772 TL.setRAngleLoc(RAngleLoc);
1773 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1774 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
1776 return CreateParsedType(Result, DI);
1779 TypeResult Sema::ActOnTagTemplateIdType(CXXScopeSpec &SS,
1780 TypeResult TypeResult,
1781 TagUseKind TUK,
1782 TypeSpecifierType TagSpec,
1783 SourceLocation TagLoc) {
1784 if (TypeResult.isInvalid())
1785 return ::TypeResult();
1787 TypeSourceInfo *DI;
1788 QualType Type = GetTypeFromParser(TypeResult.get(), &DI);
1790 // Verify the tag specifier.
1791 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1793 if (const RecordType *RT = Type->getAs<RecordType>()) {
1794 RecordDecl *D = RT->getDecl();
1796 IdentifierInfo *Id = D->getIdentifier();
1797 assert(Id && "templated class must have an identifier");
1799 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) {
1800 Diag(TagLoc, diag::err_use_with_wrong_tag)
1801 << Type
1802 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
1803 Diag(D->getLocation(), diag::note_previous_use);
1807 ElaboratedTypeKeyword Keyword
1808 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
1809 QualType ElabType = Context.getElaboratedType(Keyword, /*NNS=*/0, Type);
1811 TypeSourceInfo *ElabDI = Context.CreateTypeSourceInfo(ElabType);
1812 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(ElabDI->getTypeLoc());
1813 TL.setKeywordLoc(TagLoc);
1814 TL.setQualifierRange(SS.getRange());
1815 TL.getNamedTypeLoc().initializeFullCopy(DI->getTypeLoc());
1816 return CreateParsedType(ElabType, ElabDI);
1819 ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
1820 LookupResult &R,
1821 bool RequiresADL,
1822 const TemplateArgumentListInfo &TemplateArgs) {
1823 // FIXME: Can we do any checking at this point? I guess we could check the
1824 // template arguments that we have against the template name, if the template
1825 // name refers to a single template. That's not a terribly common case,
1826 // though.
1828 // These should be filtered out by our callers.
1829 assert(!R.empty() && "empty lookup results when building templateid");
1830 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
1832 NestedNameSpecifier *Qualifier = 0;
1833 SourceRange QualifierRange;
1834 if (SS.isSet()) {
1835 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1836 QualifierRange = SS.getRange();
1839 // We don't want lookup warnings at this point.
1840 R.suppressDiagnostics();
1842 UnresolvedLookupExpr *ULE
1843 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
1844 Qualifier, QualifierRange,
1845 R.getLookupNameInfo(),
1846 RequiresADL, TemplateArgs,
1847 R.begin(), R.end());
1849 return Owned(ULE);
1852 // We actually only call this from template instantiation.
1853 ExprResult
1854 Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
1855 const DeclarationNameInfo &NameInfo,
1856 const TemplateArgumentListInfo &TemplateArgs) {
1857 DeclContext *DC;
1858 if (!(DC = computeDeclContext(SS, false)) ||
1859 DC->isDependentContext() ||
1860 RequireCompleteDeclContext(SS, DC))
1861 return BuildDependentDeclRefExpr(SS, NameInfo, &TemplateArgs);
1863 bool MemberOfUnknownSpecialization;
1864 LookupResult R(*this, NameInfo, LookupOrdinaryName);
1865 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
1866 MemberOfUnknownSpecialization);
1868 if (R.isAmbiguous())
1869 return ExprError();
1871 if (R.empty()) {
1872 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
1873 << NameInfo.getName() << SS.getRange();
1874 return ExprError();
1877 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
1878 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
1879 << (NestedNameSpecifier*) SS.getScopeRep()
1880 << NameInfo.getName() << SS.getRange();
1881 Diag(Temp->getLocation(), diag::note_referenced_class_template);
1882 return ExprError();
1885 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
1888 /// \brief Form a dependent template name.
1890 /// This action forms a dependent template name given the template
1891 /// name and its (presumably dependent) scope specifier. For
1892 /// example, given "MetaFun::template apply", the scope specifier \p
1893 /// SS will be "MetaFun::", \p TemplateKWLoc contains the location
1894 /// of the "template" keyword, and "apply" is the \p Name.
1895 TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
1896 SourceLocation TemplateKWLoc,
1897 CXXScopeSpec &SS,
1898 UnqualifiedId &Name,
1899 ParsedType ObjectType,
1900 bool EnteringContext,
1901 TemplateTy &Result) {
1902 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent() &&
1903 !getLangOptions().CPlusPlus0x)
1904 Diag(TemplateKWLoc, diag::ext_template_outside_of_template)
1905 << FixItHint::CreateRemoval(TemplateKWLoc);
1907 DeclContext *LookupCtx = 0;
1908 if (SS.isSet())
1909 LookupCtx = computeDeclContext(SS, EnteringContext);
1910 if (!LookupCtx && ObjectType)
1911 LookupCtx = computeDeclContext(ObjectType.get());
1912 if (LookupCtx) {
1913 // C++0x [temp.names]p5:
1914 // If a name prefixed by the keyword template is not the name of
1915 // a template, the program is ill-formed. [Note: the keyword
1916 // template may not be applied to non-template members of class
1917 // templates. -end note ] [ Note: as is the case with the
1918 // typename prefix, the template prefix is allowed in cases
1919 // where it is not strictly necessary; i.e., when the
1920 // nested-name-specifier or the expression on the left of the ->
1921 // or . is not dependent on a template-parameter, or the use
1922 // does not appear in the scope of a template. -end note]
1924 // Note: C++03 was more strict here, because it banned the use of
1925 // the "template" keyword prior to a template-name that was not a
1926 // dependent name. C++ DR468 relaxed this requirement (the
1927 // "template" keyword is now permitted). We follow the C++0x
1928 // rules, even in C++03 mode with a warning, retroactively applying the DR.
1929 bool MemberOfUnknownSpecialization;
1930 TemplateNameKind TNK = isTemplateName(0, SS, TemplateKWLoc.isValid(), Name,
1931 ObjectType, EnteringContext, Result,
1932 MemberOfUnknownSpecialization);
1933 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
1934 isa<CXXRecordDecl>(LookupCtx) &&
1935 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) {
1936 // This is a dependent template. Handle it below.
1937 } else if (TNK == TNK_Non_template) {
1938 Diag(Name.getSourceRange().getBegin(),
1939 diag::err_template_kw_refers_to_non_template)
1940 << GetNameFromUnqualifiedId(Name).getName()
1941 << Name.getSourceRange()
1942 << TemplateKWLoc;
1943 return TNK_Non_template;
1944 } else {
1945 // We found something; return it.
1946 return TNK;
1950 NestedNameSpecifier *Qualifier
1951 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
1953 switch (Name.getKind()) {
1954 case UnqualifiedId::IK_Identifier:
1955 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1956 Name.Identifier));
1957 return TNK_Dependent_template_name;
1959 case UnqualifiedId::IK_OperatorFunctionId:
1960 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
1961 Name.OperatorFunctionId.Operator));
1962 return TNK_Dependent_template_name;
1964 case UnqualifiedId::IK_LiteralOperatorId:
1965 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
1967 default:
1968 break;
1971 Diag(Name.getSourceRange().getBegin(),
1972 diag::err_template_kw_refers_to_non_template)
1973 << GetNameFromUnqualifiedId(Name).getName()
1974 << Name.getSourceRange()
1975 << TemplateKWLoc;
1976 return TNK_Non_template;
1979 bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
1980 const TemplateArgumentLoc &AL,
1981 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
1982 const TemplateArgument &Arg = AL.getArgument();
1984 // Check template type parameter.
1985 switch(Arg.getKind()) {
1986 case TemplateArgument::Type:
1987 // C++ [temp.arg.type]p1:
1988 // A template-argument for a template-parameter which is a
1989 // type shall be a type-id.
1990 break;
1991 case TemplateArgument::Template: {
1992 // We have a template type parameter but the template argument
1993 // is a template without any arguments.
1994 SourceRange SR = AL.getSourceRange();
1995 TemplateName Name = Arg.getAsTemplate();
1996 Diag(SR.getBegin(), diag::err_template_missing_args)
1997 << Name << SR;
1998 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
1999 Diag(Decl->getLocation(), diag::note_template_decl_here);
2001 return true;
2003 default: {
2004 // We have a template type parameter but the template argument
2005 // is not a type.
2006 SourceRange SR = AL.getSourceRange();
2007 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
2008 Diag(Param->getLocation(), diag::note_template_param_here);
2010 return true;
2014 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
2015 return true;
2017 // Add the converted template type argument.
2018 Converted.push_back(
2019 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
2020 return false;
2023 /// \brief Substitute template arguments into the default template argument for
2024 /// the given template type parameter.
2026 /// \param SemaRef the semantic analysis object for which we are performing
2027 /// the substitution.
2029 /// \param Template the template that we are synthesizing template arguments
2030 /// for.
2032 /// \param TemplateLoc the location of the template name that started the
2033 /// template-id we are checking.
2035 /// \param RAngleLoc the location of the right angle bracket ('>') that
2036 /// terminates the template-id.
2038 /// \param Param the template template parameter whose default we are
2039 /// substituting into.
2041 /// \param Converted the list of template arguments provided for template
2042 /// parameters that precede \p Param in the template parameter list.
2044 /// \returns the substituted template argument, or NULL if an error occurred.
2045 static TypeSourceInfo *
2046 SubstDefaultTemplateArgument(Sema &SemaRef,
2047 TemplateDecl *Template,
2048 SourceLocation TemplateLoc,
2049 SourceLocation RAngleLoc,
2050 TemplateTypeParmDecl *Param,
2051 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
2052 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
2054 // If the argument type is dependent, instantiate it now based
2055 // on the previously-computed template arguments.
2056 if (ArgType->getType()->isDependentType()) {
2057 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2058 Converted.data(), Converted.size());
2060 MultiLevelTemplateArgumentList AllTemplateArgs
2061 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2063 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
2064 Template, Converted.data(),
2065 Converted.size(),
2066 SourceRange(TemplateLoc, RAngleLoc));
2068 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
2069 Param->getDefaultArgumentLoc(),
2070 Param->getDeclName());
2073 return ArgType;
2076 /// \brief Substitute template arguments into the default template argument for
2077 /// the given non-type template parameter.
2079 /// \param SemaRef the semantic analysis object for which we are performing
2080 /// the substitution.
2082 /// \param Template the template that we are synthesizing template arguments
2083 /// for.
2085 /// \param TemplateLoc the location of the template name that started the
2086 /// template-id we are checking.
2088 /// \param RAngleLoc the location of the right angle bracket ('>') that
2089 /// terminates the template-id.
2091 /// \param Param the non-type template parameter whose default we are
2092 /// substituting into.
2094 /// \param Converted the list of template arguments provided for template
2095 /// parameters that precede \p Param in the template parameter list.
2097 /// \returns the substituted template argument, or NULL if an error occurred.
2098 static ExprResult
2099 SubstDefaultTemplateArgument(Sema &SemaRef,
2100 TemplateDecl *Template,
2101 SourceLocation TemplateLoc,
2102 SourceLocation RAngleLoc,
2103 NonTypeTemplateParmDecl *Param,
2104 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
2105 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2106 Converted.data(), Converted.size());
2108 MultiLevelTemplateArgumentList AllTemplateArgs
2109 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2111 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
2112 Template, Converted.data(),
2113 Converted.size(),
2114 SourceRange(TemplateLoc, RAngleLoc));
2116 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
2119 /// \brief Substitute template arguments into the default template argument for
2120 /// the given template template parameter.
2122 /// \param SemaRef the semantic analysis object for which we are performing
2123 /// the substitution.
2125 /// \param Template the template that we are synthesizing template arguments
2126 /// for.
2128 /// \param TemplateLoc the location of the template name that started the
2129 /// template-id we are checking.
2131 /// \param RAngleLoc the location of the right angle bracket ('>') that
2132 /// terminates the template-id.
2134 /// \param Param the template template parameter whose default we are
2135 /// substituting into.
2137 /// \param Converted the list of template arguments provided for template
2138 /// parameters that precede \p Param in the template parameter list.
2140 /// \returns the substituted template argument, or NULL if an error occurred.
2141 static TemplateName
2142 SubstDefaultTemplateArgument(Sema &SemaRef,
2143 TemplateDecl *Template,
2144 SourceLocation TemplateLoc,
2145 SourceLocation RAngleLoc,
2146 TemplateTemplateParmDecl *Param,
2147 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
2148 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2149 Converted.data(), Converted.size());
2151 MultiLevelTemplateArgumentList AllTemplateArgs
2152 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2154 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
2155 Template, Converted.data(),
2156 Converted.size(),
2157 SourceRange(TemplateLoc, RAngleLoc));
2159 return SemaRef.SubstTemplateName(
2160 Param->getDefaultArgument().getArgument().getAsTemplate(),
2161 Param->getDefaultArgument().getTemplateNameLoc(),
2162 AllTemplateArgs);
2165 /// \brief If the given template parameter has a default template
2166 /// argument, substitute into that default template argument and
2167 /// return the corresponding template argument.
2168 TemplateArgumentLoc
2169 Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
2170 SourceLocation TemplateLoc,
2171 SourceLocation RAngleLoc,
2172 Decl *Param,
2173 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
2174 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
2175 if (!TypeParm->hasDefaultArgument())
2176 return TemplateArgumentLoc();
2178 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
2179 TemplateLoc,
2180 RAngleLoc,
2181 TypeParm,
2182 Converted);
2183 if (DI)
2184 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
2186 return TemplateArgumentLoc();
2189 if (NonTypeTemplateParmDecl *NonTypeParm
2190 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2191 if (!NonTypeParm->hasDefaultArgument())
2192 return TemplateArgumentLoc();
2194 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
2195 TemplateLoc,
2196 RAngleLoc,
2197 NonTypeParm,
2198 Converted);
2199 if (Arg.isInvalid())
2200 return TemplateArgumentLoc();
2202 Expr *ArgE = Arg.takeAs<Expr>();
2203 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
2206 TemplateTemplateParmDecl *TempTempParm
2207 = cast<TemplateTemplateParmDecl>(Param);
2208 if (!TempTempParm->hasDefaultArgument())
2209 return TemplateArgumentLoc();
2211 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
2212 TemplateLoc,
2213 RAngleLoc,
2214 TempTempParm,
2215 Converted);
2216 if (TName.isNull())
2217 return TemplateArgumentLoc();
2219 return TemplateArgumentLoc(TemplateArgument(TName),
2220 TempTempParm->getDefaultArgument().getTemplateQualifierRange(),
2221 TempTempParm->getDefaultArgument().getTemplateNameLoc());
2224 /// \brief Check that the given template argument corresponds to the given
2225 /// template parameter.
2227 /// \param Param The template parameter against which the argument will be
2228 /// checked.
2230 /// \param Arg The template argument.
2232 /// \param Template The template in which the template argument resides.
2234 /// \param TemplateLoc The location of the template name for the template
2235 /// whose argument list we're matching.
2237 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
2238 /// the template argument list.
2240 /// \param ArgumentPackIndex The index into the argument pack where this
2241 /// argument will be placed. Only valid if the parameter is a parameter pack.
2243 /// \param Converted The checked, converted argument will be added to the
2244 /// end of this small vector.
2246 /// \param CTAK Describes how we arrived at this particular template argument:
2247 /// explicitly written, deduced, etc.
2249 /// \returns true on error, false otherwise.
2250 bool Sema::CheckTemplateArgument(NamedDecl *Param,
2251 const TemplateArgumentLoc &Arg,
2252 NamedDecl *Template,
2253 SourceLocation TemplateLoc,
2254 SourceLocation RAngleLoc,
2255 unsigned ArgumentPackIndex,
2256 llvm::SmallVectorImpl<TemplateArgument> &Converted,
2257 CheckTemplateArgumentKind CTAK) {
2258 // Check template type parameters.
2259 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2260 return CheckTemplateTypeArgument(TTP, Arg, Converted);
2262 // Check non-type template parameters.
2263 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2264 // Do substitution on the type of the non-type template parameter
2265 // with the template arguments we've seen thus far. But if the
2266 // template has a dependent context then we cannot substitute yet.
2267 QualType NTTPType = NTTP->getType();
2268 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
2269 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
2271 if (NTTPType->isDependentType() &&
2272 !isa<TemplateTemplateParmDecl>(Template) &&
2273 !Template->getDeclContext()->isDependentContext()) {
2274 // Do substitution on the type of the non-type template parameter.
2275 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2276 NTTP, Converted.data(), Converted.size(),
2277 SourceRange(TemplateLoc, RAngleLoc));
2279 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2280 Converted.data(), Converted.size());
2281 NTTPType = SubstType(NTTPType,
2282 MultiLevelTemplateArgumentList(TemplateArgs),
2283 NTTP->getLocation(),
2284 NTTP->getDeclName());
2285 // If that worked, check the non-type template parameter type
2286 // for validity.
2287 if (!NTTPType.isNull())
2288 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2289 NTTP->getLocation());
2290 if (NTTPType.isNull())
2291 return true;
2294 switch (Arg.getArgument().getKind()) {
2295 case TemplateArgument::Null:
2296 assert(false && "Should never see a NULL template argument here");
2297 return true;
2299 case TemplateArgument::Expression: {
2300 Expr *E = Arg.getArgument().getAsExpr();
2301 TemplateArgument Result;
2302 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK))
2303 return true;
2305 Converted.push_back(Result);
2306 break;
2309 case TemplateArgument::Declaration:
2310 case TemplateArgument::Integral:
2311 // We've already checked this template argument, so just copy
2312 // it to the list of converted arguments.
2313 Converted.push_back(Arg.getArgument());
2314 break;
2316 case TemplateArgument::Template:
2317 case TemplateArgument::TemplateExpansion:
2318 // We were given a template template argument. It may not be ill-formed;
2319 // see below.
2320 if (DependentTemplateName *DTN
2321 = Arg.getArgument().getAsTemplateOrTemplatePattern()
2322 .getAsDependentTemplateName()) {
2323 // We have a template argument such as \c T::template X, which we
2324 // parsed as a template template argument. However, since we now
2325 // know that we need a non-type template argument, convert this
2326 // template name into an expression.
2328 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
2329 Arg.getTemplateNameLoc());
2331 Expr *E = DependentScopeDeclRefExpr::Create(Context,
2332 DTN->getQualifier(),
2333 Arg.getTemplateQualifierRange(),
2334 NameInfo);
2336 // If we parsed the template argument as a pack expansion, create a
2337 // pack expansion expression.
2338 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
2339 ExprResult Expansion = ActOnPackExpansion(E,
2340 Arg.getTemplateEllipsisLoc());
2341 if (Expansion.isInvalid())
2342 return true;
2344 E = Expansion.get();
2347 TemplateArgument Result;
2348 if (CheckTemplateArgument(NTTP, NTTPType, E, Result))
2349 return true;
2351 Converted.push_back(Result);
2352 break;
2355 // We have a template argument that actually does refer to a class
2356 // template, template alias, or template template parameter, and
2357 // therefore cannot be a non-type template argument.
2358 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2359 << Arg.getSourceRange();
2361 Diag(Param->getLocation(), diag::note_template_param_here);
2362 return true;
2364 case TemplateArgument::Type: {
2365 // We have a non-type template parameter but the template
2366 // argument is a type.
2368 // C++ [temp.arg]p2:
2369 // In a template-argument, an ambiguity between a type-id and
2370 // an expression is resolved to a type-id, regardless of the
2371 // form of the corresponding template-parameter.
2373 // We warn specifically about this case, since it can be rather
2374 // confusing for users.
2375 QualType T = Arg.getArgument().getAsType();
2376 SourceRange SR = Arg.getSourceRange();
2377 if (T->isFunctionType())
2378 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2379 else
2380 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2381 Diag(Param->getLocation(), diag::note_template_param_here);
2382 return true;
2385 case TemplateArgument::Pack:
2386 llvm_unreachable("Caller must expand template argument packs");
2387 break;
2390 return false;
2394 // Check template template parameters.
2395 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2397 // Substitute into the template parameter list of the template
2398 // template parameter, since previously-supplied template arguments
2399 // may appear within the template template parameter.
2401 // Set up a template instantiation context.
2402 LocalInstantiationScope Scope(*this);
2403 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2404 TempParm, Converted.data(), Converted.size(),
2405 SourceRange(TemplateLoc, RAngleLoc));
2407 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2408 Converted.data(), Converted.size());
2409 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2410 SubstDecl(TempParm, CurContext,
2411 MultiLevelTemplateArgumentList(TemplateArgs)));
2412 if (!TempParm)
2413 return true;
2416 switch (Arg.getArgument().getKind()) {
2417 case TemplateArgument::Null:
2418 assert(false && "Should never see a NULL template argument here");
2419 return true;
2421 case TemplateArgument::Template:
2422 case TemplateArgument::TemplateExpansion:
2423 if (CheckTemplateArgument(TempParm, Arg))
2424 return true;
2426 Converted.push_back(Arg.getArgument());
2427 break;
2429 case TemplateArgument::Expression:
2430 case TemplateArgument::Type:
2431 // We have a template template parameter but the template
2432 // argument does not refer to a template.
2433 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template);
2434 return true;
2436 case TemplateArgument::Declaration:
2437 llvm_unreachable(
2438 "Declaration argument with template template parameter");
2439 break;
2440 case TemplateArgument::Integral:
2441 llvm_unreachable(
2442 "Integral argument with template template parameter");
2443 break;
2445 case TemplateArgument::Pack:
2446 llvm_unreachable("Caller must expand template argument packs");
2447 break;
2450 return false;
2453 /// \brief Check that the given template argument list is well-formed
2454 /// for specializing the given template.
2455 bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2456 SourceLocation TemplateLoc,
2457 const TemplateArgumentListInfo &TemplateArgs,
2458 bool PartialTemplateArgs,
2459 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
2460 TemplateParameterList *Params = Template->getTemplateParameters();
2461 unsigned NumParams = Params->size();
2462 unsigned NumArgs = TemplateArgs.size();
2463 bool Invalid = false;
2465 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2467 bool HasParameterPack =
2468 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
2470 if ((NumArgs > NumParams && !HasParameterPack) ||
2471 (NumArgs < Params->getMinRequiredArguments() &&
2472 !PartialTemplateArgs)) {
2473 // FIXME: point at either the first arg beyond what we can handle,
2474 // or the '>', depending on whether we have too many or too few
2475 // arguments.
2476 SourceRange Range;
2477 if (NumArgs > NumParams)
2478 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
2479 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2480 << (NumArgs > NumParams)
2481 << (isa<ClassTemplateDecl>(Template)? 0 :
2482 isa<FunctionTemplateDecl>(Template)? 1 :
2483 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2484 << Template << Range;
2485 Diag(Template->getLocation(), diag::note_template_decl_here)
2486 << Params->getSourceRange();
2487 Invalid = true;
2490 // C++ [temp.arg]p1:
2491 // [...] The type and form of each template-argument specified in
2492 // a template-id shall match the type and form specified for the
2493 // corresponding parameter declared by the template in its
2494 // template-parameter-list.
2495 llvm::SmallVector<TemplateArgument, 2> ArgumentPack;
2496 TemplateParameterList::iterator Param = Params->begin(),
2497 ParamEnd = Params->end();
2498 unsigned ArgIdx = 0;
2499 LocalInstantiationScope InstScope(*this, true);
2500 while (Param != ParamEnd) {
2501 if (ArgIdx > NumArgs && PartialTemplateArgs)
2502 break;
2504 if (ArgIdx < NumArgs) {
2505 // If we have an expanded parameter pack, make sure we don't have too
2506 // many arguments.
2507 if (NonTypeTemplateParmDecl *NTTP
2508 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2509 if (NTTP->isExpandedParameterPack() &&
2510 ArgumentPack.size() >= NTTP->getNumExpansionTypes()) {
2511 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2512 << true
2513 << (isa<ClassTemplateDecl>(Template)? 0 :
2514 isa<FunctionTemplateDecl>(Template)? 1 :
2515 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2516 << Template;
2517 Diag(Template->getLocation(), diag::note_template_decl_here)
2518 << Params->getSourceRange();
2519 return true;
2523 // Check the template argument we were given.
2524 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2525 TemplateLoc, RAngleLoc,
2526 ArgumentPack.size(), Converted))
2527 return true;
2529 if ((*Param)->isTemplateParameterPack()) {
2530 // The template parameter was a template parameter pack, so take the
2531 // deduced argument and place it on the argument pack. Note that we
2532 // stay on the same template parameter so that we can deduce more
2533 // arguments.
2534 ArgumentPack.push_back(Converted.back());
2535 Converted.pop_back();
2536 } else {
2537 // Move to the next template parameter.
2538 ++Param;
2540 ++ArgIdx;
2541 continue;
2544 // If we have a template parameter pack with no more corresponding
2545 // arguments, just break out now and we'll fill in the argument pack below.
2546 if ((*Param)->isTemplateParameterPack())
2547 break;
2549 // We have a default template argument that we will use.
2550 TemplateArgumentLoc Arg;
2552 // Retrieve the default template argument from the template
2553 // parameter. For each kind of template parameter, we substitute the
2554 // template arguments provided thus far and any "outer" template arguments
2555 // (when the template parameter was part of a nested template) into
2556 // the default argument.
2557 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2558 if (!TTP->hasDefaultArgument()) {
2559 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2560 break;
2563 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
2564 Template,
2565 TemplateLoc,
2566 RAngleLoc,
2567 TTP,
2568 Converted);
2569 if (!ArgType)
2570 return true;
2572 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2573 ArgType);
2574 } else if (NonTypeTemplateParmDecl *NTTP
2575 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2576 if (!NTTP->hasDefaultArgument()) {
2577 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2578 break;
2581 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
2582 TemplateLoc,
2583 RAngleLoc,
2584 NTTP,
2585 Converted);
2586 if (E.isInvalid())
2587 return true;
2589 Expr *Ex = E.takeAs<Expr>();
2590 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2591 } else {
2592 TemplateTemplateParmDecl *TempParm
2593 = cast<TemplateTemplateParmDecl>(*Param);
2595 if (!TempParm->hasDefaultArgument()) {
2596 assert((Invalid || PartialTemplateArgs) && "Missing default argument");
2597 break;
2600 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2601 TemplateLoc,
2602 RAngleLoc,
2603 TempParm,
2604 Converted);
2605 if (Name.isNull())
2606 return true;
2608 Arg = TemplateArgumentLoc(TemplateArgument(Name),
2609 TempParm->getDefaultArgument().getTemplateQualifierRange(),
2610 TempParm->getDefaultArgument().getTemplateNameLoc());
2613 // Introduce an instantiation record that describes where we are using
2614 // the default template argument.
2615 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2616 Converted.data(), Converted.size(),
2617 SourceRange(TemplateLoc, RAngleLoc));
2619 // Check the default template argument.
2620 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
2621 RAngleLoc, 0, Converted))
2622 return true;
2624 // Move to the next template parameter and argument.
2625 ++Param;
2626 ++ArgIdx;
2629 // Form argument packs for each of the parameter packs remaining.
2630 while (Param != ParamEnd) {
2631 // If we're checking a partial list of template arguments, don't fill
2632 // in arguments for non-template parameter packs.
2634 if ((*Param)->isTemplateParameterPack()) {
2635 if (PartialTemplateArgs && ArgumentPack.empty()) {
2636 Converted.push_back(TemplateArgument());
2637 } else if (ArgumentPack.empty())
2638 Converted.push_back(TemplateArgument(0, 0));
2639 else {
2640 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
2641 ArgumentPack.data(),
2642 ArgumentPack.size()));
2643 ArgumentPack.clear();
2647 ++Param;
2650 return Invalid;
2653 namespace {
2654 class UnnamedLocalNoLinkageFinder
2655 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
2657 Sema &S;
2658 SourceRange SR;
2660 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
2662 public:
2663 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
2665 bool Visit(QualType T) {
2666 return inherited::Visit(T.getTypePtr());
2669 #define TYPE(Class, Parent) \
2670 bool Visit##Class##Type(const Class##Type *);
2671 #define ABSTRACT_TYPE(Class, Parent) \
2672 bool Visit##Class##Type(const Class##Type *) { return false; }
2673 #define NON_CANONICAL_TYPE(Class, Parent) \
2674 bool Visit##Class##Type(const Class##Type *) { return false; }
2675 #include "clang/AST/TypeNodes.def"
2677 bool VisitTagDecl(const TagDecl *Tag);
2678 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
2682 bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
2683 return false;
2686 bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
2687 return Visit(T->getElementType());
2690 bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
2691 return Visit(T->getPointeeType());
2694 bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
2695 const BlockPointerType* T) {
2696 return Visit(T->getPointeeType());
2699 bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
2700 const LValueReferenceType* T) {
2701 return Visit(T->getPointeeType());
2704 bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
2705 const RValueReferenceType* T) {
2706 return Visit(T->getPointeeType());
2709 bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
2710 const MemberPointerType* T) {
2711 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
2714 bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
2715 const ConstantArrayType* T) {
2716 return Visit(T->getElementType());
2719 bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
2720 const IncompleteArrayType* T) {
2721 return Visit(T->getElementType());
2724 bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
2725 const VariableArrayType* T) {
2726 return Visit(T->getElementType());
2729 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
2730 const DependentSizedArrayType* T) {
2731 return Visit(T->getElementType());
2734 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
2735 const DependentSizedExtVectorType* T) {
2736 return Visit(T->getElementType());
2739 bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
2740 return Visit(T->getElementType());
2743 bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
2744 return Visit(T->getElementType());
2747 bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
2748 const FunctionProtoType* T) {
2749 for (FunctionProtoType::arg_type_iterator A = T->arg_type_begin(),
2750 AEnd = T->arg_type_end();
2751 A != AEnd; ++A) {
2752 if (Visit(*A))
2753 return true;
2756 return Visit(T->getResultType());
2759 bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
2760 const FunctionNoProtoType* T) {
2761 return Visit(T->getResultType());
2764 bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
2765 const UnresolvedUsingType*) {
2766 return false;
2769 bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
2770 return false;
2773 bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
2774 return Visit(T->getUnderlyingType());
2777 bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
2778 return false;
2781 bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
2782 return VisitTagDecl(T->getDecl());
2785 bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
2786 return VisitTagDecl(T->getDecl());
2789 bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
2790 const TemplateTypeParmType*) {
2791 return false;
2794 bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
2795 const SubstTemplateTypeParmPackType *) {
2796 return false;
2799 bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
2800 const TemplateSpecializationType*) {
2801 return false;
2804 bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
2805 const InjectedClassNameType* T) {
2806 return VisitTagDecl(T->getDecl());
2809 bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
2810 const DependentNameType* T) {
2811 return VisitNestedNameSpecifier(T->getQualifier());
2814 bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
2815 const DependentTemplateSpecializationType* T) {
2816 return VisitNestedNameSpecifier(T->getQualifier());
2819 bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
2820 const PackExpansionType* T) {
2821 return Visit(T->getPattern());
2824 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
2825 return false;
2828 bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
2829 const ObjCInterfaceType *) {
2830 return false;
2833 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
2834 const ObjCObjectPointerType *) {
2835 return false;
2838 bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
2839 if (Tag->getDeclContext()->isFunctionOrMethod()) {
2840 S.Diag(SR.getBegin(), diag::ext_template_arg_local_type)
2841 << S.Context.getTypeDeclType(Tag) << SR;
2842 return true;
2845 if (!Tag->getDeclName() && !Tag->getTypedefForAnonDecl()) {
2846 S.Diag(SR.getBegin(), diag::ext_template_arg_unnamed_type) << SR;
2847 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
2848 return true;
2851 return false;
2854 bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
2855 NestedNameSpecifier *NNS) {
2856 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
2857 return true;
2859 switch (NNS->getKind()) {
2860 case NestedNameSpecifier::Identifier:
2861 case NestedNameSpecifier::Namespace:
2862 case NestedNameSpecifier::Global:
2863 return false;
2865 case NestedNameSpecifier::TypeSpec:
2866 case NestedNameSpecifier::TypeSpecWithTemplate:
2867 return Visit(QualType(NNS->getAsType(), 0));
2869 return false;
2873 /// \brief Check a template argument against its corresponding
2874 /// template type parameter.
2876 /// This routine implements the semantics of C++ [temp.arg.type]. It
2877 /// returns true if an error occurred, and false otherwise.
2878 bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
2879 TypeSourceInfo *ArgInfo) {
2880 assert(ArgInfo && "invalid TypeSourceInfo");
2881 QualType Arg = ArgInfo->getType();
2882 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
2884 if (Arg->isVariablyModifiedType()) {
2885 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
2886 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
2887 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
2890 // C++03 [temp.arg.type]p2:
2891 // A local type, a type with no linkage, an unnamed type or a type
2892 // compounded from any of these types shall not be used as a
2893 // template-argument for a template type-parameter.
2895 // C++0x allows these, and even in C++03 we allow them as an extension with
2896 // a warning.
2897 if (!LangOpts.CPlusPlus0x && Arg->hasUnnamedOrLocalType()) {
2898 UnnamedLocalNoLinkageFinder Finder(*this, SR);
2899 (void)Finder.Visit(Context.getCanonicalType(Arg));
2902 return false;
2905 /// \brief Checks whether the given template argument is the address
2906 /// of an object or function according to C++ [temp.arg.nontype]p1.
2907 static bool
2908 CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
2909 NonTypeTemplateParmDecl *Param,
2910 QualType ParamType,
2911 Expr *ArgIn,
2912 TemplateArgument &Converted) {
2913 bool Invalid = false;
2914 Expr *Arg = ArgIn;
2915 QualType ArgType = Arg->getType();
2917 // See through any implicit casts we added to fix the type.
2918 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
2919 Arg = Cast->getSubExpr();
2921 // C++ [temp.arg.nontype]p1:
2923 // A template-argument for a non-type, non-template
2924 // template-parameter shall be one of: [...]
2926 // -- the address of an object or function with external
2927 // linkage, including function templates and function
2928 // template-ids but excluding non-static class members,
2929 // expressed as & id-expression where the & is optional if
2930 // the name refers to a function or array, or if the
2931 // corresponding template-parameter is a reference; or
2932 DeclRefExpr *DRE = 0;
2934 // In C++98/03 mode, give an extension warning on any extra parentheses.
2935 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
2936 bool ExtraParens = false;
2937 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
2938 if (!Invalid && !ExtraParens && !S.getLangOptions().CPlusPlus0x) {
2939 S.Diag(Arg->getSourceRange().getBegin(),
2940 diag::ext_template_arg_extra_parens)
2941 << Arg->getSourceRange();
2942 ExtraParens = true;
2945 Arg = Parens->getSubExpr();
2948 bool AddressTaken = false;
2949 SourceLocation AddrOpLoc;
2950 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
2951 if (UnOp->getOpcode() == UO_AddrOf) {
2952 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
2953 AddressTaken = true;
2954 AddrOpLoc = UnOp->getOperatorLoc();
2956 } else
2957 DRE = dyn_cast<DeclRefExpr>(Arg);
2959 if (!DRE) {
2960 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
2961 << Arg->getSourceRange();
2962 S.Diag(Param->getLocation(), diag::note_template_param_here);
2963 return true;
2966 // Stop checking the precise nature of the argument if it is value dependent,
2967 // it should be checked when instantiated.
2968 if (Arg->isValueDependent()) {
2969 Converted = TemplateArgument(ArgIn);
2970 return false;
2973 if (!isa<ValueDecl>(DRE->getDecl())) {
2974 S.Diag(Arg->getSourceRange().getBegin(),
2975 diag::err_template_arg_not_object_or_func_form)
2976 << Arg->getSourceRange();
2977 S.Diag(Param->getLocation(), diag::note_template_param_here);
2978 return true;
2981 NamedDecl *Entity = 0;
2983 // Cannot refer to non-static data members
2984 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
2985 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
2986 << Field << Arg->getSourceRange();
2987 S.Diag(Param->getLocation(), diag::note_template_param_here);
2988 return true;
2991 // Cannot refer to non-static member functions
2992 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
2993 if (!Method->isStatic()) {
2994 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
2995 << Method << Arg->getSourceRange();
2996 S.Diag(Param->getLocation(), diag::note_template_param_here);
2997 return true;
3000 // Functions must have external linkage.
3001 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
3002 if (!isExternalLinkage(Func->getLinkage())) {
3003 S.Diag(Arg->getSourceRange().getBegin(),
3004 diag::err_template_arg_function_not_extern)
3005 << Func << Arg->getSourceRange();
3006 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
3007 << true;
3008 return true;
3011 // Okay: we've named a function with external linkage.
3012 Entity = Func;
3014 // If the template parameter has pointer type, the function decays.
3015 if (ParamType->isPointerType() && !AddressTaken)
3016 ArgType = S.Context.getPointerType(Func->getType());
3017 else if (AddressTaken && ParamType->isReferenceType()) {
3018 // If we originally had an address-of operator, but the
3019 // parameter has reference type, complain and (if things look
3020 // like they will work) drop the address-of operator.
3021 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
3022 ParamType.getNonReferenceType())) {
3023 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
3024 << ParamType;
3025 S.Diag(Param->getLocation(), diag::note_template_param_here);
3026 return true;
3029 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
3030 << ParamType
3031 << FixItHint::CreateRemoval(AddrOpLoc);
3032 S.Diag(Param->getLocation(), diag::note_template_param_here);
3034 ArgType = Func->getType();
3036 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
3037 if (!isExternalLinkage(Var->getLinkage())) {
3038 S.Diag(Arg->getSourceRange().getBegin(),
3039 diag::err_template_arg_object_not_extern)
3040 << Var << Arg->getSourceRange();
3041 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
3042 << true;
3043 return true;
3046 // A value of reference type is not an object.
3047 if (Var->getType()->isReferenceType()) {
3048 S.Diag(Arg->getSourceRange().getBegin(),
3049 diag::err_template_arg_reference_var)
3050 << Var->getType() << Arg->getSourceRange();
3051 S.Diag(Param->getLocation(), diag::note_template_param_here);
3052 return true;
3055 // Okay: we've named an object with external linkage
3056 Entity = Var;
3058 // If the template parameter has pointer type, we must have taken
3059 // the address of this object.
3060 if (ParamType->isReferenceType()) {
3061 if (AddressTaken) {
3062 // If we originally had an address-of operator, but the
3063 // parameter has reference type, complain and (if things look
3064 // like they will work) drop the address-of operator.
3065 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
3066 ParamType.getNonReferenceType())) {
3067 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
3068 << ParamType;
3069 S.Diag(Param->getLocation(), diag::note_template_param_here);
3070 return true;
3073 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
3074 << ParamType
3075 << FixItHint::CreateRemoval(AddrOpLoc);
3076 S.Diag(Param->getLocation(), diag::note_template_param_here);
3078 ArgType = Var->getType();
3080 } else if (!AddressTaken && ParamType->isPointerType()) {
3081 if (Var->getType()->isArrayType()) {
3082 // Array-to-pointer decay.
3083 ArgType = S.Context.getArrayDecayedType(Var->getType());
3084 } else {
3085 // If the template parameter has pointer type but the address of
3086 // this object was not taken, complain and (possibly) recover by
3087 // taking the address of the entity.
3088 ArgType = S.Context.getPointerType(Var->getType());
3089 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
3090 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
3091 << ParamType;
3092 S.Diag(Param->getLocation(), diag::note_template_param_here);
3093 return true;
3096 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
3097 << ParamType
3098 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
3100 S.Diag(Param->getLocation(), diag::note_template_param_here);
3103 } else {
3104 // We found something else, but we don't know specifically what it is.
3105 S.Diag(Arg->getSourceRange().getBegin(),
3106 diag::err_template_arg_not_object_or_func)
3107 << Arg->getSourceRange();
3108 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
3109 return true;
3112 if (ParamType->isPointerType() &&
3113 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
3114 S.IsQualificationConversion(ArgType, ParamType, false)) {
3115 // For pointer-to-object types, qualification conversions are
3116 // permitted.
3117 } else {
3118 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
3119 if (!ParamRef->getPointeeType()->isFunctionType()) {
3120 // C++ [temp.arg.nontype]p5b3:
3121 // For a non-type template-parameter of type reference to
3122 // object, no conversions apply. The type referred to by the
3123 // reference may be more cv-qualified than the (otherwise
3124 // identical) type of the template- argument. The
3125 // template-parameter is bound directly to the
3126 // template-argument, which shall be an lvalue.
3128 // FIXME: Other qualifiers?
3129 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
3130 unsigned ArgQuals = ArgType.getCVRQualifiers();
3132 if ((ParamQuals | ArgQuals) != ParamQuals) {
3133 S.Diag(Arg->getSourceRange().getBegin(),
3134 diag::err_template_arg_ref_bind_ignores_quals)
3135 << ParamType << Arg->getType()
3136 << Arg->getSourceRange();
3137 S.Diag(Param->getLocation(), diag::note_template_param_here);
3138 return true;
3143 // At this point, the template argument refers to an object or
3144 // function with external linkage. We now need to check whether the
3145 // argument and parameter types are compatible.
3146 if (!S.Context.hasSameUnqualifiedType(ArgType,
3147 ParamType.getNonReferenceType())) {
3148 // We can't perform this conversion or binding.
3149 if (ParamType->isReferenceType())
3150 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
3151 << ParamType << Arg->getType() << Arg->getSourceRange();
3152 else
3153 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
3154 << Arg->getType() << ParamType << Arg->getSourceRange();
3155 S.Diag(Param->getLocation(), diag::note_template_param_here);
3156 return true;
3160 // Create the template argument.
3161 Converted = TemplateArgument(Entity->getCanonicalDecl());
3162 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
3163 return false;
3166 /// \brief Checks whether the given template argument is a pointer to
3167 /// member constant according to C++ [temp.arg.nontype]p1.
3168 bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
3169 TemplateArgument &Converted) {
3170 bool Invalid = false;
3172 // See through any implicit casts we added to fix the type.
3173 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
3174 Arg = Cast->getSubExpr();
3176 // C++ [temp.arg.nontype]p1:
3178 // A template-argument for a non-type, non-template
3179 // template-parameter shall be one of: [...]
3181 // -- a pointer to member expressed as described in 5.3.1.
3182 DeclRefExpr *DRE = 0;
3184 // In C++98/03 mode, give an extension warning on any extra parentheses.
3185 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
3186 bool ExtraParens = false;
3187 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
3188 if (!Invalid && !ExtraParens && !getLangOptions().CPlusPlus0x) {
3189 Diag(Arg->getSourceRange().getBegin(),
3190 diag::ext_template_arg_extra_parens)
3191 << Arg->getSourceRange();
3192 ExtraParens = true;
3195 Arg = Parens->getSubExpr();
3198 // A pointer-to-member constant written &Class::member.
3199 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
3200 if (UnOp->getOpcode() == UO_AddrOf) {
3201 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
3202 if (DRE && !DRE->getQualifier())
3203 DRE = 0;
3206 // A constant of pointer-to-member type.
3207 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
3208 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
3209 if (VD->getType()->isMemberPointerType()) {
3210 if (isa<NonTypeTemplateParmDecl>(VD) ||
3211 (isa<VarDecl>(VD) &&
3212 Context.getCanonicalType(VD->getType()).isConstQualified())) {
3213 if (Arg->isTypeDependent() || Arg->isValueDependent())
3214 Converted = TemplateArgument(Arg);
3215 else
3216 Converted = TemplateArgument(VD->getCanonicalDecl());
3217 return Invalid;
3222 DRE = 0;
3225 if (!DRE)
3226 return Diag(Arg->getSourceRange().getBegin(),
3227 diag::err_template_arg_not_pointer_to_member_form)
3228 << Arg->getSourceRange();
3230 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
3231 assert((isa<FieldDecl>(DRE->getDecl()) ||
3232 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
3233 "Only non-static member pointers can make it here");
3235 // Okay: this is the address of a non-static member, and therefore
3236 // a member pointer constant.
3237 if (Arg->isTypeDependent() || Arg->isValueDependent())
3238 Converted = TemplateArgument(Arg);
3239 else
3240 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
3241 return Invalid;
3244 // We found something else, but we don't know specifically what it is.
3245 Diag(Arg->getSourceRange().getBegin(),
3246 diag::err_template_arg_not_pointer_to_member_form)
3247 << Arg->getSourceRange();
3248 Diag(DRE->getDecl()->getLocation(),
3249 diag::note_template_arg_refers_here);
3250 return true;
3253 /// \brief Check a template argument against its corresponding
3254 /// non-type template parameter.
3256 /// This routine implements the semantics of C++ [temp.arg.nontype].
3257 /// It returns true if an error occurred, and false otherwise. \p
3258 /// InstantiatedParamType is the type of the non-type template
3259 /// parameter after it has been instantiated.
3261 /// If no error was detected, Converted receives the converted template argument.
3262 bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
3263 QualType InstantiatedParamType, Expr *&Arg,
3264 TemplateArgument &Converted,
3265 CheckTemplateArgumentKind CTAK) {
3266 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
3268 // If either the parameter has a dependent type or the argument is
3269 // type-dependent, there's nothing we can check now.
3270 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
3271 // FIXME: Produce a cloned, canonical expression?
3272 Converted = TemplateArgument(Arg);
3273 return false;
3276 // C++ [temp.arg.nontype]p5:
3277 // The following conversions are performed on each expression used
3278 // as a non-type template-argument. If a non-type
3279 // template-argument cannot be converted to the type of the
3280 // corresponding template-parameter then the program is
3281 // ill-formed.
3283 // -- for a non-type template-parameter of integral or
3284 // enumeration type, integral promotions (4.5) and integral
3285 // conversions (4.7) are applied.
3286 QualType ParamType = InstantiatedParamType;
3287 QualType ArgType = Arg->getType();
3288 if (ParamType->isIntegralOrEnumerationType()) {
3289 // C++ [temp.arg.nontype]p1:
3290 // A template-argument for a non-type, non-template
3291 // template-parameter shall be one of:
3293 // -- an integral constant-expression of integral or enumeration
3294 // type; or
3295 // -- the name of a non-type template-parameter; or
3296 SourceLocation NonConstantLoc;
3297 llvm::APSInt Value;
3298 if (!ArgType->isIntegralOrEnumerationType()) {
3299 Diag(Arg->getSourceRange().getBegin(),
3300 diag::err_template_arg_not_integral_or_enumeral)
3301 << ArgType << Arg->getSourceRange();
3302 Diag(Param->getLocation(), diag::note_template_param_here);
3303 return true;
3304 } else if (!Arg->isValueDependent() &&
3305 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
3306 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
3307 << ArgType << Arg->getSourceRange();
3308 return true;
3311 // From here on out, all we care about are the unqualified forms
3312 // of the parameter and argument types.
3313 ParamType = ParamType.getUnqualifiedType();
3314 ArgType = ArgType.getUnqualifiedType();
3316 // Try to convert the argument to the parameter's type.
3317 if (Context.hasSameType(ParamType, ArgType)) {
3318 // Okay: no conversion necessary
3319 } else if (CTAK == CTAK_Deduced) {
3320 // C++ [temp.deduct.type]p17:
3321 // If, in the declaration of a function template with a non-type
3322 // template-parameter, the non-type template- parameter is used
3323 // in an expression in the function parameter-list and, if the
3324 // corresponding template-argument is deduced, the
3325 // template-argument type shall match the type of the
3326 // template-parameter exactly, except that a template-argument
3327 // deduced from an array bound may be of any integral type.
3328 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
3329 << ArgType << ParamType;
3330 Diag(Param->getLocation(), diag::note_template_param_here);
3331 return true;
3332 } else if (ParamType->isBooleanType()) {
3333 // This is an integral-to-boolean conversion.
3334 ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean);
3335 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
3336 !ParamType->isEnumeralType()) {
3337 // This is an integral promotion or conversion.
3338 ImpCastExprToType(Arg, ParamType, CK_IntegralCast);
3339 } else {
3340 // We can't perform this conversion.
3341 Diag(Arg->getSourceRange().getBegin(),
3342 diag::err_template_arg_not_convertible)
3343 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
3344 Diag(Param->getLocation(), diag::note_template_param_here);
3345 return true;
3348 QualType IntegerType = Context.getCanonicalType(ParamType);
3349 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
3350 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
3352 if (!Arg->isValueDependent()) {
3353 llvm::APSInt OldValue = Value;
3355 // Coerce the template argument's value to the value it will have
3356 // based on the template parameter's type.
3357 unsigned AllowedBits = Context.getTypeSize(IntegerType);
3358 if (Value.getBitWidth() != AllowedBits)
3359 Value = Value.extOrTrunc(AllowedBits);
3360 Value.setIsSigned(IntegerType->isSignedIntegerType());
3362 // Complain if an unsigned parameter received a negative value.
3363 if (IntegerType->isUnsignedIntegerType()
3364 && (OldValue.isSigned() && OldValue.isNegative())) {
3365 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
3366 << OldValue.toString(10) << Value.toString(10) << Param->getType()
3367 << Arg->getSourceRange();
3368 Diag(Param->getLocation(), diag::note_template_param_here);
3371 // Complain if we overflowed the template parameter's type.
3372 unsigned RequiredBits;
3373 if (IntegerType->isUnsignedIntegerType())
3374 RequiredBits = OldValue.getActiveBits();
3375 else if (OldValue.isUnsigned())
3376 RequiredBits = OldValue.getActiveBits() + 1;
3377 else
3378 RequiredBits = OldValue.getMinSignedBits();
3379 if (RequiredBits > AllowedBits) {
3380 Diag(Arg->getSourceRange().getBegin(),
3381 diag::warn_template_arg_too_large)
3382 << OldValue.toString(10) << Value.toString(10) << Param->getType()
3383 << Arg->getSourceRange();
3384 Diag(Param->getLocation(), diag::note_template_param_here);
3388 // Add the value of this argument to the list of converted
3389 // arguments. We use the bitwidth and signedness of the template
3390 // parameter.
3391 if (Arg->isValueDependent()) {
3392 // The argument is value-dependent. Create a new
3393 // TemplateArgument with the converted expression.
3394 Converted = TemplateArgument(Arg);
3395 return false;
3398 Converted = TemplateArgument(Value,
3399 ParamType->isEnumeralType() ? ParamType
3400 : IntegerType);
3401 return false;
3404 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
3406 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
3407 // from a template argument of type std::nullptr_t to a non-type
3408 // template parameter of type pointer to object, pointer to
3409 // function, or pointer-to-member, respectively.
3410 if (ArgType->isNullPtrType() &&
3411 (ParamType->isPointerType() || ParamType->isMemberPointerType())) {
3412 Converted = TemplateArgument((NamedDecl *)0);
3413 return false;
3416 // Handle pointer-to-function, reference-to-function, and
3417 // pointer-to-member-function all in (roughly) the same way.
3418 if (// -- For a non-type template-parameter of type pointer to
3419 // function, only the function-to-pointer conversion (4.3) is
3420 // applied. If the template-argument represents a set of
3421 // overloaded functions (or a pointer to such), the matching
3422 // function is selected from the set (13.4).
3423 (ParamType->isPointerType() &&
3424 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
3425 // -- For a non-type template-parameter of type reference to
3426 // function, no conversions apply. If the template-argument
3427 // represents a set of overloaded functions, the matching
3428 // function is selected from the set (13.4).
3429 (ParamType->isReferenceType() &&
3430 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
3431 // -- For a non-type template-parameter of type pointer to
3432 // member function, no conversions apply. If the
3433 // template-argument represents a set of overloaded member
3434 // functions, the matching member function is selected from
3435 // the set (13.4).
3436 (ParamType->isMemberPointerType() &&
3437 ParamType->getAs<MemberPointerType>()->getPointeeType()
3438 ->isFunctionType())) {
3440 if (Arg->getType() == Context.OverloadTy) {
3441 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
3442 true,
3443 FoundResult)) {
3444 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
3445 return true;
3447 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
3448 ArgType = Arg->getType();
3449 } else
3450 return true;
3453 if (!ParamType->isMemberPointerType())
3454 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3455 ParamType,
3456 Arg, Converted);
3458 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType(),
3459 false)) {
3460 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
3461 } else if (!Context.hasSameUnqualifiedType(ArgType,
3462 ParamType.getNonReferenceType())) {
3463 // We can't perform this conversion.
3464 Diag(Arg->getSourceRange().getBegin(),
3465 diag::err_template_arg_not_convertible)
3466 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
3467 Diag(Param->getLocation(), diag::note_template_param_here);
3468 return true;
3471 return CheckTemplateArgumentPointerToMember(Arg, Converted);
3474 if (ParamType->isPointerType()) {
3475 // -- for a non-type template-parameter of type pointer to
3476 // object, qualification conversions (4.4) and the
3477 // array-to-pointer conversion (4.2) are applied.
3478 // C++0x also allows a value of std::nullptr_t.
3479 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
3480 "Only object pointers allowed here");
3482 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3483 ParamType,
3484 Arg, Converted);
3487 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
3488 // -- For a non-type template-parameter of type reference to
3489 // object, no conversions apply. The type referred to by the
3490 // reference may be more cv-qualified than the (otherwise
3491 // identical) type of the template-argument. The
3492 // template-parameter is bound directly to the
3493 // template-argument, which must be an lvalue.
3494 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
3495 "Only object references allowed here");
3497 if (Arg->getType() == Context.OverloadTy) {
3498 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
3499 ParamRefType->getPointeeType(),
3500 true,
3501 FoundResult)) {
3502 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
3503 return true;
3505 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
3506 ArgType = Arg->getType();
3507 } else
3508 return true;
3511 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3512 ParamType,
3513 Arg, Converted);
3516 // -- For a non-type template-parameter of type pointer to data
3517 // member, qualification conversions (4.4) are applied.
3518 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
3520 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
3521 // Types match exactly: nothing more to do here.
3522 } else if (IsQualificationConversion(ArgType, ParamType, false)) {
3523 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg));
3524 } else {
3525 // We can't perform this conversion.
3526 Diag(Arg->getSourceRange().getBegin(),
3527 diag::err_template_arg_not_convertible)
3528 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
3529 Diag(Param->getLocation(), diag::note_template_param_here);
3530 return true;
3533 return CheckTemplateArgumentPointerToMember(Arg, Converted);
3536 /// \brief Check a template argument against its corresponding
3537 /// template template parameter.
3539 /// This routine implements the semantics of C++ [temp.arg.template].
3540 /// It returns true if an error occurred, and false otherwise.
3541 bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
3542 const TemplateArgumentLoc &Arg) {
3543 TemplateName Name = Arg.getArgument().getAsTemplate();
3544 TemplateDecl *Template = Name.getAsTemplateDecl();
3545 if (!Template) {
3546 // Any dependent template name is fine.
3547 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
3548 return false;
3551 // C++ [temp.arg.template]p1:
3552 // A template-argument for a template template-parameter shall be
3553 // the name of a class template, expressed as id-expression. Only
3554 // primary class templates are considered when matching the
3555 // template template argument with the corresponding parameter;
3556 // partial specializations are not considered even if their
3557 // parameter lists match that of the template template parameter.
3559 // Note that we also allow template template parameters here, which
3560 // will happen when we are dealing with, e.g., class template
3561 // partial specializations.
3562 if (!isa<ClassTemplateDecl>(Template) &&
3563 !isa<TemplateTemplateParmDecl>(Template)) {
3564 assert(isa<FunctionTemplateDecl>(Template) &&
3565 "Only function templates are possible here");
3566 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
3567 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
3568 << Template;
3571 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
3572 Param->getTemplateParameters(),
3573 true,
3574 TPL_TemplateTemplateArgumentMatch,
3575 Arg.getLocation());
3578 /// \brief Given a non-type template argument that refers to a
3579 /// declaration and the type of its corresponding non-type template
3580 /// parameter, produce an expression that properly refers to that
3581 /// declaration.
3582 ExprResult
3583 Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
3584 QualType ParamType,
3585 SourceLocation Loc) {
3586 assert(Arg.getKind() == TemplateArgument::Declaration &&
3587 "Only declaration template arguments permitted here");
3588 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
3590 if (VD->getDeclContext()->isRecord() &&
3591 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
3592 // If the value is a class member, we might have a pointer-to-member.
3593 // Determine whether the non-type template template parameter is of
3594 // pointer-to-member type. If so, we need to build an appropriate
3595 // expression for a pointer-to-member, since a "normal" DeclRefExpr
3596 // would refer to the member itself.
3597 if (ParamType->isMemberPointerType()) {
3598 QualType ClassType
3599 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
3600 NestedNameSpecifier *Qualifier
3601 = NestedNameSpecifier::Create(Context, 0, false,
3602 ClassType.getTypePtr());
3603 CXXScopeSpec SS;
3604 SS.setScopeRep(Qualifier);
3606 // The actual value-ness of this is unimportant, but for
3607 // internal consistency's sake, references to instance methods
3608 // are r-values.
3609 ExprValueKind VK = VK_LValue;
3610 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
3611 VK = VK_RValue;
3613 ExprResult RefExpr = BuildDeclRefExpr(VD,
3614 VD->getType().getNonReferenceType(),
3616 Loc,
3617 &SS);
3618 if (RefExpr.isInvalid())
3619 return ExprError();
3621 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
3623 // We might need to perform a trailing qualification conversion, since
3624 // the element type on the parameter could be more qualified than the
3625 // element type in the expression we constructed.
3626 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
3627 ParamType.getUnqualifiedType(), false)) {
3628 Expr *RefE = RefExpr.takeAs<Expr>();
3629 ImpCastExprToType(RefE, ParamType.getUnqualifiedType(), CK_NoOp);
3630 RefExpr = Owned(RefE);
3633 assert(!RefExpr.isInvalid() &&
3634 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
3635 ParamType.getUnqualifiedType()));
3636 return move(RefExpr);
3640 QualType T = VD->getType().getNonReferenceType();
3641 if (ParamType->isPointerType()) {
3642 // When the non-type template parameter is a pointer, take the
3643 // address of the declaration.
3644 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
3645 if (RefExpr.isInvalid())
3646 return ExprError();
3648 if (T->isFunctionType() || T->isArrayType()) {
3649 // Decay functions and arrays.
3650 Expr *RefE = (Expr *)RefExpr.get();
3651 DefaultFunctionArrayConversion(RefE);
3652 if (RefE != RefExpr.get()) {
3653 RefExpr.release();
3654 RefExpr = Owned(RefE);
3657 return move(RefExpr);
3660 // Take the address of everything else
3661 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
3664 ExprValueKind VK = VK_RValue;
3666 // If the non-type template parameter has reference type, qualify the
3667 // resulting declaration reference with the extra qualifiers on the
3668 // type that the reference refers to.
3669 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
3670 VK = VK_LValue;
3671 T = Context.getQualifiedType(T,
3672 TargetRef->getPointeeType().getQualifiers());
3675 return BuildDeclRefExpr(VD, T, VK, Loc);
3678 /// \brief Construct a new expression that refers to the given
3679 /// integral template argument with the given source-location
3680 /// information.
3682 /// This routine takes care of the mapping from an integral template
3683 /// argument (which may have any integral type) to the appropriate
3684 /// literal value.
3685 ExprResult
3686 Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
3687 SourceLocation Loc) {
3688 assert(Arg.getKind() == TemplateArgument::Integral &&
3689 "Operation is only valid for integral template arguments");
3690 QualType T = Arg.getIntegralType();
3691 if (T->isCharType() || T->isWideCharType())
3692 return Owned(new (Context) CharacterLiteral(
3693 Arg.getAsIntegral()->getZExtValue(),
3694 T->isWideCharType(),
3696 Loc));
3697 if (T->isBooleanType())
3698 return Owned(new (Context) CXXBoolLiteralExpr(
3699 Arg.getAsIntegral()->getBoolValue(),
3701 Loc));
3703 QualType BT;
3704 if (const EnumType *ET = T->getAs<EnumType>())
3705 BT = ET->getDecl()->getPromotionType();
3706 else
3707 BT = T;
3709 Expr *E = IntegerLiteral::Create(Context, *Arg.getAsIntegral(), BT, Loc);
3710 if (T->isEnumeralType()) {
3711 // FIXME: This is a hack. We need a better way to handle substituted
3712 // non-type template parameters.
3713 E = CStyleCastExpr::Create(Context, T, VK_RValue, CK_IntegralCast,
3714 E, 0,
3715 Context.getTrivialTypeSourceInfo(T, Loc),
3716 Loc, Loc);
3719 return Owned(E);
3722 /// \brief Match two template parameters within template parameter lists.
3723 static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
3724 bool Complain,
3725 Sema::TemplateParameterListEqualKind Kind,
3726 SourceLocation TemplateArgLoc) {
3727 // Check the actual kind (type, non-type, template).
3728 if (Old->getKind() != New->getKind()) {
3729 if (Complain) {
3730 unsigned NextDiag = diag::err_template_param_different_kind;
3731 if (TemplateArgLoc.isValid()) {
3732 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3733 NextDiag = diag::note_template_param_different_kind;
3735 S.Diag(New->getLocation(), NextDiag)
3736 << (Kind != Sema::TPL_TemplateMatch);
3737 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
3738 << (Kind != Sema::TPL_TemplateMatch);
3741 return false;
3744 // Check that both are parameter packs are neither are parameter packs.
3745 // However, if we are matching a template template argument to a
3746 // template template parameter, the template template parameter can have
3747 // a parameter pack where the template template argument does not.
3748 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
3749 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
3750 Old->isTemplateParameterPack())) {
3751 if (Complain) {
3752 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
3753 if (TemplateArgLoc.isValid()) {
3754 S.Diag(TemplateArgLoc,
3755 diag::err_template_arg_template_params_mismatch);
3756 NextDiag = diag::note_template_parameter_pack_non_pack;
3759 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
3760 : isa<NonTypeTemplateParmDecl>(New)? 1
3761 : 2;
3762 S.Diag(New->getLocation(), NextDiag)
3763 << ParamKind << New->isParameterPack();
3764 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
3765 << ParamKind << Old->isParameterPack();
3768 return false;
3771 // For non-type template parameters, check the type of the parameter.
3772 if (NonTypeTemplateParmDecl *OldNTTP
3773 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
3774 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
3776 // If we are matching a template template argument to a template
3777 // template parameter and one of the non-type template parameter types
3778 // is dependent, then we must wait until template instantiation time
3779 // to actually compare the arguments.
3780 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
3781 (OldNTTP->getType()->isDependentType() ||
3782 NewNTTP->getType()->isDependentType()))
3783 return true;
3785 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
3786 if (Complain) {
3787 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3788 if (TemplateArgLoc.isValid()) {
3789 S.Diag(TemplateArgLoc,
3790 diag::err_template_arg_template_params_mismatch);
3791 NextDiag = diag::note_template_nontype_parm_different_type;
3793 S.Diag(NewNTTP->getLocation(), NextDiag)
3794 << NewNTTP->getType()
3795 << (Kind != Sema::TPL_TemplateMatch);
3796 S.Diag(OldNTTP->getLocation(),
3797 diag::note_template_nontype_parm_prev_declaration)
3798 << OldNTTP->getType();
3801 return false;
3804 return true;
3807 // For template template parameters, check the template parameter types.
3808 // The template parameter lists of template template
3809 // parameters must agree.
3810 if (TemplateTemplateParmDecl *OldTTP
3811 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
3812 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
3813 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3814 OldTTP->getTemplateParameters(),
3815 Complain,
3816 (Kind == Sema::TPL_TemplateMatch
3817 ? Sema::TPL_TemplateTemplateParmMatch
3818 : Kind),
3819 TemplateArgLoc);
3822 return true;
3825 /// \brief Diagnose a known arity mismatch when comparing template argument
3826 /// lists.
3827 static
3828 void DiagnoseTemplateParameterListArityMismatch(Sema &S,
3829 TemplateParameterList *New,
3830 TemplateParameterList *Old,
3831 Sema::TemplateParameterListEqualKind Kind,
3832 SourceLocation TemplateArgLoc) {
3833 unsigned NextDiag = diag::err_template_param_list_different_arity;
3834 if (TemplateArgLoc.isValid()) {
3835 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3836 NextDiag = diag::note_template_param_list_different_arity;
3838 S.Diag(New->getTemplateLoc(), NextDiag)
3839 << (New->size() > Old->size())
3840 << (Kind != Sema::TPL_TemplateMatch)
3841 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
3842 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
3843 << (Kind != Sema::TPL_TemplateMatch)
3844 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3847 /// \brief Determine whether the given template parameter lists are
3848 /// equivalent.
3850 /// \param New The new template parameter list, typically written in the
3851 /// source code as part of a new template declaration.
3853 /// \param Old The old template parameter list, typically found via
3854 /// name lookup of the template declared with this template parameter
3855 /// list.
3857 /// \param Complain If true, this routine will produce a diagnostic if
3858 /// the template parameter lists are not equivalent.
3860 /// \param Kind describes how we are to match the template parameter lists.
3862 /// \param TemplateArgLoc If this source location is valid, then we
3863 /// are actually checking the template parameter list of a template
3864 /// argument (New) against the template parameter list of its
3865 /// corresponding template template parameter (Old). We produce
3866 /// slightly different diagnostics in this scenario.
3868 /// \returns True if the template parameter lists are equal, false
3869 /// otherwise.
3870 bool
3871 Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3872 TemplateParameterList *Old,
3873 bool Complain,
3874 TemplateParameterListEqualKind Kind,
3875 SourceLocation TemplateArgLoc) {
3876 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
3877 if (Complain)
3878 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
3879 TemplateArgLoc);
3881 return false;
3884 // C++0x [temp.arg.template]p3:
3885 // A template-argument matches a template template-parameter (call it P)
3886 // when each of the template parameters in the template-parameter-list of
3887 // the template-argument's corresponding class template or template alias
3888 // (call it A) matches the corresponding template parameter in the
3889 // template-parameter-list of P. [...]
3890 TemplateParameterList::iterator NewParm = New->begin();
3891 TemplateParameterList::iterator NewParmEnd = New->end();
3892 for (TemplateParameterList::iterator OldParm = Old->begin(),
3893 OldParmEnd = Old->end();
3894 OldParm != OldParmEnd; ++OldParm) {
3895 if (Kind != TPL_TemplateTemplateArgumentMatch ||
3896 !(*OldParm)->isTemplateParameterPack()) {
3897 if (NewParm == NewParmEnd) {
3898 if (Complain)
3899 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
3900 TemplateArgLoc);
3902 return false;
3905 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
3906 Kind, TemplateArgLoc))
3907 return false;
3909 ++NewParm;
3910 continue;
3913 // C++0x [temp.arg.template]p3:
3914 // [...] When P's template- parameter-list contains a template parameter
3915 // pack (14.5.3), the template parameter pack will match zero or more
3916 // template parameters or template parameter packs in the
3917 // template-parameter-list of A with the same type and form as the
3918 // template parameter pack in P (ignoring whether those template
3919 // parameters are template parameter packs).
3920 for (; NewParm != NewParmEnd; ++NewParm) {
3921 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
3922 Kind, TemplateArgLoc))
3923 return false;
3927 // Make sure we exhausted all of the arguments.
3928 if (NewParm != NewParmEnd) {
3929 if (Complain)
3930 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
3931 TemplateArgLoc);
3933 return false;
3936 return true;
3939 /// \brief Check whether a template can be declared within this scope.
3941 /// If the template declaration is valid in this scope, returns
3942 /// false. Otherwise, issues a diagnostic and returns true.
3943 bool
3944 Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
3945 // Find the nearest enclosing declaration scope.
3946 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3947 (S->getFlags() & Scope::TemplateParamScope) != 0)
3948 S = S->getParent();
3950 // C++ [temp]p2:
3951 // A template-declaration can appear only as a namespace scope or
3952 // class scope declaration.
3953 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
3954 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3955 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
3956 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
3957 << TemplateParams->getSourceRange();
3959 while (Ctx && isa<LinkageSpecDecl>(Ctx))
3960 Ctx = Ctx->getParent();
3962 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3963 return false;
3965 return Diag(TemplateParams->getTemplateLoc(),
3966 diag::err_template_outside_namespace_or_class_scope)
3967 << TemplateParams->getSourceRange();
3970 /// \brief Determine what kind of template specialization the given declaration
3971 /// is.
3972 static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3973 if (!D)
3974 return TSK_Undeclared;
3976 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3977 return Record->getTemplateSpecializationKind();
3978 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3979 return Function->getTemplateSpecializationKind();
3980 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3981 return Var->getTemplateSpecializationKind();
3983 return TSK_Undeclared;
3986 /// \brief Check whether a specialization is well-formed in the current
3987 /// context.
3989 /// This routine determines whether a template specialization can be declared
3990 /// in the current context (C++ [temp.expl.spec]p2).
3992 /// \param S the semantic analysis object for which this check is being
3993 /// performed.
3995 /// \param Specialized the entity being specialized or instantiated, which
3996 /// may be a kind of template (class template, function template, etc.) or
3997 /// a member of a class template (member function, static data member,
3998 /// member class).
4000 /// \param PrevDecl the previous declaration of this entity, if any.
4002 /// \param Loc the location of the explicit specialization or instantiation of
4003 /// this entity.
4005 /// \param IsPartialSpecialization whether this is a partial specialization of
4006 /// a class template.
4008 /// \returns true if there was an error that we cannot recover from, false
4009 /// otherwise.
4010 static bool CheckTemplateSpecializationScope(Sema &S,
4011 NamedDecl *Specialized,
4012 NamedDecl *PrevDecl,
4013 SourceLocation Loc,
4014 bool IsPartialSpecialization) {
4015 // Keep these "kind" numbers in sync with the %select statements in the
4016 // various diagnostics emitted by this routine.
4017 int EntityKind = 0;
4018 if (isa<ClassTemplateDecl>(Specialized))
4019 EntityKind = IsPartialSpecialization? 1 : 0;
4020 else if (isa<FunctionTemplateDecl>(Specialized))
4021 EntityKind = 2;
4022 else if (isa<CXXMethodDecl>(Specialized))
4023 EntityKind = 3;
4024 else if (isa<VarDecl>(Specialized))
4025 EntityKind = 4;
4026 else if (isa<RecordDecl>(Specialized))
4027 EntityKind = 5;
4028 else {
4029 S.Diag(Loc, diag::err_template_spec_unknown_kind);
4030 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
4031 return true;
4034 // C++ [temp.expl.spec]p2:
4035 // An explicit specialization shall be declared in the namespace
4036 // of which the template is a member, or, for member templates, in
4037 // the namespace of which the enclosing class or enclosing class
4038 // template is a member. An explicit specialization of a member
4039 // function, member class or static data member of a class
4040 // template shall be declared in the namespace of which the class
4041 // template is a member. Such a declaration may also be a
4042 // definition. If the declaration is not a definition, the
4043 // specialization may be defined later in the name- space in which
4044 // the explicit specialization was declared, or in a namespace
4045 // that encloses the one in which the explicit specialization was
4046 // declared.
4047 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
4048 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
4049 << Specialized;
4050 return true;
4053 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
4054 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
4055 << Specialized;
4056 return true;
4059 // C++ [temp.class.spec]p6:
4060 // A class template partial specialization may be declared or redeclared
4061 // in any namespace scope in which its definition may be defined (14.5.1
4062 // and 14.5.2).
4063 bool ComplainedAboutScope = false;
4064 DeclContext *SpecializedContext
4065 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
4066 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
4067 if ((!PrevDecl ||
4068 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
4069 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
4070 // C++ [temp.exp.spec]p2:
4071 // An explicit specialization shall be declared in the namespace of which
4072 // the template is a member, or, for member templates, in the namespace
4073 // of which the enclosing class or enclosing class template is a member.
4074 // An explicit specialization of a member function, member class or
4075 // static data member of a class template shall be declared in the
4076 // namespace of which the class template is a member.
4078 // C++0x [temp.expl.spec]p2:
4079 // An explicit specialization shall be declared in a namespace enclosing
4080 // the specialized template.
4081 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext) &&
4082 !(S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext))) {
4083 bool IsCPlusPlus0xExtension
4084 = !S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext);
4085 if (isa<TranslationUnitDecl>(SpecializedContext))
4086 S.Diag(Loc, IsCPlusPlus0xExtension
4087 ? diag::ext_template_spec_decl_out_of_scope_global
4088 : diag::err_template_spec_decl_out_of_scope_global)
4089 << EntityKind << Specialized;
4090 else if (isa<NamespaceDecl>(SpecializedContext))
4091 S.Diag(Loc, IsCPlusPlus0xExtension
4092 ? diag::ext_template_spec_decl_out_of_scope
4093 : diag::err_template_spec_decl_out_of_scope)
4094 << EntityKind << Specialized
4095 << cast<NamedDecl>(SpecializedContext);
4097 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
4098 ComplainedAboutScope = true;
4102 // Make sure that this redeclaration (or definition) occurs in an enclosing
4103 // namespace.
4104 // Note that HandleDeclarator() performs this check for explicit
4105 // specializations of function templates, static data members, and member
4106 // functions, so we skip the check here for those kinds of entities.
4107 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
4108 // Should we refactor that check, so that it occurs later?
4109 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
4110 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
4111 isa<FunctionDecl>(Specialized))) {
4112 if (isa<TranslationUnitDecl>(SpecializedContext))
4113 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
4114 << EntityKind << Specialized;
4115 else if (isa<NamespaceDecl>(SpecializedContext))
4116 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
4117 << EntityKind << Specialized
4118 << cast<NamedDecl>(SpecializedContext);
4120 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
4123 // FIXME: check for specialization-after-instantiation errors and such.
4125 return false;
4128 /// \brief Subroutine of Sema::CheckClassTemplatePartialSpecializationArgs
4129 /// that checks non-type template partial specialization arguments.
4130 static bool CheckNonTypeClassTemplatePartialSpecializationArgs(Sema &S,
4131 NonTypeTemplateParmDecl *Param,
4132 const TemplateArgument *Args,
4133 unsigned NumArgs) {
4134 for (unsigned I = 0; I != NumArgs; ++I) {
4135 if (Args[I].getKind() == TemplateArgument::Pack) {
4136 if (CheckNonTypeClassTemplatePartialSpecializationArgs(S, Param,
4137 Args[I].pack_begin(),
4138 Args[I].pack_size()))
4139 return true;
4141 continue;
4144 Expr *ArgExpr = Args[I].getAsExpr();
4145 if (!ArgExpr) {
4146 continue;
4149 // We can have a pack expansion of any of the bullets below.
4150 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
4151 ArgExpr = Expansion->getPattern();
4153 // Strip off any implicit casts we added as part of type checking.
4154 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
4155 ArgExpr = ICE->getSubExpr();
4157 // C++ [temp.class.spec]p8:
4158 // A non-type argument is non-specialized if it is the name of a
4159 // non-type parameter. All other non-type arguments are
4160 // specialized.
4162 // Below, we check the two conditions that only apply to
4163 // specialized non-type arguments, so skip any non-specialized
4164 // arguments.
4165 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
4166 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
4167 continue;
4169 // C++ [temp.class.spec]p9:
4170 // Within the argument list of a class template partial
4171 // specialization, the following restrictions apply:
4172 // -- A partially specialized non-type argument expression
4173 // shall not involve a template parameter of the partial
4174 // specialization except when the argument expression is a
4175 // simple identifier.
4176 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
4177 S.Diag(ArgExpr->getLocStart(),
4178 diag::err_dependent_non_type_arg_in_partial_spec)
4179 << ArgExpr->getSourceRange();
4180 return true;
4183 // -- The type of a template parameter corresponding to a
4184 // specialized non-type argument shall not be dependent on a
4185 // parameter of the specialization.
4186 if (Param->getType()->isDependentType()) {
4187 S.Diag(ArgExpr->getLocStart(),
4188 diag::err_dependent_typed_non_type_arg_in_partial_spec)
4189 << Param->getType()
4190 << ArgExpr->getSourceRange();
4191 S.Diag(Param->getLocation(), diag::note_template_param_here);
4192 return true;
4196 return false;
4199 /// \brief Check the non-type template arguments of a class template
4200 /// partial specialization according to C++ [temp.class.spec]p9.
4202 /// \param TemplateParams the template parameters of the primary class
4203 /// template.
4205 /// \param TemplateArg the template arguments of the class template
4206 /// partial specialization.
4208 /// \returns true if there was an error, false otherwise.
4209 static bool CheckClassTemplatePartialSpecializationArgs(Sema &S,
4210 TemplateParameterList *TemplateParams,
4211 llvm::SmallVectorImpl<TemplateArgument> &TemplateArgs) {
4212 const TemplateArgument *ArgList = TemplateArgs.data();
4214 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
4215 NonTypeTemplateParmDecl *Param
4216 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
4217 if (!Param)
4218 continue;
4220 if (CheckNonTypeClassTemplatePartialSpecializationArgs(S, Param,
4221 &ArgList[I], 1))
4222 return true;
4225 return false;
4228 /// \brief Retrieve the previous declaration of the given declaration.
4229 static NamedDecl *getPreviousDecl(NamedDecl *ND) {
4230 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4231 return VD->getPreviousDeclaration();
4232 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
4233 return FD->getPreviousDeclaration();
4234 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
4235 return TD->getPreviousDeclaration();
4236 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
4237 return TD->getPreviousDeclaration();
4238 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4239 return FTD->getPreviousDeclaration();
4240 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
4241 return CTD->getPreviousDeclaration();
4242 return 0;
4245 DeclResult
4246 Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
4247 TagUseKind TUK,
4248 SourceLocation KWLoc,
4249 CXXScopeSpec &SS,
4250 TemplateTy TemplateD,
4251 SourceLocation TemplateNameLoc,
4252 SourceLocation LAngleLoc,
4253 ASTTemplateArgsPtr TemplateArgsIn,
4254 SourceLocation RAngleLoc,
4255 AttributeList *Attr,
4256 MultiTemplateParamsArg TemplateParameterLists) {
4257 assert(TUK != TUK_Reference && "References are not specializations");
4259 // Find the class template we're specializing
4260 TemplateName Name = TemplateD.getAsVal<TemplateName>();
4261 ClassTemplateDecl *ClassTemplate
4262 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
4264 if (!ClassTemplate) {
4265 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
4266 << (Name.getAsTemplateDecl() &&
4267 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
4268 return true;
4271 bool isExplicitSpecialization = false;
4272 bool isPartialSpecialization = false;
4274 // Check the validity of the template headers that introduce this
4275 // template.
4276 // FIXME: We probably shouldn't complain about these headers for
4277 // friend declarations.
4278 bool Invalid = false;
4279 TemplateParameterList *TemplateParams
4280 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
4281 (TemplateParameterList**)TemplateParameterLists.get(),
4282 TemplateParameterLists.size(),
4283 TUK == TUK_Friend,
4284 isExplicitSpecialization,
4285 Invalid);
4286 if (Invalid)
4287 return true;
4289 unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size();
4290 if (TemplateParams)
4291 --NumMatchedTemplateParamLists;
4293 if (TemplateParams && TemplateParams->size() > 0) {
4294 isPartialSpecialization = true;
4296 if (TUK == TUK_Friend) {
4297 Diag(KWLoc, diag::err_partial_specialization_friend)
4298 << SourceRange(LAngleLoc, RAngleLoc);
4299 return true;
4302 // C++ [temp.class.spec]p10:
4303 // The template parameter list of a specialization shall not
4304 // contain default template argument values.
4305 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
4306 Decl *Param = TemplateParams->getParam(I);
4307 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
4308 if (TTP->hasDefaultArgument()) {
4309 Diag(TTP->getDefaultArgumentLoc(),
4310 diag::err_default_arg_in_partial_spec);
4311 TTP->removeDefaultArgument();
4313 } else if (NonTypeTemplateParmDecl *NTTP
4314 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4315 if (Expr *DefArg = NTTP->getDefaultArgument()) {
4316 Diag(NTTP->getDefaultArgumentLoc(),
4317 diag::err_default_arg_in_partial_spec)
4318 << DefArg->getSourceRange();
4319 NTTP->removeDefaultArgument();
4321 } else {
4322 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
4323 if (TTP->hasDefaultArgument()) {
4324 Diag(TTP->getDefaultArgument().getLocation(),
4325 diag::err_default_arg_in_partial_spec)
4326 << TTP->getDefaultArgument().getSourceRange();
4327 TTP->removeDefaultArgument();
4331 } else if (TemplateParams) {
4332 if (TUK == TUK_Friend)
4333 Diag(KWLoc, diag::err_template_spec_friend)
4334 << FixItHint::CreateRemoval(
4335 SourceRange(TemplateParams->getTemplateLoc(),
4336 TemplateParams->getRAngleLoc()))
4337 << SourceRange(LAngleLoc, RAngleLoc);
4338 else
4339 isExplicitSpecialization = true;
4340 } else if (TUK != TUK_Friend) {
4341 Diag(KWLoc, diag::err_template_spec_needs_header)
4342 << FixItHint::CreateInsertion(KWLoc, "template<> ");
4343 isExplicitSpecialization = true;
4346 // Check that the specialization uses the same tag kind as the
4347 // original template.
4348 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4349 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
4350 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
4351 Kind, KWLoc,
4352 *ClassTemplate->getIdentifier())) {
4353 Diag(KWLoc, diag::err_use_with_wrong_tag)
4354 << ClassTemplate
4355 << FixItHint::CreateReplacement(KWLoc,
4356 ClassTemplate->getTemplatedDecl()->getKindName());
4357 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
4358 diag::note_previous_use);
4359 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4362 // Translate the parser's template argument list in our AST format.
4363 TemplateArgumentListInfo TemplateArgs;
4364 TemplateArgs.setLAngleLoc(LAngleLoc);
4365 TemplateArgs.setRAngleLoc(RAngleLoc);
4366 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4368 // Check for unexpanded parameter packs in any of the template arguments.
4369 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4370 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4371 UPPC_PartialSpecialization))
4372 return true;
4374 // Check that the template argument list is well-formed for this
4375 // template.
4376 llvm::SmallVector<TemplateArgument, 4> Converted;
4377 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4378 TemplateArgs, false, Converted))
4379 return true;
4381 assert((Converted.size() == ClassTemplate->getTemplateParameters()->size()) &&
4382 "Converted template argument list is too short!");
4384 // Find the class template (partial) specialization declaration that
4385 // corresponds to these arguments.
4386 if (isPartialSpecialization) {
4387 if (CheckClassTemplatePartialSpecializationArgs(*this,
4388 ClassTemplate->getTemplateParameters(),
4389 Converted))
4390 return true;
4392 if (!Name.isDependent() &&
4393 !TemplateSpecializationType::anyDependentTemplateArguments(
4394 TemplateArgs.getArgumentArray(),
4395 TemplateArgs.size())) {
4396 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4397 << ClassTemplate->getDeclName();
4398 isPartialSpecialization = false;
4402 void *InsertPos = 0;
4403 ClassTemplateSpecializationDecl *PrevDecl = 0;
4405 if (isPartialSpecialization)
4406 // FIXME: Template parameter list matters, too
4407 PrevDecl
4408 = ClassTemplate->findPartialSpecialization(Converted.data(),
4409 Converted.size(),
4410 InsertPos);
4411 else
4412 PrevDecl
4413 = ClassTemplate->findSpecialization(Converted.data(),
4414 Converted.size(), InsertPos);
4416 ClassTemplateSpecializationDecl *Specialization = 0;
4418 // Check whether we can declare a class template specialization in
4419 // the current scope.
4420 if (TUK != TUK_Friend &&
4421 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
4422 TemplateNameLoc,
4423 isPartialSpecialization))
4424 return true;
4426 // The canonical type
4427 QualType CanonType;
4428 if (PrevDecl &&
4429 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
4430 TUK == TUK_Friend)) {
4431 // Since the only prior class template specialization with these
4432 // arguments was referenced but not declared, or we're only
4433 // referencing this specialization as a friend, reuse that
4434 // declaration node as our own, updating its source location to
4435 // reflect our new declaration.
4436 Specialization = PrevDecl;
4437 Specialization->setLocation(TemplateNameLoc);
4438 PrevDecl = 0;
4439 CanonType = Context.getTypeDeclType(Specialization);
4440 } else if (isPartialSpecialization) {
4441 // Build the canonical type that describes the converted template
4442 // arguments of the class template partial specialization.
4443 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4444 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
4445 Converted.data(),
4446 Converted.size());
4448 if (Context.hasSameType(CanonType,
4449 ClassTemplate->getInjectedClassNameSpecialization())) {
4450 // C++ [temp.class.spec]p9b3:
4452 // -- The argument list of the specialization shall not be identical
4453 // to the implicit argument list of the primary template.
4454 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4455 << (TUK == TUK_Definition)
4456 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4457 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
4458 ClassTemplate->getIdentifier(),
4459 TemplateNameLoc,
4460 Attr,
4461 TemplateParams,
4462 AS_none);
4465 // Create a new class template partial specialization declaration node.
4466 ClassTemplatePartialSpecializationDecl *PrevPartial
4467 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
4468 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
4469 : ClassTemplate->getNextPartialSpecSequenceNumber();
4470 ClassTemplatePartialSpecializationDecl *Partial
4471 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
4472 ClassTemplate->getDeclContext(),
4473 TemplateNameLoc,
4474 TemplateParams,
4475 ClassTemplate,
4476 Converted.data(),
4477 Converted.size(),
4478 TemplateArgs,
4479 CanonType,
4480 PrevPartial,
4481 SequenceNumber);
4482 SetNestedNameSpecifier(Partial, SS);
4483 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
4484 Partial->setTemplateParameterListsInfo(Context,
4485 NumMatchedTemplateParamLists,
4486 (TemplateParameterList**) TemplateParameterLists.release());
4489 if (!PrevPartial)
4490 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
4491 Specialization = Partial;
4493 // If we are providing an explicit specialization of a member class
4494 // template specialization, make a note of that.
4495 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4496 PrevPartial->setMemberSpecialization();
4498 // Check that all of the template parameters of the class template
4499 // partial specialization are deducible from the template
4500 // arguments. If not, this class template partial specialization
4501 // will never be used.
4502 llvm::SmallVector<bool, 8> DeducibleParams;
4503 DeducibleParams.resize(TemplateParams->size());
4504 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4505 TemplateParams->getDepth(),
4506 DeducibleParams);
4507 unsigned NumNonDeducible = 0;
4508 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
4509 if (!DeducibleParams[I])
4510 ++NumNonDeducible;
4512 if (NumNonDeducible) {
4513 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
4514 << (NumNonDeducible > 1)
4515 << SourceRange(TemplateNameLoc, RAngleLoc);
4516 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4517 if (!DeducibleParams[I]) {
4518 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
4519 if (Param->getDeclName())
4520 Diag(Param->getLocation(),
4521 diag::note_partial_spec_unused_parameter)
4522 << Param->getDeclName();
4523 else
4524 Diag(Param->getLocation(),
4525 diag::note_partial_spec_unused_parameter)
4526 << "<anonymous>";
4530 } else {
4531 // Create a new class template specialization declaration node for
4532 // this explicit specialization or friend declaration.
4533 Specialization
4534 = ClassTemplateSpecializationDecl::Create(Context, Kind,
4535 ClassTemplate->getDeclContext(),
4536 TemplateNameLoc,
4537 ClassTemplate,
4538 Converted.data(),
4539 Converted.size(),
4540 PrevDecl);
4541 SetNestedNameSpecifier(Specialization, SS);
4542 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
4543 Specialization->setTemplateParameterListsInfo(Context,
4544 NumMatchedTemplateParamLists,
4545 (TemplateParameterList**) TemplateParameterLists.release());
4548 if (!PrevDecl)
4549 ClassTemplate->AddSpecialization(Specialization, InsertPos);
4551 CanonType = Context.getTypeDeclType(Specialization);
4554 // C++ [temp.expl.spec]p6:
4555 // If a template, a member template or the member of a class template is
4556 // explicitly specialized then that specialization shall be declared
4557 // before the first use of that specialization that would cause an implicit
4558 // instantiation to take place, in every translation unit in which such a
4559 // use occurs; no diagnostic is required.
4560 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4561 bool Okay = false;
4562 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4563 // Is there any previous explicit specialization declaration?
4564 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
4565 Okay = true;
4566 break;
4570 if (!Okay) {
4571 SourceRange Range(TemplateNameLoc, RAngleLoc);
4572 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4573 << Context.getTypeDeclType(Specialization) << Range;
4575 Diag(PrevDecl->getPointOfInstantiation(),
4576 diag::note_instantiation_required_here)
4577 << (PrevDecl->getTemplateSpecializationKind()
4578 != TSK_ImplicitInstantiation);
4579 return true;
4583 // If this is not a friend, note that this is an explicit specialization.
4584 if (TUK != TUK_Friend)
4585 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4587 // Check that this isn't a redefinition of this specialization.
4588 if (TUK == TUK_Definition) {
4589 if (RecordDecl *Def = Specialization->getDefinition()) {
4590 SourceRange Range(TemplateNameLoc, RAngleLoc);
4591 Diag(TemplateNameLoc, diag::err_redefinition)
4592 << Context.getTypeDeclType(Specialization) << Range;
4593 Diag(Def->getLocation(), diag::note_previous_definition);
4594 Specialization->setInvalidDecl();
4595 return true;
4599 if (Attr)
4600 ProcessDeclAttributeList(S, Specialization, Attr);
4602 // Build the fully-sugared type for this class template
4603 // specialization as the user wrote in the specialization
4604 // itself. This means that we'll pretty-print the type retrieved
4605 // from the specialization's declaration the way that the user
4606 // actually wrote the specialization, rather than formatting the
4607 // name based on the "canonical" representation used to store the
4608 // template arguments in the specialization.
4609 TypeSourceInfo *WrittenTy
4610 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4611 TemplateArgs, CanonType);
4612 if (TUK != TUK_Friend) {
4613 Specialization->setTypeAsWritten(WrittenTy);
4614 if (TemplateParams)
4615 Specialization->setTemplateKeywordLoc(TemplateParams->getTemplateLoc());
4617 TemplateArgsIn.release();
4619 // C++ [temp.expl.spec]p9:
4620 // A template explicit specialization is in the scope of the
4621 // namespace in which the template was defined.
4623 // We actually implement this paragraph where we set the semantic
4624 // context (in the creation of the ClassTemplateSpecializationDecl),
4625 // but we also maintain the lexical context where the actual
4626 // definition occurs.
4627 Specialization->setLexicalDeclContext(CurContext);
4629 // We may be starting the definition of this specialization.
4630 if (TUK == TUK_Definition)
4631 Specialization->startDefinition();
4633 if (TUK == TUK_Friend) {
4634 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
4635 TemplateNameLoc,
4636 WrittenTy,
4637 /*FIXME:*/KWLoc);
4638 Friend->setAccess(AS_public);
4639 CurContext->addDecl(Friend);
4640 } else {
4641 // Add the specialization into its lexical context, so that it can
4642 // be seen when iterating through the list of declarations in that
4643 // context. However, specializations are not found by name lookup.
4644 CurContext->addDecl(Specialization);
4646 return Specialization;
4649 Decl *Sema::ActOnTemplateDeclarator(Scope *S,
4650 MultiTemplateParamsArg TemplateParameterLists,
4651 Declarator &D) {
4652 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
4655 Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
4656 MultiTemplateParamsArg TemplateParameterLists,
4657 Declarator &D) {
4658 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
4659 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
4661 if (FTI.hasPrototype) {
4662 // FIXME: Diagnose arguments without names in C.
4665 Scope *ParentScope = FnBodyScope->getParent();
4667 Decl *DP = HandleDeclarator(ParentScope, D,
4668 move(TemplateParameterLists),
4669 /*IsFunctionDefinition=*/true);
4670 if (FunctionTemplateDecl *FunctionTemplate
4671 = dyn_cast_or_null<FunctionTemplateDecl>(DP))
4672 return ActOnStartOfFunctionDef(FnBodyScope,
4673 FunctionTemplate->getTemplatedDecl());
4674 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP))
4675 return ActOnStartOfFunctionDef(FnBodyScope, Function);
4676 return 0;
4679 /// \brief Strips various properties off an implicit instantiation
4680 /// that has just been explicitly specialized.
4681 static void StripImplicitInstantiation(NamedDecl *D) {
4682 D->dropAttrs();
4684 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4685 FD->setInlineSpecified(false);
4689 /// \brief Diagnose cases where we have an explicit template specialization
4690 /// before/after an explicit template instantiation, producing diagnostics
4691 /// for those cases where they are required and determining whether the
4692 /// new specialization/instantiation will have any effect.
4694 /// \param NewLoc the location of the new explicit specialization or
4695 /// instantiation.
4697 /// \param NewTSK the kind of the new explicit specialization or instantiation.
4699 /// \param PrevDecl the previous declaration of the entity.
4701 /// \param PrevTSK the kind of the old explicit specialization or instantiatin.
4703 /// \param PrevPointOfInstantiation if valid, indicates where the previus
4704 /// declaration was instantiated (either implicitly or explicitly).
4706 /// \param HasNoEffect will be set to true to indicate that the new
4707 /// specialization or instantiation has no effect and should be ignored.
4709 /// \returns true if there was an error that should prevent the introduction of
4710 /// the new declaration into the AST, false otherwise.
4711 bool
4712 Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4713 TemplateSpecializationKind NewTSK,
4714 NamedDecl *PrevDecl,
4715 TemplateSpecializationKind PrevTSK,
4716 SourceLocation PrevPointOfInstantiation,
4717 bool &HasNoEffect) {
4718 HasNoEffect = false;
4720 switch (NewTSK) {
4721 case TSK_Undeclared:
4722 case TSK_ImplicitInstantiation:
4723 assert(false && "Don't check implicit instantiations here");
4724 return false;
4726 case TSK_ExplicitSpecialization:
4727 switch (PrevTSK) {
4728 case TSK_Undeclared:
4729 case TSK_ExplicitSpecialization:
4730 // Okay, we're just specializing something that is either already
4731 // explicitly specialized or has merely been mentioned without any
4732 // instantiation.
4733 return false;
4735 case TSK_ImplicitInstantiation:
4736 if (PrevPointOfInstantiation.isInvalid()) {
4737 // The declaration itself has not actually been instantiated, so it is
4738 // still okay to specialize it.
4739 StripImplicitInstantiation(PrevDecl);
4740 return false;
4742 // Fall through
4744 case TSK_ExplicitInstantiationDeclaration:
4745 case TSK_ExplicitInstantiationDefinition:
4746 assert((PrevTSK == TSK_ImplicitInstantiation ||
4747 PrevPointOfInstantiation.isValid()) &&
4748 "Explicit instantiation without point of instantiation?");
4750 // C++ [temp.expl.spec]p6:
4751 // If a template, a member template or the member of a class template
4752 // is explicitly specialized then that specialization shall be declared
4753 // before the first use of that specialization that would cause an
4754 // implicit instantiation to take place, in every translation unit in
4755 // which such a use occurs; no diagnostic is required.
4756 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4757 // Is there any previous explicit specialization declaration?
4758 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4759 return false;
4762 Diag(NewLoc, diag::err_specialization_after_instantiation)
4763 << PrevDecl;
4764 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
4765 << (PrevTSK != TSK_ImplicitInstantiation);
4767 return true;
4769 break;
4771 case TSK_ExplicitInstantiationDeclaration:
4772 switch (PrevTSK) {
4773 case TSK_ExplicitInstantiationDeclaration:
4774 // This explicit instantiation declaration is redundant (that's okay).
4775 HasNoEffect = true;
4776 return false;
4778 case TSK_Undeclared:
4779 case TSK_ImplicitInstantiation:
4780 // We're explicitly instantiating something that may have already been
4781 // implicitly instantiated; that's fine.
4782 return false;
4784 case TSK_ExplicitSpecialization:
4785 // C++0x [temp.explicit]p4:
4786 // For a given set of template parameters, if an explicit instantiation
4787 // of a template appears after a declaration of an explicit
4788 // specialization for that template, the explicit instantiation has no
4789 // effect.
4790 HasNoEffect = true;
4791 return false;
4793 case TSK_ExplicitInstantiationDefinition:
4794 // C++0x [temp.explicit]p10:
4795 // If an entity is the subject of both an explicit instantiation
4796 // declaration and an explicit instantiation definition in the same
4797 // translation unit, the definition shall follow the declaration.
4798 Diag(NewLoc,
4799 diag::err_explicit_instantiation_declaration_after_definition);
4800 Diag(PrevPointOfInstantiation,
4801 diag::note_explicit_instantiation_definition_here);
4802 assert(PrevPointOfInstantiation.isValid() &&
4803 "Explicit instantiation without point of instantiation?");
4804 HasNoEffect = true;
4805 return false;
4807 break;
4809 case TSK_ExplicitInstantiationDefinition:
4810 switch (PrevTSK) {
4811 case TSK_Undeclared:
4812 case TSK_ImplicitInstantiation:
4813 // We're explicitly instantiating something that may have already been
4814 // implicitly instantiated; that's fine.
4815 return false;
4817 case TSK_ExplicitSpecialization:
4818 // C++ DR 259, C++0x [temp.explicit]p4:
4819 // For a given set of template parameters, if an explicit
4820 // instantiation of a template appears after a declaration of
4821 // an explicit specialization for that template, the explicit
4822 // instantiation has no effect.
4824 // In C++98/03 mode, we only give an extension warning here, because it
4825 // is not harmful to try to explicitly instantiate something that
4826 // has been explicitly specialized.
4827 if (!getLangOptions().CPlusPlus0x) {
4828 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
4829 << PrevDecl;
4830 Diag(PrevDecl->getLocation(),
4831 diag::note_previous_template_specialization);
4833 HasNoEffect = true;
4834 return false;
4836 case TSK_ExplicitInstantiationDeclaration:
4837 // We're explicity instantiating a definition for something for which we
4838 // were previously asked to suppress instantiations. That's fine.
4839 return false;
4841 case TSK_ExplicitInstantiationDefinition:
4842 // C++0x [temp.spec]p5:
4843 // For a given template and a given set of template-arguments,
4844 // - an explicit instantiation definition shall appear at most once
4845 // in a program,
4846 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
4847 << PrevDecl;
4848 Diag(PrevPointOfInstantiation,
4849 diag::note_previous_explicit_instantiation);
4850 HasNoEffect = true;
4851 return false;
4853 break;
4856 assert(false && "Missing specialization/instantiation case?");
4858 return false;
4861 /// \brief Perform semantic analysis for the given dependent function
4862 /// template specialization. The only possible way to get a dependent
4863 /// function template specialization is with a friend declaration,
4864 /// like so:
4866 /// template <class T> void foo(T);
4867 /// template <class T> class A {
4868 /// friend void foo<>(T);
4869 /// };
4871 /// There really isn't any useful analysis we can do here, so we
4872 /// just store the information.
4873 bool
4874 Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4875 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4876 LookupResult &Previous) {
4877 // Remove anything from Previous that isn't a function template in
4878 // the correct context.
4879 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
4880 LookupResult::Filter F = Previous.makeFilter();
4881 while (F.hasNext()) {
4882 NamedDecl *D = F.next()->getUnderlyingDecl();
4883 if (!isa<FunctionTemplateDecl>(D) ||
4884 !FDLookupContext->InEnclosingNamespaceSetOf(
4885 D->getDeclContext()->getRedeclContext()))
4886 F.erase();
4888 F.done();
4890 // Should this be diagnosed here?
4891 if (Previous.empty()) return true;
4893 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4894 ExplicitTemplateArgs);
4895 return false;
4898 /// \brief Perform semantic analysis for the given function template
4899 /// specialization.
4901 /// This routine performs all of the semantic analysis required for an
4902 /// explicit function template specialization. On successful completion,
4903 /// the function declaration \p FD will become a function template
4904 /// specialization.
4906 /// \param FD the function declaration, which will be updated to become a
4907 /// function template specialization.
4909 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4910 /// if any. Note that this may be valid info even when 0 arguments are
4911 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
4912 /// as it anyway contains info on the angle brackets locations.
4914 /// \param PrevDecl the set of declarations that may be specialized by
4915 /// this function specialization.
4916 bool
4917 Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
4918 const TemplateArgumentListInfo *ExplicitTemplateArgs,
4919 LookupResult &Previous) {
4920 // The set of function template specializations that could match this
4921 // explicit function template specialization.
4922 UnresolvedSet<8> Candidates;
4924 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
4925 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4926 I != E; ++I) {
4927 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4928 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
4929 // Only consider templates found within the same semantic lookup scope as
4930 // FD.
4931 if (!FDLookupContext->InEnclosingNamespaceSetOf(
4932 Ovl->getDeclContext()->getRedeclContext()))
4933 continue;
4935 // C++ [temp.expl.spec]p11:
4936 // A trailing template-argument can be left unspecified in the
4937 // template-id naming an explicit function template specialization
4938 // provided it can be deduced from the function argument type.
4939 // Perform template argument deduction to determine whether we may be
4940 // specializing this template.
4941 // FIXME: It is somewhat wasteful to build
4942 TemplateDeductionInfo Info(Context, FD->getLocation());
4943 FunctionDecl *Specialization = 0;
4944 if (TemplateDeductionResult TDK
4945 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
4946 FD->getType(),
4947 Specialization,
4948 Info)) {
4949 // FIXME: Template argument deduction failed; record why it failed, so
4950 // that we can provide nifty diagnostics.
4951 (void)TDK;
4952 continue;
4955 // Record this candidate.
4956 Candidates.addDecl(Specialization, I.getAccess());
4960 // Find the most specialized function template.
4961 UnresolvedSetIterator Result
4962 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4963 TPOC_Other, 0, FD->getLocation(),
4964 PDiag(diag::err_function_template_spec_no_match)
4965 << FD->getDeclName(),
4966 PDiag(diag::err_function_template_spec_ambiguous)
4967 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
4968 PDiag(diag::note_function_template_spec_matched));
4969 if (Result == Candidates.end())
4970 return true;
4972 // Ignore access information; it doesn't figure into redeclaration checking.
4973 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
4974 Specialization->setLocation(FD->getLocation());
4976 // FIXME: Check if the prior specialization has a point of instantiation.
4977 // If so, we have run afoul of .
4979 // If this is a friend declaration, then we're not really declaring
4980 // an explicit specialization.
4981 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
4983 // Check the scope of this explicit specialization.
4984 if (!isFriend &&
4985 CheckTemplateSpecializationScope(*this,
4986 Specialization->getPrimaryTemplate(),
4987 Specialization, FD->getLocation(),
4988 false))
4989 return true;
4991 // C++ [temp.expl.spec]p6:
4992 // If a template, a member template or the member of a class template is
4993 // explicitly specialized then that specialization shall be declared
4994 // before the first use of that specialization that would cause an implicit
4995 // instantiation to take place, in every translation unit in which such a
4996 // use occurs; no diagnostic is required.
4997 FunctionTemplateSpecializationInfo *SpecInfo
4998 = Specialization->getTemplateSpecializationInfo();
4999 assert(SpecInfo && "Function template specialization info missing?");
5001 bool HasNoEffect = false;
5002 if (!isFriend &&
5003 CheckSpecializationInstantiationRedecl(FD->getLocation(),
5004 TSK_ExplicitSpecialization,
5005 Specialization,
5006 SpecInfo->getTemplateSpecializationKind(),
5007 SpecInfo->getPointOfInstantiation(),
5008 HasNoEffect))
5009 return true;
5011 // Mark the prior declaration as an explicit specialization, so that later
5012 // clients know that this is an explicit specialization.
5013 if (!isFriend) {
5014 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
5015 MarkUnusedFileScopedDecl(Specialization);
5018 // Turn the given function declaration into a function template
5019 // specialization, with the template arguments from the previous
5020 // specialization.
5021 // Take copies of (semantic and syntactic) template argument lists.
5022 const TemplateArgumentList* TemplArgs = new (Context)
5023 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
5024 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs
5025 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0;
5026 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
5027 TemplArgs, /*InsertPos=*/0,
5028 SpecInfo->getTemplateSpecializationKind(),
5029 TemplArgsAsWritten);
5031 // The "previous declaration" for this function template specialization is
5032 // the prior function template specialization.
5033 Previous.clear();
5034 Previous.addDecl(Specialization);
5035 return false;
5038 /// \brief Perform semantic analysis for the given non-template member
5039 /// specialization.
5041 /// This routine performs all of the semantic analysis required for an
5042 /// explicit member function specialization. On successful completion,
5043 /// the function declaration \p FD will become a member function
5044 /// specialization.
5046 /// \param Member the member declaration, which will be updated to become a
5047 /// specialization.
5049 /// \param Previous the set of declarations, one of which may be specialized
5050 /// by this function specialization; the set will be modified to contain the
5051 /// redeclared member.
5052 bool
5053 Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
5054 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
5056 // Try to find the member we are instantiating.
5057 NamedDecl *Instantiation = 0;
5058 NamedDecl *InstantiatedFrom = 0;
5059 MemberSpecializationInfo *MSInfo = 0;
5061 if (Previous.empty()) {
5062 // Nowhere to look anyway.
5063 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
5064 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5065 I != E; ++I) {
5066 NamedDecl *D = (*I)->getUnderlyingDecl();
5067 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
5068 if (Context.hasSameType(Function->getType(), Method->getType())) {
5069 Instantiation = Method;
5070 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
5071 MSInfo = Method->getMemberSpecializationInfo();
5072 break;
5076 } else if (isa<VarDecl>(Member)) {
5077 VarDecl *PrevVar;
5078 if (Previous.isSingleResult() &&
5079 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
5080 if (PrevVar->isStaticDataMember()) {
5081 Instantiation = PrevVar;
5082 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
5083 MSInfo = PrevVar->getMemberSpecializationInfo();
5085 } else if (isa<RecordDecl>(Member)) {
5086 CXXRecordDecl *PrevRecord;
5087 if (Previous.isSingleResult() &&
5088 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
5089 Instantiation = PrevRecord;
5090 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
5091 MSInfo = PrevRecord->getMemberSpecializationInfo();
5095 if (!Instantiation) {
5096 // There is no previous declaration that matches. Since member
5097 // specializations are always out-of-line, the caller will complain about
5098 // this mismatch later.
5099 return false;
5102 // If this is a friend, just bail out here before we start turning
5103 // things into explicit specializations.
5104 if (Member->getFriendObjectKind() != Decl::FOK_None) {
5105 // Preserve instantiation information.
5106 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
5107 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
5108 cast<CXXMethodDecl>(InstantiatedFrom),
5109 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
5110 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
5111 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
5112 cast<CXXRecordDecl>(InstantiatedFrom),
5113 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
5116 Previous.clear();
5117 Previous.addDecl(Instantiation);
5118 return false;
5121 // Make sure that this is a specialization of a member.
5122 if (!InstantiatedFrom) {
5123 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
5124 << Member;
5125 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
5126 return true;
5129 // C++ [temp.expl.spec]p6:
5130 // If a template, a member template or the member of a class template is
5131 // explicitly specialized then that spe- cialization shall be declared
5132 // before the first use of that specialization that would cause an implicit
5133 // instantiation to take place, in every translation unit in which such a
5134 // use occurs; no diagnostic is required.
5135 assert(MSInfo && "Member specialization info missing?");
5137 bool HasNoEffect = false;
5138 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
5139 TSK_ExplicitSpecialization,
5140 Instantiation,
5141 MSInfo->getTemplateSpecializationKind(),
5142 MSInfo->getPointOfInstantiation(),
5143 HasNoEffect))
5144 return true;
5146 // Check the scope of this explicit specialization.
5147 if (CheckTemplateSpecializationScope(*this,
5148 InstantiatedFrom,
5149 Instantiation, Member->getLocation(),
5150 false))
5151 return true;
5153 // Note that this is an explicit instantiation of a member.
5154 // the original declaration to note that it is an explicit specialization
5155 // (if it was previously an implicit instantiation). This latter step
5156 // makes bookkeeping easier.
5157 if (isa<FunctionDecl>(Member)) {
5158 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
5159 if (InstantiationFunction->getTemplateSpecializationKind() ==
5160 TSK_ImplicitInstantiation) {
5161 InstantiationFunction->setTemplateSpecializationKind(
5162 TSK_ExplicitSpecialization);
5163 InstantiationFunction->setLocation(Member->getLocation());
5166 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
5167 cast<CXXMethodDecl>(InstantiatedFrom),
5168 TSK_ExplicitSpecialization);
5169 MarkUnusedFileScopedDecl(InstantiationFunction);
5170 } else if (isa<VarDecl>(Member)) {
5171 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
5172 if (InstantiationVar->getTemplateSpecializationKind() ==
5173 TSK_ImplicitInstantiation) {
5174 InstantiationVar->setTemplateSpecializationKind(
5175 TSK_ExplicitSpecialization);
5176 InstantiationVar->setLocation(Member->getLocation());
5179 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
5180 cast<VarDecl>(InstantiatedFrom),
5181 TSK_ExplicitSpecialization);
5182 MarkUnusedFileScopedDecl(InstantiationVar);
5183 } else {
5184 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
5185 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
5186 if (InstantiationClass->getTemplateSpecializationKind() ==
5187 TSK_ImplicitInstantiation) {
5188 InstantiationClass->setTemplateSpecializationKind(
5189 TSK_ExplicitSpecialization);
5190 InstantiationClass->setLocation(Member->getLocation());
5193 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
5194 cast<CXXRecordDecl>(InstantiatedFrom),
5195 TSK_ExplicitSpecialization);
5198 // Save the caller the trouble of having to figure out which declaration
5199 // this specialization matches.
5200 Previous.clear();
5201 Previous.addDecl(Instantiation);
5202 return false;
5205 /// \brief Check the scope of an explicit instantiation.
5207 /// \returns true if a serious error occurs, false otherwise.
5208 static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
5209 SourceLocation InstLoc,
5210 bool WasQualifiedName) {
5211 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
5212 DeclContext *CurContext = S.CurContext->getRedeclContext();
5214 if (CurContext->isRecord()) {
5215 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
5216 << D;
5217 return true;
5220 // C++0x [temp.explicit]p2:
5221 // An explicit instantiation shall appear in an enclosing namespace of its
5222 // template.
5224 // This is DR275, which we do not retroactively apply to C++98/03.
5225 if (S.getLangOptions().CPlusPlus0x &&
5226 !CurContext->Encloses(OrigContext)) {
5227 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext))
5228 S.Diag(InstLoc,
5229 S.getLangOptions().CPlusPlus0x?
5230 diag::err_explicit_instantiation_out_of_scope
5231 : diag::warn_explicit_instantiation_out_of_scope_0x)
5232 << D << NS;
5233 else
5234 S.Diag(InstLoc,
5235 S.getLangOptions().CPlusPlus0x?
5236 diag::err_explicit_instantiation_must_be_global
5237 : diag::warn_explicit_instantiation_out_of_scope_0x)
5238 << D;
5239 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
5240 return false;
5243 // C++0x [temp.explicit]p2:
5244 // If the name declared in the explicit instantiation is an unqualified
5245 // name, the explicit instantiation shall appear in the namespace where
5246 // its template is declared or, if that namespace is inline (7.3.1), any
5247 // namespace from its enclosing namespace set.
5248 if (WasQualifiedName)
5249 return false;
5251 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
5252 return false;
5254 S.Diag(InstLoc,
5255 S.getLangOptions().CPlusPlus0x?
5256 diag::err_explicit_instantiation_unqualified_wrong_namespace
5257 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
5258 << D << OrigContext;
5259 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
5260 return false;
5263 /// \brief Determine whether the given scope specifier has a template-id in it.
5264 static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
5265 if (!SS.isSet())
5266 return false;
5268 // C++0x [temp.explicit]p2:
5269 // If the explicit instantiation is for a member function, a member class
5270 // or a static data member of a class template specialization, the name of
5271 // the class template specialization in the qualified-id for the member
5272 // name shall be a simple-template-id.
5274 // C++98 has the same restriction, just worded differently.
5275 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
5276 NNS; NNS = NNS->getPrefix())
5277 if (const Type *T = NNS->getAsType())
5278 if (isa<TemplateSpecializationType>(T))
5279 return true;
5281 return false;
5284 // Explicit instantiation of a class template specialization
5285 DeclResult
5286 Sema::ActOnExplicitInstantiation(Scope *S,
5287 SourceLocation ExternLoc,
5288 SourceLocation TemplateLoc,
5289 unsigned TagSpec,
5290 SourceLocation KWLoc,
5291 const CXXScopeSpec &SS,
5292 TemplateTy TemplateD,
5293 SourceLocation TemplateNameLoc,
5294 SourceLocation LAngleLoc,
5295 ASTTemplateArgsPtr TemplateArgsIn,
5296 SourceLocation RAngleLoc,
5297 AttributeList *Attr) {
5298 // Find the class template we're specializing
5299 TemplateName Name = TemplateD.getAsVal<TemplateName>();
5300 ClassTemplateDecl *ClassTemplate
5301 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
5303 // Check that the specialization uses the same tag kind as the
5304 // original template.
5305 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
5306 assert(Kind != TTK_Enum &&
5307 "Invalid enum tag in class template explicit instantiation!");
5308 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
5309 Kind, KWLoc,
5310 *ClassTemplate->getIdentifier())) {
5311 Diag(KWLoc, diag::err_use_with_wrong_tag)
5312 << ClassTemplate
5313 << FixItHint::CreateReplacement(KWLoc,
5314 ClassTemplate->getTemplatedDecl()->getKindName());
5315 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
5316 diag::note_previous_use);
5317 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
5320 // C++0x [temp.explicit]p2:
5321 // There are two forms of explicit instantiation: an explicit instantiation
5322 // definition and an explicit instantiation declaration. An explicit
5323 // instantiation declaration begins with the extern keyword. [...]
5324 TemplateSpecializationKind TSK
5325 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5326 : TSK_ExplicitInstantiationDeclaration;
5328 // Translate the parser's template argument list in our AST format.
5329 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
5330 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
5332 // Check that the template argument list is well-formed for this
5333 // template.
5334 llvm::SmallVector<TemplateArgument, 4> Converted;
5335 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
5336 TemplateArgs, false, Converted))
5337 return true;
5339 assert((Converted.size() == ClassTemplate->getTemplateParameters()->size()) &&
5340 "Converted template argument list is too short!");
5342 // Find the class template specialization declaration that
5343 // corresponds to these arguments.
5344 void *InsertPos = 0;
5345 ClassTemplateSpecializationDecl *PrevDecl
5346 = ClassTemplate->findSpecialization(Converted.data(),
5347 Converted.size(), InsertPos);
5349 TemplateSpecializationKind PrevDecl_TSK
5350 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
5352 // C++0x [temp.explicit]p2:
5353 // [...] An explicit instantiation shall appear in an enclosing
5354 // namespace of its template. [...]
5356 // This is C++ DR 275.
5357 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
5358 SS.isSet()))
5359 return true;
5361 ClassTemplateSpecializationDecl *Specialization = 0;
5363 bool HasNoEffect = false;
5364 if (PrevDecl) {
5365 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
5366 PrevDecl, PrevDecl_TSK,
5367 PrevDecl->getPointOfInstantiation(),
5368 HasNoEffect))
5369 return PrevDecl;
5371 // Even though HasNoEffect == true means that this explicit instantiation
5372 // has no effect on semantics, we go on to put its syntax in the AST.
5374 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
5375 PrevDecl_TSK == TSK_Undeclared) {
5376 // Since the only prior class template specialization with these
5377 // arguments was referenced but not declared, reuse that
5378 // declaration node as our own, updating the source location
5379 // for the template name to reflect our new declaration.
5380 // (Other source locations will be updated later.)
5381 Specialization = PrevDecl;
5382 Specialization->setLocation(TemplateNameLoc);
5383 PrevDecl = 0;
5387 if (!Specialization) {
5388 // Create a new class template specialization declaration node for
5389 // this explicit specialization.
5390 Specialization
5391 = ClassTemplateSpecializationDecl::Create(Context, Kind,
5392 ClassTemplate->getDeclContext(),
5393 TemplateNameLoc,
5394 ClassTemplate,
5395 Converted.data(),
5396 Converted.size(),
5397 PrevDecl);
5398 SetNestedNameSpecifier(Specialization, SS);
5400 if (!HasNoEffect && !PrevDecl) {
5401 // Insert the new specialization.
5402 ClassTemplate->AddSpecialization(Specialization, InsertPos);
5406 // Build the fully-sugared type for this explicit instantiation as
5407 // the user wrote in the explicit instantiation itself. This means
5408 // that we'll pretty-print the type retrieved from the
5409 // specialization's declaration the way that the user actually wrote
5410 // the explicit instantiation, rather than formatting the name based
5411 // on the "canonical" representation used to store the template
5412 // arguments in the specialization.
5413 TypeSourceInfo *WrittenTy
5414 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
5415 TemplateArgs,
5416 Context.getTypeDeclType(Specialization));
5417 Specialization->setTypeAsWritten(WrittenTy);
5418 TemplateArgsIn.release();
5420 // Set source locations for keywords.
5421 Specialization->setExternLoc(ExternLoc);
5422 Specialization->setTemplateKeywordLoc(TemplateLoc);
5424 // Add the explicit instantiation into its lexical context. However,
5425 // since explicit instantiations are never found by name lookup, we
5426 // just put it into the declaration context directly.
5427 Specialization->setLexicalDeclContext(CurContext);
5428 CurContext->addDecl(Specialization);
5430 // Syntax is now OK, so return if it has no other effect on semantics.
5431 if (HasNoEffect) {
5432 // Set the template specialization kind.
5433 Specialization->setTemplateSpecializationKind(TSK);
5434 return Specialization;
5437 // C++ [temp.explicit]p3:
5438 // A definition of a class template or class member template
5439 // shall be in scope at the point of the explicit instantiation of
5440 // the class template or class member template.
5442 // This check comes when we actually try to perform the
5443 // instantiation.
5444 ClassTemplateSpecializationDecl *Def
5445 = cast_or_null<ClassTemplateSpecializationDecl>(
5446 Specialization->getDefinition());
5447 if (!Def)
5448 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
5449 else if (TSK == TSK_ExplicitInstantiationDefinition) {
5450 MarkVTableUsed(TemplateNameLoc, Specialization, true);
5451 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
5454 // Instantiate the members of this class template specialization.
5455 Def = cast_or_null<ClassTemplateSpecializationDecl>(
5456 Specialization->getDefinition());
5457 if (Def) {
5458 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
5460 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
5461 // TSK_ExplicitInstantiationDefinition
5462 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
5463 TSK == TSK_ExplicitInstantiationDefinition)
5464 Def->setTemplateSpecializationKind(TSK);
5466 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
5469 // Set the template specialization kind.
5470 Specialization->setTemplateSpecializationKind(TSK);
5471 return Specialization;
5474 // Explicit instantiation of a member class of a class template.
5475 DeclResult
5476 Sema::ActOnExplicitInstantiation(Scope *S,
5477 SourceLocation ExternLoc,
5478 SourceLocation TemplateLoc,
5479 unsigned TagSpec,
5480 SourceLocation KWLoc,
5481 CXXScopeSpec &SS,
5482 IdentifierInfo *Name,
5483 SourceLocation NameLoc,
5484 AttributeList *Attr) {
5486 bool Owned = false;
5487 bool IsDependent = false;
5488 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
5489 KWLoc, SS, Name, NameLoc, Attr, AS_none,
5490 MultiTemplateParamsArg(*this, 0, 0),
5491 Owned, IsDependent, false, false,
5492 TypeResult());
5493 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
5495 if (!TagD)
5496 return true;
5498 TagDecl *Tag = cast<TagDecl>(TagD);
5499 if (Tag->isEnum()) {
5500 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
5501 << Context.getTypeDeclType(Tag);
5502 return true;
5505 if (Tag->isInvalidDecl())
5506 return true;
5508 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
5509 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
5510 if (!Pattern) {
5511 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
5512 << Context.getTypeDeclType(Record);
5513 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
5514 return true;
5517 // C++0x [temp.explicit]p2:
5518 // If the explicit instantiation is for a class or member class, the
5519 // elaborated-type-specifier in the declaration shall include a
5520 // simple-template-id.
5522 // C++98 has the same restriction, just worded differently.
5523 if (!ScopeSpecifierHasTemplateId(SS))
5524 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
5525 << Record << SS.getRange();
5527 // C++0x [temp.explicit]p2:
5528 // There are two forms of explicit instantiation: an explicit instantiation
5529 // definition and an explicit instantiation declaration. An explicit
5530 // instantiation declaration begins with the extern keyword. [...]
5531 TemplateSpecializationKind TSK
5532 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5533 : TSK_ExplicitInstantiationDeclaration;
5535 // C++0x [temp.explicit]p2:
5536 // [...] An explicit instantiation shall appear in an enclosing
5537 // namespace of its template. [...]
5539 // This is C++ DR 275.
5540 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
5542 // Verify that it is okay to explicitly instantiate here.
5543 CXXRecordDecl *PrevDecl
5544 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
5545 if (!PrevDecl && Record->getDefinition())
5546 PrevDecl = Record;
5547 if (PrevDecl) {
5548 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
5549 bool HasNoEffect = false;
5550 assert(MSInfo && "No member specialization information?");
5551 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
5552 PrevDecl,
5553 MSInfo->getTemplateSpecializationKind(),
5554 MSInfo->getPointOfInstantiation(),
5555 HasNoEffect))
5556 return true;
5557 if (HasNoEffect)
5558 return TagD;
5561 CXXRecordDecl *RecordDef
5562 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
5563 if (!RecordDef) {
5564 // C++ [temp.explicit]p3:
5565 // A definition of a member class of a class template shall be in scope
5566 // at the point of an explicit instantiation of the member class.
5567 CXXRecordDecl *Def
5568 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
5569 if (!Def) {
5570 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
5571 << 0 << Record->getDeclName() << Record->getDeclContext();
5572 Diag(Pattern->getLocation(), diag::note_forward_declaration)
5573 << Pattern;
5574 return true;
5575 } else {
5576 if (InstantiateClass(NameLoc, Record, Def,
5577 getTemplateInstantiationArgs(Record),
5578 TSK))
5579 return true;
5581 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
5582 if (!RecordDef)
5583 return true;
5587 // Instantiate all of the members of the class.
5588 InstantiateClassMembers(NameLoc, RecordDef,
5589 getTemplateInstantiationArgs(Record), TSK);
5591 if (TSK == TSK_ExplicitInstantiationDefinition)
5592 MarkVTableUsed(NameLoc, RecordDef, true);
5594 // FIXME: We don't have any representation for explicit instantiations of
5595 // member classes. Such a representation is not needed for compilation, but it
5596 // should be available for clients that want to see all of the declarations in
5597 // the source code.
5598 return TagD;
5601 DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
5602 SourceLocation ExternLoc,
5603 SourceLocation TemplateLoc,
5604 Declarator &D) {
5605 // Explicit instantiations always require a name.
5606 // TODO: check if/when DNInfo should replace Name.
5607 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5608 DeclarationName Name = NameInfo.getName();
5609 if (!Name) {
5610 if (!D.isInvalidType())
5611 Diag(D.getDeclSpec().getSourceRange().getBegin(),
5612 diag::err_explicit_instantiation_requires_name)
5613 << D.getDeclSpec().getSourceRange()
5614 << D.getSourceRange();
5616 return true;
5619 // The scope passed in may not be a decl scope. Zip up the scope tree until
5620 // we find one that is.
5621 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5622 (S->getFlags() & Scope::TemplateParamScope) != 0)
5623 S = S->getParent();
5625 // Determine the type of the declaration.
5626 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
5627 QualType R = T->getType();
5628 if (R.isNull())
5629 return true;
5631 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5632 // Cannot explicitly instantiate a typedef.
5633 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
5634 << Name;
5635 return true;
5638 // C++0x [temp.explicit]p1:
5639 // [...] An explicit instantiation of a function template shall not use the
5640 // inline or constexpr specifiers.
5641 // Presumably, this also applies to member functions of class templates as
5642 // well.
5643 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
5644 Diag(D.getDeclSpec().getInlineSpecLoc(),
5645 diag::err_explicit_instantiation_inline)
5646 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
5648 // FIXME: check for constexpr specifier.
5650 // C++0x [temp.explicit]p2:
5651 // There are two forms of explicit instantiation: an explicit instantiation
5652 // definition and an explicit instantiation declaration. An explicit
5653 // instantiation declaration begins with the extern keyword. [...]
5654 TemplateSpecializationKind TSK
5655 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5656 : TSK_ExplicitInstantiationDeclaration;
5658 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
5659 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
5661 if (!R->isFunctionType()) {
5662 // C++ [temp.explicit]p1:
5663 // A [...] static data member of a class template can be explicitly
5664 // instantiated from the member definition associated with its class
5665 // template.
5666 if (Previous.isAmbiguous())
5667 return true;
5669 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
5670 if (!Prev || !Prev->isStaticDataMember()) {
5671 // We expect to see a data data member here.
5672 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
5673 << Name;
5674 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5675 P != PEnd; ++P)
5676 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
5677 return true;
5680 if (!Prev->getInstantiatedFromStaticDataMember()) {
5681 // FIXME: Check for explicit specialization?
5682 Diag(D.getIdentifierLoc(),
5683 diag::err_explicit_instantiation_data_member_not_instantiated)
5684 << Prev;
5685 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
5686 // FIXME: Can we provide a note showing where this was declared?
5687 return true;
5690 // C++0x [temp.explicit]p2:
5691 // If the explicit instantiation is for a member function, a member class
5692 // or a static data member of a class template specialization, the name of
5693 // the class template specialization in the qualified-id for the member
5694 // name shall be a simple-template-id.
5696 // C++98 has the same restriction, just worded differently.
5697 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5698 Diag(D.getIdentifierLoc(),
5699 diag::ext_explicit_instantiation_without_qualified_id)
5700 << Prev << D.getCXXScopeSpec().getRange();
5702 // Check the scope of this explicit instantiation.
5703 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
5705 // Verify that it is okay to explicitly instantiate here.
5706 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
5707 assert(MSInfo && "Missing static data member specialization info?");
5708 bool HasNoEffect = false;
5709 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
5710 MSInfo->getTemplateSpecializationKind(),
5711 MSInfo->getPointOfInstantiation(),
5712 HasNoEffect))
5713 return true;
5714 if (HasNoEffect)
5715 return (Decl*) 0;
5717 // Instantiate static data member.
5718 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
5719 if (TSK == TSK_ExplicitInstantiationDefinition)
5720 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev);
5722 // FIXME: Create an ExplicitInstantiation node?
5723 return (Decl*) 0;
5726 // If the declarator is a template-id, translate the parser's template
5727 // argument list into our AST format.
5728 bool HasExplicitTemplateArgs = false;
5729 TemplateArgumentListInfo TemplateArgs;
5730 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5731 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5732 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5733 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
5734 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5735 TemplateId->getTemplateArgs(),
5736 TemplateId->NumArgs);
5737 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
5738 HasExplicitTemplateArgs = true;
5739 TemplateArgsPtr.release();
5742 // C++ [temp.explicit]p1:
5743 // A [...] function [...] can be explicitly instantiated from its template.
5744 // A member function [...] of a class template can be explicitly
5745 // instantiated from the member definition associated with its class
5746 // template.
5747 UnresolvedSet<8> Matches;
5748 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5749 P != PEnd; ++P) {
5750 NamedDecl *Prev = *P;
5751 if (!HasExplicitTemplateArgs) {
5752 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
5753 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
5754 Matches.clear();
5756 Matches.addDecl(Method, P.getAccess());
5757 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
5758 break;
5763 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5764 if (!FunTmpl)
5765 continue;
5767 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
5768 FunctionDecl *Specialization = 0;
5769 if (TemplateDeductionResult TDK
5770 = DeduceTemplateArguments(FunTmpl,
5771 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
5772 R, Specialization, Info)) {
5773 // FIXME: Keep track of almost-matches?
5774 (void)TDK;
5775 continue;
5778 Matches.addDecl(Specialization, P.getAccess());
5781 // Find the most specialized function template specialization.
5782 UnresolvedSetIterator Result
5783 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other, 0,
5784 D.getIdentifierLoc(),
5785 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5786 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5787 PDiag(diag::note_explicit_instantiation_candidate));
5789 if (Result == Matches.end())
5790 return true;
5792 // Ignore access control bits, we don't need them for redeclaration checking.
5793 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
5795 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
5796 Diag(D.getIdentifierLoc(),
5797 diag::err_explicit_instantiation_member_function_not_instantiated)
5798 << Specialization
5799 << (Specialization->getTemplateSpecializationKind() ==
5800 TSK_ExplicitSpecialization);
5801 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5802 return true;
5805 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
5806 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5807 PrevDecl = Specialization;
5809 if (PrevDecl) {
5810 bool HasNoEffect = false;
5811 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
5812 PrevDecl,
5813 PrevDecl->getTemplateSpecializationKind(),
5814 PrevDecl->getPointOfInstantiation(),
5815 HasNoEffect))
5816 return true;
5818 // FIXME: We may still want to build some representation of this
5819 // explicit specialization.
5820 if (HasNoEffect)
5821 return (Decl*) 0;
5824 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
5826 if (TSK == TSK_ExplicitInstantiationDefinition)
5827 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
5829 // C++0x [temp.explicit]p2:
5830 // If the explicit instantiation is for a member function, a member class
5831 // or a static data member of a class template specialization, the name of
5832 // the class template specialization in the qualified-id for the member
5833 // name shall be a simple-template-id.
5835 // C++98 has the same restriction, just worded differently.
5836 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
5837 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
5838 D.getCXXScopeSpec().isSet() &&
5839 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5840 Diag(D.getIdentifierLoc(),
5841 diag::ext_explicit_instantiation_without_qualified_id)
5842 << Specialization << D.getCXXScopeSpec().getRange();
5844 CheckExplicitInstantiationScope(*this,
5845 FunTmpl? (NamedDecl *)FunTmpl
5846 : Specialization->getInstantiatedFromMemberFunction(),
5847 D.getIdentifierLoc(),
5848 D.getCXXScopeSpec().isSet());
5850 // FIXME: Create some kind of ExplicitInstantiationDecl here.
5851 return (Decl*) 0;
5854 TypeResult
5855 Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5856 const CXXScopeSpec &SS, IdentifierInfo *Name,
5857 SourceLocation TagLoc, SourceLocation NameLoc) {
5858 // This has to hold, because SS is expected to be defined.
5859 assert(Name && "Expected a name in a dependent tag");
5861 NestedNameSpecifier *NNS
5862 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5863 if (!NNS)
5864 return true;
5866 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
5868 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
5869 Diag(NameLoc, diag::err_dependent_tag_decl)
5870 << (TUK == TUK_Definition) << Kind << SS.getRange();
5871 return true;
5874 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
5875 return ParsedType::make(Context.getDependentNameType(Kwd, NNS, Name));
5878 TypeResult
5879 Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5880 const CXXScopeSpec &SS, const IdentifierInfo &II,
5881 SourceLocation IdLoc) {
5882 NestedNameSpecifier *NNS
5883 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5884 if (!NNS)
5885 return true;
5887 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5888 !getLangOptions().CPlusPlus0x)
5889 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5890 << FixItHint::CreateRemoval(TypenameLoc);
5892 QualType T = CheckTypenameType(ETK_Typename, NNS, II,
5893 TypenameLoc, SS.getRange(), IdLoc);
5894 if (T.isNull())
5895 return true;
5897 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5898 if (isa<DependentNameType>(T)) {
5899 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
5900 TL.setKeywordLoc(TypenameLoc);
5901 TL.setQualifierRange(SS.getRange());
5902 TL.setNameLoc(IdLoc);
5903 } else {
5904 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
5905 TL.setKeywordLoc(TypenameLoc);
5906 TL.setQualifierRange(SS.getRange());
5907 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
5910 return CreateParsedType(T, TSI);
5913 TypeResult
5914 Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5915 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
5916 ParsedType Ty) {
5917 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5918 !getLangOptions().CPlusPlus0x)
5919 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5920 << FixItHint::CreateRemoval(TypenameLoc);
5922 TypeSourceInfo *InnerTSI = 0;
5923 QualType T = GetTypeFromParser(Ty, &InnerTSI);
5925 assert(isa<TemplateSpecializationType>(T) &&
5926 "Expected a template specialization type");
5928 if (computeDeclContext(SS, false)) {
5929 // If we can compute a declaration context, then the "typename"
5930 // keyword was superfluous. Just build an ElaboratedType to keep
5931 // track of the nested-name-specifier.
5933 // Push the inner type, preserving its source locations if possible.
5934 TypeLocBuilder Builder;
5935 if (InnerTSI)
5936 Builder.pushFullCopy(InnerTSI->getTypeLoc());
5937 else
5938 Builder.push<TemplateSpecializationTypeLoc>(T).initialize(Context,
5939 TemplateLoc);
5941 /* Note: NNS already embedded in template specialization type T. */
5942 T = Context.getElaboratedType(ETK_Typename, /*NNS=*/0, T);
5943 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
5944 TL.setKeywordLoc(TypenameLoc);
5945 TL.setQualifierRange(SS.getRange());
5947 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
5948 return CreateParsedType(T, TSI);
5951 // TODO: it's really silly that we make a template specialization
5952 // type earlier only to drop it again here.
5953 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
5954 DependentTemplateName *DTN =
5955 TST->getTemplateName().getAsDependentTemplateName();
5956 assert(DTN && "dependent template has non-dependent name?");
5957 assert(DTN->getQualifier()
5958 == static_cast<NestedNameSpecifier*>(SS.getScopeRep()));
5959 T = Context.getDependentTemplateSpecializationType(ETK_Typename,
5960 DTN->getQualifier(),
5961 DTN->getIdentifier(),
5962 TST->getNumArgs(),
5963 TST->getArgs());
5964 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5965 DependentTemplateSpecializationTypeLoc TL =
5966 cast<DependentTemplateSpecializationTypeLoc>(TSI->getTypeLoc());
5967 if (InnerTSI) {
5968 TemplateSpecializationTypeLoc TSTL =
5969 cast<TemplateSpecializationTypeLoc>(InnerTSI->getTypeLoc());
5970 TL.setLAngleLoc(TSTL.getLAngleLoc());
5971 TL.setRAngleLoc(TSTL.getRAngleLoc());
5972 for (unsigned I = 0, E = TST->getNumArgs(); I != E; ++I)
5973 TL.setArgLocInfo(I, TSTL.getArgLocInfo(I));
5974 } else {
5975 // FIXME: Poor source-location information here.
5976 TL.initializeLocal(Context, TemplateLoc);
5978 TL.setKeywordLoc(TypenameLoc);
5979 TL.setQualifierRange(SS.getRange());
5980 return CreateParsedType(T, TSI);
5983 /// \brief Build the type that describes a C++ typename specifier,
5984 /// e.g., "typename T::type".
5985 QualType
5986 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
5987 NestedNameSpecifier *NNS, const IdentifierInfo &II,
5988 SourceLocation KeywordLoc, SourceRange NNSRange,
5989 SourceLocation IILoc) {
5990 CXXScopeSpec SS;
5991 SS.setScopeRep(NNS);
5992 SS.setRange(NNSRange);
5994 DeclContext *Ctx = computeDeclContext(SS);
5995 if (!Ctx) {
5996 // If the nested-name-specifier is dependent and couldn't be
5997 // resolved to a type, build a typename type.
5998 assert(NNS->isDependent());
5999 return Context.getDependentNameType(Keyword, NNS, &II);
6002 // If the nested-name-specifier refers to the current instantiation,
6003 // the "typename" keyword itself is superfluous. In C++03, the
6004 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
6005 // allows such extraneous "typename" keywords, and we retroactively
6006 // apply this DR to C++03 code with only a warning. In any case we continue.
6008 if (RequireCompleteDeclContext(SS, Ctx))
6009 return QualType();
6011 DeclarationName Name(&II);
6012 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
6013 LookupQualifiedName(Result, Ctx);
6014 unsigned DiagID = 0;
6015 Decl *Referenced = 0;
6016 switch (Result.getResultKind()) {
6017 case LookupResult::NotFound:
6018 DiagID = diag::err_typename_nested_not_found;
6019 break;
6021 case LookupResult::FoundUnresolvedValue: {
6022 // We found a using declaration that is a value. Most likely, the using
6023 // declaration itself is meant to have the 'typename' keyword.
6024 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
6025 IILoc);
6026 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
6027 << Name << Ctx << FullRange;
6028 if (UnresolvedUsingValueDecl *Using
6029 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
6030 SourceLocation Loc = Using->getTargetNestedNameRange().getBegin();
6031 Diag(Loc, diag::note_using_value_decl_missing_typename)
6032 << FixItHint::CreateInsertion(Loc, "typename ");
6035 // Fall through to create a dependent typename type, from which we can recover
6036 // better.
6038 case LookupResult::NotFoundInCurrentInstantiation:
6039 // Okay, it's a member of an unknown instantiation.
6040 return Context.getDependentNameType(Keyword, NNS, &II);
6042 case LookupResult::Found:
6043 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
6044 // We found a type. Build an ElaboratedType, since the
6045 // typename-specifier was just sugar.
6046 return Context.getElaboratedType(ETK_Typename, NNS,
6047 Context.getTypeDeclType(Type));
6050 DiagID = diag::err_typename_nested_not_type;
6051 Referenced = Result.getFoundDecl();
6052 break;
6055 llvm_unreachable("unresolved using decl in non-dependent context");
6056 return QualType();
6058 case LookupResult::FoundOverloaded:
6059 DiagID = diag::err_typename_nested_not_type;
6060 Referenced = *Result.begin();
6061 break;
6063 case LookupResult::Ambiguous:
6064 return QualType();
6067 // If we get here, it's because name lookup did not find a
6068 // type. Emit an appropriate diagnostic and return an error.
6069 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
6070 IILoc);
6071 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
6072 if (Referenced)
6073 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
6074 << Name;
6075 return QualType();
6078 namespace {
6079 // See Sema::RebuildTypeInCurrentInstantiation
6080 class CurrentInstantiationRebuilder
6081 : public TreeTransform<CurrentInstantiationRebuilder> {
6082 SourceLocation Loc;
6083 DeclarationName Entity;
6085 public:
6086 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
6088 CurrentInstantiationRebuilder(Sema &SemaRef,
6089 SourceLocation Loc,
6090 DeclarationName Entity)
6091 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
6092 Loc(Loc), Entity(Entity) { }
6094 /// \brief Determine whether the given type \p T has already been
6095 /// transformed.
6097 /// For the purposes of type reconstruction, a type has already been
6098 /// transformed if it is NULL or if it is not dependent.
6099 bool AlreadyTransformed(QualType T) {
6100 return T.isNull() || !T->isDependentType();
6103 /// \brief Returns the location of the entity whose type is being
6104 /// rebuilt.
6105 SourceLocation getBaseLocation() { return Loc; }
6107 /// \brief Returns the name of the entity whose type is being rebuilt.
6108 DeclarationName getBaseEntity() { return Entity; }
6110 /// \brief Sets the "base" location and entity when that
6111 /// information is known based on another transformation.
6112 void setBase(SourceLocation Loc, DeclarationName Entity) {
6113 this->Loc = Loc;
6114 this->Entity = Entity;
6119 /// \brief Rebuilds a type within the context of the current instantiation.
6121 /// The type \p T is part of the type of an out-of-line member definition of
6122 /// a class template (or class template partial specialization) that was parsed
6123 /// and constructed before we entered the scope of the class template (or
6124 /// partial specialization thereof). This routine will rebuild that type now
6125 /// that we have entered the declarator's scope, which may produce different
6126 /// canonical types, e.g.,
6128 /// \code
6129 /// template<typename T>
6130 /// struct X {
6131 /// typedef T* pointer;
6132 /// pointer data();
6133 /// };
6135 /// template<typename T>
6136 /// typename X<T>::pointer X<T>::data() { ... }
6137 /// \endcode
6139 /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
6140 /// since we do not know that we can look into X<T> when we parsed the type.
6141 /// This function will rebuild the type, performing the lookup of "pointer"
6142 /// in X<T> and returning an ElaboratedType whose canonical type is the same
6143 /// as the canonical type of T*, allowing the return types of the out-of-line
6144 /// definition and the declaration to match.
6145 TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
6146 SourceLocation Loc,
6147 DeclarationName Name) {
6148 if (!T || !T->getType()->isDependentType())
6149 return T;
6151 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
6152 return Rebuilder.TransformType(T);
6155 ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
6156 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
6157 DeclarationName());
6158 return Rebuilder.TransformExpr(E);
6161 bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
6162 if (SS.isInvalid()) return true;
6164 NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6165 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
6166 DeclarationName());
6167 NestedNameSpecifier *Rebuilt =
6168 Rebuilder.TransformNestedNameSpecifier(NNS, SS.getRange());
6169 if (!Rebuilt) return true;
6171 SS.setScopeRep(Rebuilt);
6172 return false;
6175 /// \brief Produces a formatted string that describes the binding of
6176 /// template parameters to template arguments.
6177 std::string
6178 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6179 const TemplateArgumentList &Args) {
6180 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
6183 std::string
6184 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6185 const TemplateArgument *Args,
6186 unsigned NumArgs) {
6187 llvm::SmallString<128> Str;
6188 llvm::raw_svector_ostream Out(Str);
6190 if (!Params || Params->size() == 0 || NumArgs == 0)
6191 return std::string();
6193 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
6194 if (I >= NumArgs)
6195 break;
6197 if (I == 0)
6198 Out << "[with ";
6199 else
6200 Out << ", ";
6202 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
6203 Out << Id->getName();
6204 } else {
6205 Out << '$' << I;
6208 Out << " = ";
6209 Args[I].print(Context.PrintingPolicy, Out);
6212 Out << ']';
6213 return Out.str();