rename test
[clang.git] / lib / Sema / SemaTemplate.cpp
blob88ba3f9a8857d8298282e1935fbd11572de6cae0
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 ImpCastExprToType(E, T, CK_IntegralCast);
3712 return Owned(E);
3715 /// \brief Match two template parameters within template parameter lists.
3716 static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
3717 bool Complain,
3718 Sema::TemplateParameterListEqualKind Kind,
3719 SourceLocation TemplateArgLoc) {
3720 // Check the actual kind (type, non-type, template).
3721 if (Old->getKind() != New->getKind()) {
3722 if (Complain) {
3723 unsigned NextDiag = diag::err_template_param_different_kind;
3724 if (TemplateArgLoc.isValid()) {
3725 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3726 NextDiag = diag::note_template_param_different_kind;
3728 S.Diag(New->getLocation(), NextDiag)
3729 << (Kind != Sema::TPL_TemplateMatch);
3730 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
3731 << (Kind != Sema::TPL_TemplateMatch);
3734 return false;
3737 // Check that both are parameter packs are neither are parameter packs.
3738 // However, if we are matching a template template argument to a
3739 // template template parameter, the template template parameter can have
3740 // a parameter pack where the template template argument does not.
3741 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
3742 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
3743 Old->isTemplateParameterPack())) {
3744 if (Complain) {
3745 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
3746 if (TemplateArgLoc.isValid()) {
3747 S.Diag(TemplateArgLoc,
3748 diag::err_template_arg_template_params_mismatch);
3749 NextDiag = diag::note_template_parameter_pack_non_pack;
3752 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
3753 : isa<NonTypeTemplateParmDecl>(New)? 1
3754 : 2;
3755 S.Diag(New->getLocation(), NextDiag)
3756 << ParamKind << New->isParameterPack();
3757 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
3758 << ParamKind << Old->isParameterPack();
3761 return false;
3764 // For non-type template parameters, check the type of the parameter.
3765 if (NonTypeTemplateParmDecl *OldNTTP
3766 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
3767 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
3769 // If we are matching a template template argument to a template
3770 // template parameter and one of the non-type template parameter types
3771 // is dependent, then we must wait until template instantiation time
3772 // to actually compare the arguments.
3773 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
3774 (OldNTTP->getType()->isDependentType() ||
3775 NewNTTP->getType()->isDependentType()))
3776 return true;
3778 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
3779 if (Complain) {
3780 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
3781 if (TemplateArgLoc.isValid()) {
3782 S.Diag(TemplateArgLoc,
3783 diag::err_template_arg_template_params_mismatch);
3784 NextDiag = diag::note_template_nontype_parm_different_type;
3786 S.Diag(NewNTTP->getLocation(), NextDiag)
3787 << NewNTTP->getType()
3788 << (Kind != Sema::TPL_TemplateMatch);
3789 S.Diag(OldNTTP->getLocation(),
3790 diag::note_template_nontype_parm_prev_declaration)
3791 << OldNTTP->getType();
3794 return false;
3797 return true;
3800 // For template template parameters, check the template parameter types.
3801 // The template parameter lists of template template
3802 // parameters must agree.
3803 if (TemplateTemplateParmDecl *OldTTP
3804 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
3805 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
3806 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
3807 OldTTP->getTemplateParameters(),
3808 Complain,
3809 (Kind == Sema::TPL_TemplateMatch
3810 ? Sema::TPL_TemplateTemplateParmMatch
3811 : Kind),
3812 TemplateArgLoc);
3815 return true;
3818 /// \brief Diagnose a known arity mismatch when comparing template argument
3819 /// lists.
3820 static
3821 void DiagnoseTemplateParameterListArityMismatch(Sema &S,
3822 TemplateParameterList *New,
3823 TemplateParameterList *Old,
3824 Sema::TemplateParameterListEqualKind Kind,
3825 SourceLocation TemplateArgLoc) {
3826 unsigned NextDiag = diag::err_template_param_list_different_arity;
3827 if (TemplateArgLoc.isValid()) {
3828 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
3829 NextDiag = diag::note_template_param_list_different_arity;
3831 S.Diag(New->getTemplateLoc(), NextDiag)
3832 << (New->size() > Old->size())
3833 << (Kind != Sema::TPL_TemplateMatch)
3834 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
3835 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
3836 << (Kind != Sema::TPL_TemplateMatch)
3837 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
3840 /// \brief Determine whether the given template parameter lists are
3841 /// equivalent.
3843 /// \param New The new template parameter list, typically written in the
3844 /// source code as part of a new template declaration.
3846 /// \param Old The old template parameter list, typically found via
3847 /// name lookup of the template declared with this template parameter
3848 /// list.
3850 /// \param Complain If true, this routine will produce a diagnostic if
3851 /// the template parameter lists are not equivalent.
3853 /// \param Kind describes how we are to match the template parameter lists.
3855 /// \param TemplateArgLoc If this source location is valid, then we
3856 /// are actually checking the template parameter list of a template
3857 /// argument (New) against the template parameter list of its
3858 /// corresponding template template parameter (Old). We produce
3859 /// slightly different diagnostics in this scenario.
3861 /// \returns True if the template parameter lists are equal, false
3862 /// otherwise.
3863 bool
3864 Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
3865 TemplateParameterList *Old,
3866 bool Complain,
3867 TemplateParameterListEqualKind Kind,
3868 SourceLocation TemplateArgLoc) {
3869 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
3870 if (Complain)
3871 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
3872 TemplateArgLoc);
3874 return false;
3877 // C++0x [temp.arg.template]p3:
3878 // A template-argument matches a template template-parameter (call it P)
3879 // when each of the template parameters in the template-parameter-list of
3880 // the template-argument's corresponding class template or template alias
3881 // (call it A) matches the corresponding template parameter in the
3882 // template-parameter-list of P. [...]
3883 TemplateParameterList::iterator NewParm = New->begin();
3884 TemplateParameterList::iterator NewParmEnd = New->end();
3885 for (TemplateParameterList::iterator OldParm = Old->begin(),
3886 OldParmEnd = Old->end();
3887 OldParm != OldParmEnd; ++OldParm) {
3888 if (Kind != TPL_TemplateTemplateArgumentMatch ||
3889 !(*OldParm)->isTemplateParameterPack()) {
3890 if (NewParm == NewParmEnd) {
3891 if (Complain)
3892 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
3893 TemplateArgLoc);
3895 return false;
3898 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
3899 Kind, TemplateArgLoc))
3900 return false;
3902 ++NewParm;
3903 continue;
3906 // C++0x [temp.arg.template]p3:
3907 // [...] When P's template- parameter-list contains a template parameter
3908 // pack (14.5.3), the template parameter pack will match zero or more
3909 // template parameters or template parameter packs in the
3910 // template-parameter-list of A with the same type and form as the
3911 // template parameter pack in P (ignoring whether those template
3912 // parameters are template parameter packs).
3913 for (; NewParm != NewParmEnd; ++NewParm) {
3914 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
3915 Kind, TemplateArgLoc))
3916 return false;
3920 // Make sure we exhausted all of the arguments.
3921 if (NewParm != NewParmEnd) {
3922 if (Complain)
3923 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
3924 TemplateArgLoc);
3926 return false;
3929 return true;
3932 /// \brief Check whether a template can be declared within this scope.
3934 /// If the template declaration is valid in this scope, returns
3935 /// false. Otherwise, issues a diagnostic and returns true.
3936 bool
3937 Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
3938 // Find the nearest enclosing declaration scope.
3939 while ((S->getFlags() & Scope::DeclScope) == 0 ||
3940 (S->getFlags() & Scope::TemplateParamScope) != 0)
3941 S = S->getParent();
3943 // C++ [temp]p2:
3944 // A template-declaration can appear only as a namespace scope or
3945 // class scope declaration.
3946 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
3947 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
3948 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
3949 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
3950 << TemplateParams->getSourceRange();
3952 while (Ctx && isa<LinkageSpecDecl>(Ctx))
3953 Ctx = Ctx->getParent();
3955 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
3956 return false;
3958 return Diag(TemplateParams->getTemplateLoc(),
3959 diag::err_template_outside_namespace_or_class_scope)
3960 << TemplateParams->getSourceRange();
3963 /// \brief Determine what kind of template specialization the given declaration
3964 /// is.
3965 static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
3966 if (!D)
3967 return TSK_Undeclared;
3969 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
3970 return Record->getTemplateSpecializationKind();
3971 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
3972 return Function->getTemplateSpecializationKind();
3973 if (VarDecl *Var = dyn_cast<VarDecl>(D))
3974 return Var->getTemplateSpecializationKind();
3976 return TSK_Undeclared;
3979 /// \brief Check whether a specialization is well-formed in the current
3980 /// context.
3982 /// This routine determines whether a template specialization can be declared
3983 /// in the current context (C++ [temp.expl.spec]p2).
3985 /// \param S the semantic analysis object for which this check is being
3986 /// performed.
3988 /// \param Specialized the entity being specialized or instantiated, which
3989 /// may be a kind of template (class template, function template, etc.) or
3990 /// a member of a class template (member function, static data member,
3991 /// member class).
3993 /// \param PrevDecl the previous declaration of this entity, if any.
3995 /// \param Loc the location of the explicit specialization or instantiation of
3996 /// this entity.
3998 /// \param IsPartialSpecialization whether this is a partial specialization of
3999 /// a class template.
4001 /// \returns true if there was an error that we cannot recover from, false
4002 /// otherwise.
4003 static bool CheckTemplateSpecializationScope(Sema &S,
4004 NamedDecl *Specialized,
4005 NamedDecl *PrevDecl,
4006 SourceLocation Loc,
4007 bool IsPartialSpecialization) {
4008 // Keep these "kind" numbers in sync with the %select statements in the
4009 // various diagnostics emitted by this routine.
4010 int EntityKind = 0;
4011 if (isa<ClassTemplateDecl>(Specialized))
4012 EntityKind = IsPartialSpecialization? 1 : 0;
4013 else if (isa<FunctionTemplateDecl>(Specialized))
4014 EntityKind = 2;
4015 else if (isa<CXXMethodDecl>(Specialized))
4016 EntityKind = 3;
4017 else if (isa<VarDecl>(Specialized))
4018 EntityKind = 4;
4019 else if (isa<RecordDecl>(Specialized))
4020 EntityKind = 5;
4021 else {
4022 S.Diag(Loc, diag::err_template_spec_unknown_kind);
4023 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
4024 return true;
4027 // C++ [temp.expl.spec]p2:
4028 // An explicit specialization shall be declared in the namespace
4029 // of which the template is a member, or, for member templates, in
4030 // the namespace of which the enclosing class or enclosing class
4031 // template is a member. An explicit specialization of a member
4032 // function, member class or static data member of a class
4033 // template shall be declared in the namespace of which the class
4034 // template is a member. Such a declaration may also be a
4035 // definition. If the declaration is not a definition, the
4036 // specialization may be defined later in the name- space in which
4037 // the explicit specialization was declared, or in a namespace
4038 // that encloses the one in which the explicit specialization was
4039 // declared.
4040 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
4041 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
4042 << Specialized;
4043 return true;
4046 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
4047 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
4048 << Specialized;
4049 return true;
4052 // C++ [temp.class.spec]p6:
4053 // A class template partial specialization may be declared or redeclared
4054 // in any namespace scope in which its definition may be defined (14.5.1
4055 // and 14.5.2).
4056 bool ComplainedAboutScope = false;
4057 DeclContext *SpecializedContext
4058 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
4059 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
4060 if ((!PrevDecl ||
4061 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
4062 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
4063 // C++ [temp.exp.spec]p2:
4064 // An explicit specialization shall be declared in the namespace of which
4065 // the template is a member, or, for member templates, in the namespace
4066 // of which the enclosing class or enclosing class template is a member.
4067 // An explicit specialization of a member function, member class or
4068 // static data member of a class template shall be declared in the
4069 // namespace of which the class template is a member.
4071 // C++0x [temp.expl.spec]p2:
4072 // An explicit specialization shall be declared in a namespace enclosing
4073 // the specialized template.
4074 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext) &&
4075 !(S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext))) {
4076 bool IsCPlusPlus0xExtension
4077 = !S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext);
4078 if (isa<TranslationUnitDecl>(SpecializedContext))
4079 S.Diag(Loc, IsCPlusPlus0xExtension
4080 ? diag::ext_template_spec_decl_out_of_scope_global
4081 : diag::err_template_spec_decl_out_of_scope_global)
4082 << EntityKind << Specialized;
4083 else if (isa<NamespaceDecl>(SpecializedContext))
4084 S.Diag(Loc, IsCPlusPlus0xExtension
4085 ? diag::ext_template_spec_decl_out_of_scope
4086 : diag::err_template_spec_decl_out_of_scope)
4087 << EntityKind << Specialized
4088 << cast<NamedDecl>(SpecializedContext);
4090 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
4091 ComplainedAboutScope = true;
4095 // Make sure that this redeclaration (or definition) occurs in an enclosing
4096 // namespace.
4097 // Note that HandleDeclarator() performs this check for explicit
4098 // specializations of function templates, static data members, and member
4099 // functions, so we skip the check here for those kinds of entities.
4100 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
4101 // Should we refactor that check, so that it occurs later?
4102 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
4103 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
4104 isa<FunctionDecl>(Specialized))) {
4105 if (isa<TranslationUnitDecl>(SpecializedContext))
4106 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
4107 << EntityKind << Specialized;
4108 else if (isa<NamespaceDecl>(SpecializedContext))
4109 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
4110 << EntityKind << Specialized
4111 << cast<NamedDecl>(SpecializedContext);
4113 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
4116 // FIXME: check for specialization-after-instantiation errors and such.
4118 return false;
4121 /// \brief Subroutine of Sema::CheckClassTemplatePartialSpecializationArgs
4122 /// that checks non-type template partial specialization arguments.
4123 static bool CheckNonTypeClassTemplatePartialSpecializationArgs(Sema &S,
4124 NonTypeTemplateParmDecl *Param,
4125 const TemplateArgument *Args,
4126 unsigned NumArgs) {
4127 for (unsigned I = 0; I != NumArgs; ++I) {
4128 if (Args[I].getKind() == TemplateArgument::Pack) {
4129 if (CheckNonTypeClassTemplatePartialSpecializationArgs(S, Param,
4130 Args[I].pack_begin(),
4131 Args[I].pack_size()))
4132 return true;
4134 continue;
4137 Expr *ArgExpr = Args[I].getAsExpr();
4138 if (!ArgExpr) {
4139 continue;
4142 // We can have a pack expansion of any of the bullets below.
4143 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
4144 ArgExpr = Expansion->getPattern();
4146 // Strip off any implicit casts we added as part of type checking.
4147 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
4148 ArgExpr = ICE->getSubExpr();
4150 // C++ [temp.class.spec]p8:
4151 // A non-type argument is non-specialized if it is the name of a
4152 // non-type parameter. All other non-type arguments are
4153 // specialized.
4155 // Below, we check the two conditions that only apply to
4156 // specialized non-type arguments, so skip any non-specialized
4157 // arguments.
4158 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
4159 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
4160 continue;
4162 // C++ [temp.class.spec]p9:
4163 // Within the argument list of a class template partial
4164 // specialization, the following restrictions apply:
4165 // -- A partially specialized non-type argument expression
4166 // shall not involve a template parameter of the partial
4167 // specialization except when the argument expression is a
4168 // simple identifier.
4169 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
4170 S.Diag(ArgExpr->getLocStart(),
4171 diag::err_dependent_non_type_arg_in_partial_spec)
4172 << ArgExpr->getSourceRange();
4173 return true;
4176 // -- The type of a template parameter corresponding to a
4177 // specialized non-type argument shall not be dependent on a
4178 // parameter of the specialization.
4179 if (Param->getType()->isDependentType()) {
4180 S.Diag(ArgExpr->getLocStart(),
4181 diag::err_dependent_typed_non_type_arg_in_partial_spec)
4182 << Param->getType()
4183 << ArgExpr->getSourceRange();
4184 S.Diag(Param->getLocation(), diag::note_template_param_here);
4185 return true;
4189 return false;
4192 /// \brief Check the non-type template arguments of a class template
4193 /// partial specialization according to C++ [temp.class.spec]p9.
4195 /// \param TemplateParams the template parameters of the primary class
4196 /// template.
4198 /// \param TemplateArg the template arguments of the class template
4199 /// partial specialization.
4201 /// \returns true if there was an error, false otherwise.
4202 static bool CheckClassTemplatePartialSpecializationArgs(Sema &S,
4203 TemplateParameterList *TemplateParams,
4204 llvm::SmallVectorImpl<TemplateArgument> &TemplateArgs) {
4205 const TemplateArgument *ArgList = TemplateArgs.data();
4207 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
4208 NonTypeTemplateParmDecl *Param
4209 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
4210 if (!Param)
4211 continue;
4213 if (CheckNonTypeClassTemplatePartialSpecializationArgs(S, Param,
4214 &ArgList[I], 1))
4215 return true;
4218 return false;
4221 /// \brief Retrieve the previous declaration of the given declaration.
4222 static NamedDecl *getPreviousDecl(NamedDecl *ND) {
4223 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4224 return VD->getPreviousDeclaration();
4225 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
4226 return FD->getPreviousDeclaration();
4227 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
4228 return TD->getPreviousDeclaration();
4229 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
4230 return TD->getPreviousDeclaration();
4231 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4232 return FTD->getPreviousDeclaration();
4233 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
4234 return CTD->getPreviousDeclaration();
4235 return 0;
4238 DeclResult
4239 Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
4240 TagUseKind TUK,
4241 SourceLocation KWLoc,
4242 CXXScopeSpec &SS,
4243 TemplateTy TemplateD,
4244 SourceLocation TemplateNameLoc,
4245 SourceLocation LAngleLoc,
4246 ASTTemplateArgsPtr TemplateArgsIn,
4247 SourceLocation RAngleLoc,
4248 AttributeList *Attr,
4249 MultiTemplateParamsArg TemplateParameterLists) {
4250 assert(TUK != TUK_Reference && "References are not specializations");
4252 // Find the class template we're specializing
4253 TemplateName Name = TemplateD.getAsVal<TemplateName>();
4254 ClassTemplateDecl *ClassTemplate
4255 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
4257 if (!ClassTemplate) {
4258 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
4259 << (Name.getAsTemplateDecl() &&
4260 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
4261 return true;
4264 bool isExplicitSpecialization = false;
4265 bool isPartialSpecialization = false;
4267 // Check the validity of the template headers that introduce this
4268 // template.
4269 // FIXME: We probably shouldn't complain about these headers for
4270 // friend declarations.
4271 bool Invalid = false;
4272 TemplateParameterList *TemplateParams
4273 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS,
4274 (TemplateParameterList**)TemplateParameterLists.get(),
4275 TemplateParameterLists.size(),
4276 TUK == TUK_Friend,
4277 isExplicitSpecialization,
4278 Invalid);
4279 if (Invalid)
4280 return true;
4282 unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size();
4283 if (TemplateParams)
4284 --NumMatchedTemplateParamLists;
4286 if (TemplateParams && TemplateParams->size() > 0) {
4287 isPartialSpecialization = true;
4289 if (TUK == TUK_Friend) {
4290 Diag(KWLoc, diag::err_partial_specialization_friend)
4291 << SourceRange(LAngleLoc, RAngleLoc);
4292 return true;
4295 // C++ [temp.class.spec]p10:
4296 // The template parameter list of a specialization shall not
4297 // contain default template argument values.
4298 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
4299 Decl *Param = TemplateParams->getParam(I);
4300 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
4301 if (TTP->hasDefaultArgument()) {
4302 Diag(TTP->getDefaultArgumentLoc(),
4303 diag::err_default_arg_in_partial_spec);
4304 TTP->removeDefaultArgument();
4306 } else if (NonTypeTemplateParmDecl *NTTP
4307 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4308 if (Expr *DefArg = NTTP->getDefaultArgument()) {
4309 Diag(NTTP->getDefaultArgumentLoc(),
4310 diag::err_default_arg_in_partial_spec)
4311 << DefArg->getSourceRange();
4312 NTTP->removeDefaultArgument();
4314 } else {
4315 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
4316 if (TTP->hasDefaultArgument()) {
4317 Diag(TTP->getDefaultArgument().getLocation(),
4318 diag::err_default_arg_in_partial_spec)
4319 << TTP->getDefaultArgument().getSourceRange();
4320 TTP->removeDefaultArgument();
4324 } else if (TemplateParams) {
4325 if (TUK == TUK_Friend)
4326 Diag(KWLoc, diag::err_template_spec_friend)
4327 << FixItHint::CreateRemoval(
4328 SourceRange(TemplateParams->getTemplateLoc(),
4329 TemplateParams->getRAngleLoc()))
4330 << SourceRange(LAngleLoc, RAngleLoc);
4331 else
4332 isExplicitSpecialization = true;
4333 } else if (TUK != TUK_Friend) {
4334 Diag(KWLoc, diag::err_template_spec_needs_header)
4335 << FixItHint::CreateInsertion(KWLoc, "template<> ");
4336 isExplicitSpecialization = true;
4339 // Check that the specialization uses the same tag kind as the
4340 // original template.
4341 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4342 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
4343 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
4344 Kind, KWLoc,
4345 *ClassTemplate->getIdentifier())) {
4346 Diag(KWLoc, diag::err_use_with_wrong_tag)
4347 << ClassTemplate
4348 << FixItHint::CreateReplacement(KWLoc,
4349 ClassTemplate->getTemplatedDecl()->getKindName());
4350 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
4351 diag::note_previous_use);
4352 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4355 // Translate the parser's template argument list in our AST format.
4356 TemplateArgumentListInfo TemplateArgs;
4357 TemplateArgs.setLAngleLoc(LAngleLoc);
4358 TemplateArgs.setRAngleLoc(RAngleLoc);
4359 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4361 // Check for unexpanded parameter packs in any of the template arguments.
4362 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4363 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4364 UPPC_PartialSpecialization))
4365 return true;
4367 // Check that the template argument list is well-formed for this
4368 // template.
4369 llvm::SmallVector<TemplateArgument, 4> Converted;
4370 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4371 TemplateArgs, false, Converted))
4372 return true;
4374 assert((Converted.size() == ClassTemplate->getTemplateParameters()->size()) &&
4375 "Converted template argument list is too short!");
4377 // Find the class template (partial) specialization declaration that
4378 // corresponds to these arguments.
4379 if (isPartialSpecialization) {
4380 if (CheckClassTemplatePartialSpecializationArgs(*this,
4381 ClassTemplate->getTemplateParameters(),
4382 Converted))
4383 return true;
4385 if (!Name.isDependent() &&
4386 !TemplateSpecializationType::anyDependentTemplateArguments(
4387 TemplateArgs.getArgumentArray(),
4388 TemplateArgs.size())) {
4389 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4390 << ClassTemplate->getDeclName();
4391 isPartialSpecialization = false;
4395 void *InsertPos = 0;
4396 ClassTemplateSpecializationDecl *PrevDecl = 0;
4398 if (isPartialSpecialization)
4399 // FIXME: Template parameter list matters, too
4400 PrevDecl
4401 = ClassTemplate->findPartialSpecialization(Converted.data(),
4402 Converted.size(),
4403 InsertPos);
4404 else
4405 PrevDecl
4406 = ClassTemplate->findSpecialization(Converted.data(),
4407 Converted.size(), InsertPos);
4409 ClassTemplateSpecializationDecl *Specialization = 0;
4411 // Check whether we can declare a class template specialization in
4412 // the current scope.
4413 if (TUK != TUK_Friend &&
4414 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
4415 TemplateNameLoc,
4416 isPartialSpecialization))
4417 return true;
4419 // The canonical type
4420 QualType CanonType;
4421 if (PrevDecl &&
4422 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
4423 TUK == TUK_Friend)) {
4424 // Since the only prior class template specialization with these
4425 // arguments was referenced but not declared, or we're only
4426 // referencing this specialization as a friend, reuse that
4427 // declaration node as our own, updating its source location to
4428 // reflect our new declaration.
4429 Specialization = PrevDecl;
4430 Specialization->setLocation(TemplateNameLoc);
4431 PrevDecl = 0;
4432 CanonType = Context.getTypeDeclType(Specialization);
4433 } else if (isPartialSpecialization) {
4434 // Build the canonical type that describes the converted template
4435 // arguments of the class template partial specialization.
4436 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4437 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
4438 Converted.data(),
4439 Converted.size());
4441 if (Context.hasSameType(CanonType,
4442 ClassTemplate->getInjectedClassNameSpecialization())) {
4443 // C++ [temp.class.spec]p9b3:
4445 // -- The argument list of the specialization shall not be identical
4446 // to the implicit argument list of the primary template.
4447 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4448 << (TUK == TUK_Definition)
4449 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4450 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
4451 ClassTemplate->getIdentifier(),
4452 TemplateNameLoc,
4453 Attr,
4454 TemplateParams,
4455 AS_none);
4458 // Create a new class template partial specialization declaration node.
4459 ClassTemplatePartialSpecializationDecl *PrevPartial
4460 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
4461 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
4462 : ClassTemplate->getNextPartialSpecSequenceNumber();
4463 ClassTemplatePartialSpecializationDecl *Partial
4464 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
4465 ClassTemplate->getDeclContext(),
4466 TemplateNameLoc,
4467 TemplateParams,
4468 ClassTemplate,
4469 Converted.data(),
4470 Converted.size(),
4471 TemplateArgs,
4472 CanonType,
4473 PrevPartial,
4474 SequenceNumber);
4475 SetNestedNameSpecifier(Partial, SS);
4476 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
4477 Partial->setTemplateParameterListsInfo(Context,
4478 NumMatchedTemplateParamLists,
4479 (TemplateParameterList**) TemplateParameterLists.release());
4482 if (!PrevPartial)
4483 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
4484 Specialization = Partial;
4486 // If we are providing an explicit specialization of a member class
4487 // template specialization, make a note of that.
4488 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4489 PrevPartial->setMemberSpecialization();
4491 // Check that all of the template parameters of the class template
4492 // partial specialization are deducible from the template
4493 // arguments. If not, this class template partial specialization
4494 // will never be used.
4495 llvm::SmallVector<bool, 8> DeducibleParams;
4496 DeducibleParams.resize(TemplateParams->size());
4497 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4498 TemplateParams->getDepth(),
4499 DeducibleParams);
4500 unsigned NumNonDeducible = 0;
4501 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
4502 if (!DeducibleParams[I])
4503 ++NumNonDeducible;
4505 if (NumNonDeducible) {
4506 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
4507 << (NumNonDeducible > 1)
4508 << SourceRange(TemplateNameLoc, RAngleLoc);
4509 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4510 if (!DeducibleParams[I]) {
4511 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
4512 if (Param->getDeclName())
4513 Diag(Param->getLocation(),
4514 diag::note_partial_spec_unused_parameter)
4515 << Param->getDeclName();
4516 else
4517 Diag(Param->getLocation(),
4518 diag::note_partial_spec_unused_parameter)
4519 << "<anonymous>";
4523 } else {
4524 // Create a new class template specialization declaration node for
4525 // this explicit specialization or friend declaration.
4526 Specialization
4527 = ClassTemplateSpecializationDecl::Create(Context, Kind,
4528 ClassTemplate->getDeclContext(),
4529 TemplateNameLoc,
4530 ClassTemplate,
4531 Converted.data(),
4532 Converted.size(),
4533 PrevDecl);
4534 SetNestedNameSpecifier(Specialization, SS);
4535 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) {
4536 Specialization->setTemplateParameterListsInfo(Context,
4537 NumMatchedTemplateParamLists,
4538 (TemplateParameterList**) TemplateParameterLists.release());
4541 if (!PrevDecl)
4542 ClassTemplate->AddSpecialization(Specialization, InsertPos);
4544 CanonType = Context.getTypeDeclType(Specialization);
4547 // C++ [temp.expl.spec]p6:
4548 // If a template, a member template or the member of a class template is
4549 // explicitly specialized then that specialization shall be declared
4550 // before the first use of that specialization that would cause an implicit
4551 // instantiation to take place, in every translation unit in which such a
4552 // use occurs; no diagnostic is required.
4553 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4554 bool Okay = false;
4555 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4556 // Is there any previous explicit specialization declaration?
4557 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
4558 Okay = true;
4559 break;
4563 if (!Okay) {
4564 SourceRange Range(TemplateNameLoc, RAngleLoc);
4565 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4566 << Context.getTypeDeclType(Specialization) << Range;
4568 Diag(PrevDecl->getPointOfInstantiation(),
4569 diag::note_instantiation_required_here)
4570 << (PrevDecl->getTemplateSpecializationKind()
4571 != TSK_ImplicitInstantiation);
4572 return true;
4576 // If this is not a friend, note that this is an explicit specialization.
4577 if (TUK != TUK_Friend)
4578 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4580 // Check that this isn't a redefinition of this specialization.
4581 if (TUK == TUK_Definition) {
4582 if (RecordDecl *Def = Specialization->getDefinition()) {
4583 SourceRange Range(TemplateNameLoc, RAngleLoc);
4584 Diag(TemplateNameLoc, diag::err_redefinition)
4585 << Context.getTypeDeclType(Specialization) << Range;
4586 Diag(Def->getLocation(), diag::note_previous_definition);
4587 Specialization->setInvalidDecl();
4588 return true;
4592 if (Attr)
4593 ProcessDeclAttributeList(S, Specialization, Attr);
4595 // Build the fully-sugared type for this class template
4596 // specialization as the user wrote in the specialization
4597 // itself. This means that we'll pretty-print the type retrieved
4598 // from the specialization's declaration the way that the user
4599 // actually wrote the specialization, rather than formatting the
4600 // name based on the "canonical" representation used to store the
4601 // template arguments in the specialization.
4602 TypeSourceInfo *WrittenTy
4603 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
4604 TemplateArgs, CanonType);
4605 if (TUK != TUK_Friend) {
4606 Specialization->setTypeAsWritten(WrittenTy);
4607 if (TemplateParams)
4608 Specialization->setTemplateKeywordLoc(TemplateParams->getTemplateLoc());
4610 TemplateArgsIn.release();
4612 // C++ [temp.expl.spec]p9:
4613 // A template explicit specialization is in the scope of the
4614 // namespace in which the template was defined.
4616 // We actually implement this paragraph where we set the semantic
4617 // context (in the creation of the ClassTemplateSpecializationDecl),
4618 // but we also maintain the lexical context where the actual
4619 // definition occurs.
4620 Specialization->setLexicalDeclContext(CurContext);
4622 // We may be starting the definition of this specialization.
4623 if (TUK == TUK_Definition)
4624 Specialization->startDefinition();
4626 if (TUK == TUK_Friend) {
4627 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
4628 TemplateNameLoc,
4629 WrittenTy,
4630 /*FIXME:*/KWLoc);
4631 Friend->setAccess(AS_public);
4632 CurContext->addDecl(Friend);
4633 } else {
4634 // Add the specialization into its lexical context, so that it can
4635 // be seen when iterating through the list of declarations in that
4636 // context. However, specializations are not found by name lookup.
4637 CurContext->addDecl(Specialization);
4639 return Specialization;
4642 Decl *Sema::ActOnTemplateDeclarator(Scope *S,
4643 MultiTemplateParamsArg TemplateParameterLists,
4644 Declarator &D) {
4645 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
4648 Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
4649 MultiTemplateParamsArg TemplateParameterLists,
4650 Declarator &D) {
4651 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
4652 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
4654 if (FTI.hasPrototype) {
4655 // FIXME: Diagnose arguments without names in C.
4658 Scope *ParentScope = FnBodyScope->getParent();
4660 Decl *DP = HandleDeclarator(ParentScope, D,
4661 move(TemplateParameterLists),
4662 /*IsFunctionDefinition=*/true);
4663 if (FunctionTemplateDecl *FunctionTemplate
4664 = dyn_cast_or_null<FunctionTemplateDecl>(DP))
4665 return ActOnStartOfFunctionDef(FnBodyScope,
4666 FunctionTemplate->getTemplatedDecl());
4667 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP))
4668 return ActOnStartOfFunctionDef(FnBodyScope, Function);
4669 return 0;
4672 /// \brief Strips various properties off an implicit instantiation
4673 /// that has just been explicitly specialized.
4674 static void StripImplicitInstantiation(NamedDecl *D) {
4675 D->dropAttrs();
4677 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4678 FD->setInlineSpecified(false);
4682 /// \brief Diagnose cases where we have an explicit template specialization
4683 /// before/after an explicit template instantiation, producing diagnostics
4684 /// for those cases where they are required and determining whether the
4685 /// new specialization/instantiation will have any effect.
4687 /// \param NewLoc the location of the new explicit specialization or
4688 /// instantiation.
4690 /// \param NewTSK the kind of the new explicit specialization or instantiation.
4692 /// \param PrevDecl the previous declaration of the entity.
4694 /// \param PrevTSK the kind of the old explicit specialization or instantiatin.
4696 /// \param PrevPointOfInstantiation if valid, indicates where the previus
4697 /// declaration was instantiated (either implicitly or explicitly).
4699 /// \param HasNoEffect will be set to true to indicate that the new
4700 /// specialization or instantiation has no effect and should be ignored.
4702 /// \returns true if there was an error that should prevent the introduction of
4703 /// the new declaration into the AST, false otherwise.
4704 bool
4705 Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
4706 TemplateSpecializationKind NewTSK,
4707 NamedDecl *PrevDecl,
4708 TemplateSpecializationKind PrevTSK,
4709 SourceLocation PrevPointOfInstantiation,
4710 bool &HasNoEffect) {
4711 HasNoEffect = false;
4713 switch (NewTSK) {
4714 case TSK_Undeclared:
4715 case TSK_ImplicitInstantiation:
4716 assert(false && "Don't check implicit instantiations here");
4717 return false;
4719 case TSK_ExplicitSpecialization:
4720 switch (PrevTSK) {
4721 case TSK_Undeclared:
4722 case TSK_ExplicitSpecialization:
4723 // Okay, we're just specializing something that is either already
4724 // explicitly specialized or has merely been mentioned without any
4725 // instantiation.
4726 return false;
4728 case TSK_ImplicitInstantiation:
4729 if (PrevPointOfInstantiation.isInvalid()) {
4730 // The declaration itself has not actually been instantiated, so it is
4731 // still okay to specialize it.
4732 StripImplicitInstantiation(PrevDecl);
4733 return false;
4735 // Fall through
4737 case TSK_ExplicitInstantiationDeclaration:
4738 case TSK_ExplicitInstantiationDefinition:
4739 assert((PrevTSK == TSK_ImplicitInstantiation ||
4740 PrevPointOfInstantiation.isValid()) &&
4741 "Explicit instantiation without point of instantiation?");
4743 // C++ [temp.expl.spec]p6:
4744 // If a template, a member template or the member of a class template
4745 // is explicitly specialized then that specialization shall be declared
4746 // before the first use of that specialization that would cause an
4747 // implicit instantiation to take place, in every translation unit in
4748 // which such a use occurs; no diagnostic is required.
4749 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4750 // Is there any previous explicit specialization declaration?
4751 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
4752 return false;
4755 Diag(NewLoc, diag::err_specialization_after_instantiation)
4756 << PrevDecl;
4757 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
4758 << (PrevTSK != TSK_ImplicitInstantiation);
4760 return true;
4762 break;
4764 case TSK_ExplicitInstantiationDeclaration:
4765 switch (PrevTSK) {
4766 case TSK_ExplicitInstantiationDeclaration:
4767 // This explicit instantiation declaration is redundant (that's okay).
4768 HasNoEffect = true;
4769 return false;
4771 case TSK_Undeclared:
4772 case TSK_ImplicitInstantiation:
4773 // We're explicitly instantiating something that may have already been
4774 // implicitly instantiated; that's fine.
4775 return false;
4777 case TSK_ExplicitSpecialization:
4778 // C++0x [temp.explicit]p4:
4779 // For a given set of template parameters, if an explicit instantiation
4780 // of a template appears after a declaration of an explicit
4781 // specialization for that template, the explicit instantiation has no
4782 // effect.
4783 HasNoEffect = true;
4784 return false;
4786 case TSK_ExplicitInstantiationDefinition:
4787 // C++0x [temp.explicit]p10:
4788 // If an entity is the subject of both an explicit instantiation
4789 // declaration and an explicit instantiation definition in the same
4790 // translation unit, the definition shall follow the declaration.
4791 Diag(NewLoc,
4792 diag::err_explicit_instantiation_declaration_after_definition);
4793 Diag(PrevPointOfInstantiation,
4794 diag::note_explicit_instantiation_definition_here);
4795 assert(PrevPointOfInstantiation.isValid() &&
4796 "Explicit instantiation without point of instantiation?");
4797 HasNoEffect = true;
4798 return false;
4800 break;
4802 case TSK_ExplicitInstantiationDefinition:
4803 switch (PrevTSK) {
4804 case TSK_Undeclared:
4805 case TSK_ImplicitInstantiation:
4806 // We're explicitly instantiating something that may have already been
4807 // implicitly instantiated; that's fine.
4808 return false;
4810 case TSK_ExplicitSpecialization:
4811 // C++ DR 259, C++0x [temp.explicit]p4:
4812 // For a given set of template parameters, if an explicit
4813 // instantiation of a template appears after a declaration of
4814 // an explicit specialization for that template, the explicit
4815 // instantiation has no effect.
4817 // In C++98/03 mode, we only give an extension warning here, because it
4818 // is not harmful to try to explicitly instantiate something that
4819 // has been explicitly specialized.
4820 if (!getLangOptions().CPlusPlus0x) {
4821 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
4822 << PrevDecl;
4823 Diag(PrevDecl->getLocation(),
4824 diag::note_previous_template_specialization);
4826 HasNoEffect = true;
4827 return false;
4829 case TSK_ExplicitInstantiationDeclaration:
4830 // We're explicity instantiating a definition for something for which we
4831 // were previously asked to suppress instantiations. That's fine.
4832 return false;
4834 case TSK_ExplicitInstantiationDefinition:
4835 // C++0x [temp.spec]p5:
4836 // For a given template and a given set of template-arguments,
4837 // - an explicit instantiation definition shall appear at most once
4838 // in a program,
4839 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
4840 << PrevDecl;
4841 Diag(PrevPointOfInstantiation,
4842 diag::note_previous_explicit_instantiation);
4843 HasNoEffect = true;
4844 return false;
4846 break;
4849 assert(false && "Missing specialization/instantiation case?");
4851 return false;
4854 /// \brief Perform semantic analysis for the given dependent function
4855 /// template specialization. The only possible way to get a dependent
4856 /// function template specialization is with a friend declaration,
4857 /// like so:
4859 /// template <class T> void foo(T);
4860 /// template <class T> class A {
4861 /// friend void foo<>(T);
4862 /// };
4864 /// There really isn't any useful analysis we can do here, so we
4865 /// just store the information.
4866 bool
4867 Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
4868 const TemplateArgumentListInfo &ExplicitTemplateArgs,
4869 LookupResult &Previous) {
4870 // Remove anything from Previous that isn't a function template in
4871 // the correct context.
4872 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
4873 LookupResult::Filter F = Previous.makeFilter();
4874 while (F.hasNext()) {
4875 NamedDecl *D = F.next()->getUnderlyingDecl();
4876 if (!isa<FunctionTemplateDecl>(D) ||
4877 !FDLookupContext->InEnclosingNamespaceSetOf(
4878 D->getDeclContext()->getRedeclContext()))
4879 F.erase();
4881 F.done();
4883 // Should this be diagnosed here?
4884 if (Previous.empty()) return true;
4886 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
4887 ExplicitTemplateArgs);
4888 return false;
4891 /// \brief Perform semantic analysis for the given function template
4892 /// specialization.
4894 /// This routine performs all of the semantic analysis required for an
4895 /// explicit function template specialization. On successful completion,
4896 /// the function declaration \p FD will become a function template
4897 /// specialization.
4899 /// \param FD the function declaration, which will be updated to become a
4900 /// function template specialization.
4902 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
4903 /// if any. Note that this may be valid info even when 0 arguments are
4904 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
4905 /// as it anyway contains info on the angle brackets locations.
4907 /// \param PrevDecl the set of declarations that may be specialized by
4908 /// this function specialization.
4909 bool
4910 Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
4911 const TemplateArgumentListInfo *ExplicitTemplateArgs,
4912 LookupResult &Previous) {
4913 // The set of function template specializations that could match this
4914 // explicit function template specialization.
4915 UnresolvedSet<8> Candidates;
4917 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
4918 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
4919 I != E; ++I) {
4920 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
4921 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
4922 // Only consider templates found within the same semantic lookup scope as
4923 // FD.
4924 if (!FDLookupContext->InEnclosingNamespaceSetOf(
4925 Ovl->getDeclContext()->getRedeclContext()))
4926 continue;
4928 // C++ [temp.expl.spec]p11:
4929 // A trailing template-argument can be left unspecified in the
4930 // template-id naming an explicit function template specialization
4931 // provided it can be deduced from the function argument type.
4932 // Perform template argument deduction to determine whether we may be
4933 // specializing this template.
4934 // FIXME: It is somewhat wasteful to build
4935 TemplateDeductionInfo Info(Context, FD->getLocation());
4936 FunctionDecl *Specialization = 0;
4937 if (TemplateDeductionResult TDK
4938 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
4939 FD->getType(),
4940 Specialization,
4941 Info)) {
4942 // FIXME: Template argument deduction failed; record why it failed, so
4943 // that we can provide nifty diagnostics.
4944 (void)TDK;
4945 continue;
4948 // Record this candidate.
4949 Candidates.addDecl(Specialization, I.getAccess());
4953 // Find the most specialized function template.
4954 UnresolvedSetIterator Result
4955 = getMostSpecialized(Candidates.begin(), Candidates.end(),
4956 TPOC_Other, 0, FD->getLocation(),
4957 PDiag(diag::err_function_template_spec_no_match)
4958 << FD->getDeclName(),
4959 PDiag(diag::err_function_template_spec_ambiguous)
4960 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
4961 PDiag(diag::note_function_template_spec_matched));
4962 if (Result == Candidates.end())
4963 return true;
4965 // Ignore access information; it doesn't figure into redeclaration checking.
4966 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
4967 Specialization->setLocation(FD->getLocation());
4969 // FIXME: Check if the prior specialization has a point of instantiation.
4970 // If so, we have run afoul of .
4972 // If this is a friend declaration, then we're not really declaring
4973 // an explicit specialization.
4974 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
4976 // Check the scope of this explicit specialization.
4977 if (!isFriend &&
4978 CheckTemplateSpecializationScope(*this,
4979 Specialization->getPrimaryTemplate(),
4980 Specialization, FD->getLocation(),
4981 false))
4982 return true;
4984 // C++ [temp.expl.spec]p6:
4985 // If a template, a member template or the member of a class template is
4986 // explicitly specialized then that specialization shall be declared
4987 // before the first use of that specialization that would cause an implicit
4988 // instantiation to take place, in every translation unit in which such a
4989 // use occurs; no diagnostic is required.
4990 FunctionTemplateSpecializationInfo *SpecInfo
4991 = Specialization->getTemplateSpecializationInfo();
4992 assert(SpecInfo && "Function template specialization info missing?");
4994 bool HasNoEffect = false;
4995 if (!isFriend &&
4996 CheckSpecializationInstantiationRedecl(FD->getLocation(),
4997 TSK_ExplicitSpecialization,
4998 Specialization,
4999 SpecInfo->getTemplateSpecializationKind(),
5000 SpecInfo->getPointOfInstantiation(),
5001 HasNoEffect))
5002 return true;
5004 // Mark the prior declaration as an explicit specialization, so that later
5005 // clients know that this is an explicit specialization.
5006 if (!isFriend) {
5007 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
5008 MarkUnusedFileScopedDecl(Specialization);
5011 // Turn the given function declaration into a function template
5012 // specialization, with the template arguments from the previous
5013 // specialization.
5014 // Take copies of (semantic and syntactic) template argument lists.
5015 const TemplateArgumentList* TemplArgs = new (Context)
5016 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
5017 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs
5018 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0;
5019 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
5020 TemplArgs, /*InsertPos=*/0,
5021 SpecInfo->getTemplateSpecializationKind(),
5022 TemplArgsAsWritten);
5024 // The "previous declaration" for this function template specialization is
5025 // the prior function template specialization.
5026 Previous.clear();
5027 Previous.addDecl(Specialization);
5028 return false;
5031 /// \brief Perform semantic analysis for the given non-template member
5032 /// specialization.
5034 /// This routine performs all of the semantic analysis required for an
5035 /// explicit member function specialization. On successful completion,
5036 /// the function declaration \p FD will become a member function
5037 /// specialization.
5039 /// \param Member the member declaration, which will be updated to become a
5040 /// specialization.
5042 /// \param Previous the set of declarations, one of which may be specialized
5043 /// by this function specialization; the set will be modified to contain the
5044 /// redeclared member.
5045 bool
5046 Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
5047 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
5049 // Try to find the member we are instantiating.
5050 NamedDecl *Instantiation = 0;
5051 NamedDecl *InstantiatedFrom = 0;
5052 MemberSpecializationInfo *MSInfo = 0;
5054 if (Previous.empty()) {
5055 // Nowhere to look anyway.
5056 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
5057 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5058 I != E; ++I) {
5059 NamedDecl *D = (*I)->getUnderlyingDecl();
5060 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
5061 if (Context.hasSameType(Function->getType(), Method->getType())) {
5062 Instantiation = Method;
5063 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
5064 MSInfo = Method->getMemberSpecializationInfo();
5065 break;
5069 } else if (isa<VarDecl>(Member)) {
5070 VarDecl *PrevVar;
5071 if (Previous.isSingleResult() &&
5072 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
5073 if (PrevVar->isStaticDataMember()) {
5074 Instantiation = PrevVar;
5075 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
5076 MSInfo = PrevVar->getMemberSpecializationInfo();
5078 } else if (isa<RecordDecl>(Member)) {
5079 CXXRecordDecl *PrevRecord;
5080 if (Previous.isSingleResult() &&
5081 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
5082 Instantiation = PrevRecord;
5083 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
5084 MSInfo = PrevRecord->getMemberSpecializationInfo();
5088 if (!Instantiation) {
5089 // There is no previous declaration that matches. Since member
5090 // specializations are always out-of-line, the caller will complain about
5091 // this mismatch later.
5092 return false;
5095 // If this is a friend, just bail out here before we start turning
5096 // things into explicit specializations.
5097 if (Member->getFriendObjectKind() != Decl::FOK_None) {
5098 // Preserve instantiation information.
5099 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
5100 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
5101 cast<CXXMethodDecl>(InstantiatedFrom),
5102 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
5103 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
5104 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
5105 cast<CXXRecordDecl>(InstantiatedFrom),
5106 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
5109 Previous.clear();
5110 Previous.addDecl(Instantiation);
5111 return false;
5114 // Make sure that this is a specialization of a member.
5115 if (!InstantiatedFrom) {
5116 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
5117 << Member;
5118 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
5119 return true;
5122 // C++ [temp.expl.spec]p6:
5123 // If a template, a member template or the member of a class template is
5124 // explicitly specialized then that spe- cialization shall be declared
5125 // before the first use of that specialization that would cause an implicit
5126 // instantiation to take place, in every translation unit in which such a
5127 // use occurs; no diagnostic is required.
5128 assert(MSInfo && "Member specialization info missing?");
5130 bool HasNoEffect = false;
5131 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
5132 TSK_ExplicitSpecialization,
5133 Instantiation,
5134 MSInfo->getTemplateSpecializationKind(),
5135 MSInfo->getPointOfInstantiation(),
5136 HasNoEffect))
5137 return true;
5139 // Check the scope of this explicit specialization.
5140 if (CheckTemplateSpecializationScope(*this,
5141 InstantiatedFrom,
5142 Instantiation, Member->getLocation(),
5143 false))
5144 return true;
5146 // Note that this is an explicit instantiation of a member.
5147 // the original declaration to note that it is an explicit specialization
5148 // (if it was previously an implicit instantiation). This latter step
5149 // makes bookkeeping easier.
5150 if (isa<FunctionDecl>(Member)) {
5151 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
5152 if (InstantiationFunction->getTemplateSpecializationKind() ==
5153 TSK_ImplicitInstantiation) {
5154 InstantiationFunction->setTemplateSpecializationKind(
5155 TSK_ExplicitSpecialization);
5156 InstantiationFunction->setLocation(Member->getLocation());
5159 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
5160 cast<CXXMethodDecl>(InstantiatedFrom),
5161 TSK_ExplicitSpecialization);
5162 MarkUnusedFileScopedDecl(InstantiationFunction);
5163 } else if (isa<VarDecl>(Member)) {
5164 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
5165 if (InstantiationVar->getTemplateSpecializationKind() ==
5166 TSK_ImplicitInstantiation) {
5167 InstantiationVar->setTemplateSpecializationKind(
5168 TSK_ExplicitSpecialization);
5169 InstantiationVar->setLocation(Member->getLocation());
5172 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
5173 cast<VarDecl>(InstantiatedFrom),
5174 TSK_ExplicitSpecialization);
5175 MarkUnusedFileScopedDecl(InstantiationVar);
5176 } else {
5177 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
5178 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
5179 if (InstantiationClass->getTemplateSpecializationKind() ==
5180 TSK_ImplicitInstantiation) {
5181 InstantiationClass->setTemplateSpecializationKind(
5182 TSK_ExplicitSpecialization);
5183 InstantiationClass->setLocation(Member->getLocation());
5186 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
5187 cast<CXXRecordDecl>(InstantiatedFrom),
5188 TSK_ExplicitSpecialization);
5191 // Save the caller the trouble of having to figure out which declaration
5192 // this specialization matches.
5193 Previous.clear();
5194 Previous.addDecl(Instantiation);
5195 return false;
5198 /// \brief Check the scope of an explicit instantiation.
5200 /// \returns true if a serious error occurs, false otherwise.
5201 static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
5202 SourceLocation InstLoc,
5203 bool WasQualifiedName) {
5204 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
5205 DeclContext *CurContext = S.CurContext->getRedeclContext();
5207 if (CurContext->isRecord()) {
5208 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
5209 << D;
5210 return true;
5213 // C++0x [temp.explicit]p2:
5214 // An explicit instantiation shall appear in an enclosing namespace of its
5215 // template.
5217 // This is DR275, which we do not retroactively apply to C++98/03.
5218 if (S.getLangOptions().CPlusPlus0x &&
5219 !CurContext->Encloses(OrigContext)) {
5220 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext))
5221 S.Diag(InstLoc,
5222 S.getLangOptions().CPlusPlus0x?
5223 diag::err_explicit_instantiation_out_of_scope
5224 : diag::warn_explicit_instantiation_out_of_scope_0x)
5225 << D << NS;
5226 else
5227 S.Diag(InstLoc,
5228 S.getLangOptions().CPlusPlus0x?
5229 diag::err_explicit_instantiation_must_be_global
5230 : diag::warn_explicit_instantiation_out_of_scope_0x)
5231 << D;
5232 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
5233 return false;
5236 // C++0x [temp.explicit]p2:
5237 // If the name declared in the explicit instantiation is an unqualified
5238 // name, the explicit instantiation shall appear in the namespace where
5239 // its template is declared or, if that namespace is inline (7.3.1), any
5240 // namespace from its enclosing namespace set.
5241 if (WasQualifiedName)
5242 return false;
5244 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
5245 return false;
5247 S.Diag(InstLoc,
5248 S.getLangOptions().CPlusPlus0x?
5249 diag::err_explicit_instantiation_unqualified_wrong_namespace
5250 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
5251 << D << OrigContext;
5252 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
5253 return false;
5256 /// \brief Determine whether the given scope specifier has a template-id in it.
5257 static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
5258 if (!SS.isSet())
5259 return false;
5261 // C++0x [temp.explicit]p2:
5262 // If the explicit instantiation is for a member function, a member class
5263 // or a static data member of a class template specialization, the name of
5264 // the class template specialization in the qualified-id for the member
5265 // name shall be a simple-template-id.
5267 // C++98 has the same restriction, just worded differently.
5268 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
5269 NNS; NNS = NNS->getPrefix())
5270 if (const Type *T = NNS->getAsType())
5271 if (isa<TemplateSpecializationType>(T))
5272 return true;
5274 return false;
5277 // Explicit instantiation of a class template specialization
5278 DeclResult
5279 Sema::ActOnExplicitInstantiation(Scope *S,
5280 SourceLocation ExternLoc,
5281 SourceLocation TemplateLoc,
5282 unsigned TagSpec,
5283 SourceLocation KWLoc,
5284 const CXXScopeSpec &SS,
5285 TemplateTy TemplateD,
5286 SourceLocation TemplateNameLoc,
5287 SourceLocation LAngleLoc,
5288 ASTTemplateArgsPtr TemplateArgsIn,
5289 SourceLocation RAngleLoc,
5290 AttributeList *Attr) {
5291 // Find the class template we're specializing
5292 TemplateName Name = TemplateD.getAsVal<TemplateName>();
5293 ClassTemplateDecl *ClassTemplate
5294 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
5296 // Check that the specialization uses the same tag kind as the
5297 // original template.
5298 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
5299 assert(Kind != TTK_Enum &&
5300 "Invalid enum tag in class template explicit instantiation!");
5301 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
5302 Kind, KWLoc,
5303 *ClassTemplate->getIdentifier())) {
5304 Diag(KWLoc, diag::err_use_with_wrong_tag)
5305 << ClassTemplate
5306 << FixItHint::CreateReplacement(KWLoc,
5307 ClassTemplate->getTemplatedDecl()->getKindName());
5308 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
5309 diag::note_previous_use);
5310 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
5313 // C++0x [temp.explicit]p2:
5314 // There are two forms of explicit instantiation: an explicit instantiation
5315 // definition and an explicit instantiation declaration. An explicit
5316 // instantiation declaration begins with the extern keyword. [...]
5317 TemplateSpecializationKind TSK
5318 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5319 : TSK_ExplicitInstantiationDeclaration;
5321 // Translate the parser's template argument list in our AST format.
5322 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
5323 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
5325 // Check that the template argument list is well-formed for this
5326 // template.
5327 llvm::SmallVector<TemplateArgument, 4> Converted;
5328 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
5329 TemplateArgs, false, Converted))
5330 return true;
5332 assert((Converted.size() == ClassTemplate->getTemplateParameters()->size()) &&
5333 "Converted template argument list is too short!");
5335 // Find the class template specialization declaration that
5336 // corresponds to these arguments.
5337 void *InsertPos = 0;
5338 ClassTemplateSpecializationDecl *PrevDecl
5339 = ClassTemplate->findSpecialization(Converted.data(),
5340 Converted.size(), InsertPos);
5342 TemplateSpecializationKind PrevDecl_TSK
5343 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
5345 // C++0x [temp.explicit]p2:
5346 // [...] An explicit instantiation shall appear in an enclosing
5347 // namespace of its template. [...]
5349 // This is C++ DR 275.
5350 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
5351 SS.isSet()))
5352 return true;
5354 ClassTemplateSpecializationDecl *Specialization = 0;
5356 bool HasNoEffect = false;
5357 if (PrevDecl) {
5358 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
5359 PrevDecl, PrevDecl_TSK,
5360 PrevDecl->getPointOfInstantiation(),
5361 HasNoEffect))
5362 return PrevDecl;
5364 // Even though HasNoEffect == true means that this explicit instantiation
5365 // has no effect on semantics, we go on to put its syntax in the AST.
5367 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
5368 PrevDecl_TSK == TSK_Undeclared) {
5369 // Since the only prior class template specialization with these
5370 // arguments was referenced but not declared, reuse that
5371 // declaration node as our own, updating the source location
5372 // for the template name to reflect our new declaration.
5373 // (Other source locations will be updated later.)
5374 Specialization = PrevDecl;
5375 Specialization->setLocation(TemplateNameLoc);
5376 PrevDecl = 0;
5380 if (!Specialization) {
5381 // Create a new class template specialization declaration node for
5382 // this explicit specialization.
5383 Specialization
5384 = ClassTemplateSpecializationDecl::Create(Context, Kind,
5385 ClassTemplate->getDeclContext(),
5386 TemplateNameLoc,
5387 ClassTemplate,
5388 Converted.data(),
5389 Converted.size(),
5390 PrevDecl);
5391 SetNestedNameSpecifier(Specialization, SS);
5393 if (!HasNoEffect && !PrevDecl) {
5394 // Insert the new specialization.
5395 ClassTemplate->AddSpecialization(Specialization, InsertPos);
5399 // Build the fully-sugared type for this explicit instantiation as
5400 // the user wrote in the explicit instantiation itself. This means
5401 // that we'll pretty-print the type retrieved from the
5402 // specialization's declaration the way that the user actually wrote
5403 // the explicit instantiation, rather than formatting the name based
5404 // on the "canonical" representation used to store the template
5405 // arguments in the specialization.
5406 TypeSourceInfo *WrittenTy
5407 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
5408 TemplateArgs,
5409 Context.getTypeDeclType(Specialization));
5410 Specialization->setTypeAsWritten(WrittenTy);
5411 TemplateArgsIn.release();
5413 // Set source locations for keywords.
5414 Specialization->setExternLoc(ExternLoc);
5415 Specialization->setTemplateKeywordLoc(TemplateLoc);
5417 // Add the explicit instantiation into its lexical context. However,
5418 // since explicit instantiations are never found by name lookup, we
5419 // just put it into the declaration context directly.
5420 Specialization->setLexicalDeclContext(CurContext);
5421 CurContext->addDecl(Specialization);
5423 // Syntax is now OK, so return if it has no other effect on semantics.
5424 if (HasNoEffect) {
5425 // Set the template specialization kind.
5426 Specialization->setTemplateSpecializationKind(TSK);
5427 return Specialization;
5430 // C++ [temp.explicit]p3:
5431 // A definition of a class template or class member template
5432 // shall be in scope at the point of the explicit instantiation of
5433 // the class template or class member template.
5435 // This check comes when we actually try to perform the
5436 // instantiation.
5437 ClassTemplateSpecializationDecl *Def
5438 = cast_or_null<ClassTemplateSpecializationDecl>(
5439 Specialization->getDefinition());
5440 if (!Def)
5441 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
5442 else if (TSK == TSK_ExplicitInstantiationDefinition) {
5443 MarkVTableUsed(TemplateNameLoc, Specialization, true);
5444 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
5447 // Instantiate the members of this class template specialization.
5448 Def = cast_or_null<ClassTemplateSpecializationDecl>(
5449 Specialization->getDefinition());
5450 if (Def) {
5451 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
5453 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
5454 // TSK_ExplicitInstantiationDefinition
5455 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
5456 TSK == TSK_ExplicitInstantiationDefinition)
5457 Def->setTemplateSpecializationKind(TSK);
5459 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
5462 // Set the template specialization kind.
5463 Specialization->setTemplateSpecializationKind(TSK);
5464 return Specialization;
5467 // Explicit instantiation of a member class of a class template.
5468 DeclResult
5469 Sema::ActOnExplicitInstantiation(Scope *S,
5470 SourceLocation ExternLoc,
5471 SourceLocation TemplateLoc,
5472 unsigned TagSpec,
5473 SourceLocation KWLoc,
5474 CXXScopeSpec &SS,
5475 IdentifierInfo *Name,
5476 SourceLocation NameLoc,
5477 AttributeList *Attr) {
5479 bool Owned = false;
5480 bool IsDependent = false;
5481 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
5482 KWLoc, SS, Name, NameLoc, Attr, AS_none,
5483 MultiTemplateParamsArg(*this, 0, 0),
5484 Owned, IsDependent, false, false,
5485 TypeResult());
5486 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
5488 if (!TagD)
5489 return true;
5491 TagDecl *Tag = cast<TagDecl>(TagD);
5492 if (Tag->isEnum()) {
5493 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
5494 << Context.getTypeDeclType(Tag);
5495 return true;
5498 if (Tag->isInvalidDecl())
5499 return true;
5501 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
5502 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
5503 if (!Pattern) {
5504 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
5505 << Context.getTypeDeclType(Record);
5506 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
5507 return true;
5510 // C++0x [temp.explicit]p2:
5511 // If the explicit instantiation is for a class or member class, the
5512 // elaborated-type-specifier in the declaration shall include a
5513 // simple-template-id.
5515 // C++98 has the same restriction, just worded differently.
5516 if (!ScopeSpecifierHasTemplateId(SS))
5517 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
5518 << Record << SS.getRange();
5520 // C++0x [temp.explicit]p2:
5521 // There are two forms of explicit instantiation: an explicit instantiation
5522 // definition and an explicit instantiation declaration. An explicit
5523 // instantiation declaration begins with the extern keyword. [...]
5524 TemplateSpecializationKind TSK
5525 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5526 : TSK_ExplicitInstantiationDeclaration;
5528 // C++0x [temp.explicit]p2:
5529 // [...] An explicit instantiation shall appear in an enclosing
5530 // namespace of its template. [...]
5532 // This is C++ DR 275.
5533 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
5535 // Verify that it is okay to explicitly instantiate here.
5536 CXXRecordDecl *PrevDecl
5537 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
5538 if (!PrevDecl && Record->getDefinition())
5539 PrevDecl = Record;
5540 if (PrevDecl) {
5541 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
5542 bool HasNoEffect = false;
5543 assert(MSInfo && "No member specialization information?");
5544 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
5545 PrevDecl,
5546 MSInfo->getTemplateSpecializationKind(),
5547 MSInfo->getPointOfInstantiation(),
5548 HasNoEffect))
5549 return true;
5550 if (HasNoEffect)
5551 return TagD;
5554 CXXRecordDecl *RecordDef
5555 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
5556 if (!RecordDef) {
5557 // C++ [temp.explicit]p3:
5558 // A definition of a member class of a class template shall be in scope
5559 // at the point of an explicit instantiation of the member class.
5560 CXXRecordDecl *Def
5561 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
5562 if (!Def) {
5563 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
5564 << 0 << Record->getDeclName() << Record->getDeclContext();
5565 Diag(Pattern->getLocation(), diag::note_forward_declaration)
5566 << Pattern;
5567 return true;
5568 } else {
5569 if (InstantiateClass(NameLoc, Record, Def,
5570 getTemplateInstantiationArgs(Record),
5571 TSK))
5572 return true;
5574 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
5575 if (!RecordDef)
5576 return true;
5580 // Instantiate all of the members of the class.
5581 InstantiateClassMembers(NameLoc, RecordDef,
5582 getTemplateInstantiationArgs(Record), TSK);
5584 if (TSK == TSK_ExplicitInstantiationDefinition)
5585 MarkVTableUsed(NameLoc, RecordDef, true);
5587 // FIXME: We don't have any representation for explicit instantiations of
5588 // member classes. Such a representation is not needed for compilation, but it
5589 // should be available for clients that want to see all of the declarations in
5590 // the source code.
5591 return TagD;
5594 DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
5595 SourceLocation ExternLoc,
5596 SourceLocation TemplateLoc,
5597 Declarator &D) {
5598 // Explicit instantiations always require a name.
5599 // TODO: check if/when DNInfo should replace Name.
5600 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5601 DeclarationName Name = NameInfo.getName();
5602 if (!Name) {
5603 if (!D.isInvalidType())
5604 Diag(D.getDeclSpec().getSourceRange().getBegin(),
5605 diag::err_explicit_instantiation_requires_name)
5606 << D.getDeclSpec().getSourceRange()
5607 << D.getSourceRange();
5609 return true;
5612 // The scope passed in may not be a decl scope. Zip up the scope tree until
5613 // we find one that is.
5614 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5615 (S->getFlags() & Scope::TemplateParamScope) != 0)
5616 S = S->getParent();
5618 // Determine the type of the declaration.
5619 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
5620 QualType R = T->getType();
5621 if (R.isNull())
5622 return true;
5624 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5625 // Cannot explicitly instantiate a typedef.
5626 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
5627 << Name;
5628 return true;
5631 // C++0x [temp.explicit]p1:
5632 // [...] An explicit instantiation of a function template shall not use the
5633 // inline or constexpr specifiers.
5634 // Presumably, this also applies to member functions of class templates as
5635 // well.
5636 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
5637 Diag(D.getDeclSpec().getInlineSpecLoc(),
5638 diag::err_explicit_instantiation_inline)
5639 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
5641 // FIXME: check for constexpr specifier.
5643 // C++0x [temp.explicit]p2:
5644 // There are two forms of explicit instantiation: an explicit instantiation
5645 // definition and an explicit instantiation declaration. An explicit
5646 // instantiation declaration begins with the extern keyword. [...]
5647 TemplateSpecializationKind TSK
5648 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5649 : TSK_ExplicitInstantiationDeclaration;
5651 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
5652 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
5654 if (!R->isFunctionType()) {
5655 // C++ [temp.explicit]p1:
5656 // A [...] static data member of a class template can be explicitly
5657 // instantiated from the member definition associated with its class
5658 // template.
5659 if (Previous.isAmbiguous())
5660 return true;
5662 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
5663 if (!Prev || !Prev->isStaticDataMember()) {
5664 // We expect to see a data data member here.
5665 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
5666 << Name;
5667 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5668 P != PEnd; ++P)
5669 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
5670 return true;
5673 if (!Prev->getInstantiatedFromStaticDataMember()) {
5674 // FIXME: Check for explicit specialization?
5675 Diag(D.getIdentifierLoc(),
5676 diag::err_explicit_instantiation_data_member_not_instantiated)
5677 << Prev;
5678 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
5679 // FIXME: Can we provide a note showing where this was declared?
5680 return true;
5683 // C++0x [temp.explicit]p2:
5684 // If the explicit instantiation is for a member function, a member class
5685 // or a static data member of a class template specialization, the name of
5686 // the class template specialization in the qualified-id for the member
5687 // name shall be a simple-template-id.
5689 // C++98 has the same restriction, just worded differently.
5690 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5691 Diag(D.getIdentifierLoc(),
5692 diag::ext_explicit_instantiation_without_qualified_id)
5693 << Prev << D.getCXXScopeSpec().getRange();
5695 // Check the scope of this explicit instantiation.
5696 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
5698 // Verify that it is okay to explicitly instantiate here.
5699 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
5700 assert(MSInfo && "Missing static data member specialization info?");
5701 bool HasNoEffect = false;
5702 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
5703 MSInfo->getTemplateSpecializationKind(),
5704 MSInfo->getPointOfInstantiation(),
5705 HasNoEffect))
5706 return true;
5707 if (HasNoEffect)
5708 return (Decl*) 0;
5710 // Instantiate static data member.
5711 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
5712 if (TSK == TSK_ExplicitInstantiationDefinition)
5713 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev);
5715 // FIXME: Create an ExplicitInstantiation node?
5716 return (Decl*) 0;
5719 // If the declarator is a template-id, translate the parser's template
5720 // argument list into our AST format.
5721 bool HasExplicitTemplateArgs = false;
5722 TemplateArgumentListInfo TemplateArgs;
5723 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5724 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5725 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
5726 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
5727 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5728 TemplateId->getTemplateArgs(),
5729 TemplateId->NumArgs);
5730 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
5731 HasExplicitTemplateArgs = true;
5732 TemplateArgsPtr.release();
5735 // C++ [temp.explicit]p1:
5736 // A [...] function [...] can be explicitly instantiated from its template.
5737 // A member function [...] of a class template can be explicitly
5738 // instantiated from the member definition associated with its class
5739 // template.
5740 UnresolvedSet<8> Matches;
5741 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
5742 P != PEnd; ++P) {
5743 NamedDecl *Prev = *P;
5744 if (!HasExplicitTemplateArgs) {
5745 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
5746 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
5747 Matches.clear();
5749 Matches.addDecl(Method, P.getAccess());
5750 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
5751 break;
5756 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
5757 if (!FunTmpl)
5758 continue;
5760 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
5761 FunctionDecl *Specialization = 0;
5762 if (TemplateDeductionResult TDK
5763 = DeduceTemplateArguments(FunTmpl,
5764 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
5765 R, Specialization, Info)) {
5766 // FIXME: Keep track of almost-matches?
5767 (void)TDK;
5768 continue;
5771 Matches.addDecl(Specialization, P.getAccess());
5774 // Find the most specialized function template specialization.
5775 UnresolvedSetIterator Result
5776 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other, 0,
5777 D.getIdentifierLoc(),
5778 PDiag(diag::err_explicit_instantiation_not_known) << Name,
5779 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
5780 PDiag(diag::note_explicit_instantiation_candidate));
5782 if (Result == Matches.end())
5783 return true;
5785 // Ignore access control bits, we don't need them for redeclaration checking.
5786 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
5788 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
5789 Diag(D.getIdentifierLoc(),
5790 diag::err_explicit_instantiation_member_function_not_instantiated)
5791 << Specialization
5792 << (Specialization->getTemplateSpecializationKind() ==
5793 TSK_ExplicitSpecialization);
5794 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
5795 return true;
5798 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
5799 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
5800 PrevDecl = Specialization;
5802 if (PrevDecl) {
5803 bool HasNoEffect = false;
5804 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
5805 PrevDecl,
5806 PrevDecl->getTemplateSpecializationKind(),
5807 PrevDecl->getPointOfInstantiation(),
5808 HasNoEffect))
5809 return true;
5811 // FIXME: We may still want to build some representation of this
5812 // explicit specialization.
5813 if (HasNoEffect)
5814 return (Decl*) 0;
5817 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
5819 if (TSK == TSK_ExplicitInstantiationDefinition)
5820 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
5822 // C++0x [temp.explicit]p2:
5823 // If the explicit instantiation is for a member function, a member class
5824 // or a static data member of a class template specialization, the name of
5825 // the class template specialization in the qualified-id for the member
5826 // name shall be a simple-template-id.
5828 // C++98 has the same restriction, just worded differently.
5829 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
5830 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
5831 D.getCXXScopeSpec().isSet() &&
5832 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
5833 Diag(D.getIdentifierLoc(),
5834 diag::ext_explicit_instantiation_without_qualified_id)
5835 << Specialization << D.getCXXScopeSpec().getRange();
5837 CheckExplicitInstantiationScope(*this,
5838 FunTmpl? (NamedDecl *)FunTmpl
5839 : Specialization->getInstantiatedFromMemberFunction(),
5840 D.getIdentifierLoc(),
5841 D.getCXXScopeSpec().isSet());
5843 // FIXME: Create some kind of ExplicitInstantiationDecl here.
5844 return (Decl*) 0;
5847 TypeResult
5848 Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
5849 const CXXScopeSpec &SS, IdentifierInfo *Name,
5850 SourceLocation TagLoc, SourceLocation NameLoc) {
5851 // This has to hold, because SS is expected to be defined.
5852 assert(Name && "Expected a name in a dependent tag");
5854 NestedNameSpecifier *NNS
5855 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5856 if (!NNS)
5857 return true;
5859 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
5861 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
5862 Diag(NameLoc, diag::err_dependent_tag_decl)
5863 << (TUK == TUK_Definition) << Kind << SS.getRange();
5864 return true;
5867 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
5868 return ParsedType::make(Context.getDependentNameType(Kwd, NNS, Name));
5871 TypeResult
5872 Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5873 const CXXScopeSpec &SS, const IdentifierInfo &II,
5874 SourceLocation IdLoc) {
5875 NestedNameSpecifier *NNS
5876 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5877 if (!NNS)
5878 return true;
5880 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5881 !getLangOptions().CPlusPlus0x)
5882 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5883 << FixItHint::CreateRemoval(TypenameLoc);
5885 QualType T = CheckTypenameType(ETK_Typename, NNS, II,
5886 TypenameLoc, SS.getRange(), IdLoc);
5887 if (T.isNull())
5888 return true;
5890 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5891 if (isa<DependentNameType>(T)) {
5892 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
5893 TL.setKeywordLoc(TypenameLoc);
5894 TL.setQualifierRange(SS.getRange());
5895 TL.setNameLoc(IdLoc);
5896 } else {
5897 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
5898 TL.setKeywordLoc(TypenameLoc);
5899 TL.setQualifierRange(SS.getRange());
5900 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
5903 return CreateParsedType(T, TSI);
5906 TypeResult
5907 Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
5908 const CXXScopeSpec &SS, SourceLocation TemplateLoc,
5909 ParsedType Ty) {
5910 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
5911 !getLangOptions().CPlusPlus0x)
5912 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
5913 << FixItHint::CreateRemoval(TypenameLoc);
5915 TypeSourceInfo *InnerTSI = 0;
5916 QualType T = GetTypeFromParser(Ty, &InnerTSI);
5918 assert(isa<TemplateSpecializationType>(T) &&
5919 "Expected a template specialization type");
5921 if (computeDeclContext(SS, false)) {
5922 // If we can compute a declaration context, then the "typename"
5923 // keyword was superfluous. Just build an ElaboratedType to keep
5924 // track of the nested-name-specifier.
5926 // Push the inner type, preserving its source locations if possible.
5927 TypeLocBuilder Builder;
5928 if (InnerTSI)
5929 Builder.pushFullCopy(InnerTSI->getTypeLoc());
5930 else
5931 Builder.push<TemplateSpecializationTypeLoc>(T).initialize(Context,
5932 TemplateLoc);
5934 /* Note: NNS already embedded in template specialization type T. */
5935 T = Context.getElaboratedType(ETK_Typename, /*NNS=*/0, T);
5936 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
5937 TL.setKeywordLoc(TypenameLoc);
5938 TL.setQualifierRange(SS.getRange());
5940 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
5941 return CreateParsedType(T, TSI);
5944 // TODO: it's really silly that we make a template specialization
5945 // type earlier only to drop it again here.
5946 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
5947 DependentTemplateName *DTN =
5948 TST->getTemplateName().getAsDependentTemplateName();
5949 assert(DTN && "dependent template has non-dependent name?");
5950 assert(DTN->getQualifier()
5951 == static_cast<NestedNameSpecifier*>(SS.getScopeRep()));
5952 T = Context.getDependentTemplateSpecializationType(ETK_Typename,
5953 DTN->getQualifier(),
5954 DTN->getIdentifier(),
5955 TST->getNumArgs(),
5956 TST->getArgs());
5957 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
5958 DependentTemplateSpecializationTypeLoc TL =
5959 cast<DependentTemplateSpecializationTypeLoc>(TSI->getTypeLoc());
5960 if (InnerTSI) {
5961 TemplateSpecializationTypeLoc TSTL =
5962 cast<TemplateSpecializationTypeLoc>(InnerTSI->getTypeLoc());
5963 TL.setLAngleLoc(TSTL.getLAngleLoc());
5964 TL.setRAngleLoc(TSTL.getRAngleLoc());
5965 for (unsigned I = 0, E = TST->getNumArgs(); I != E; ++I)
5966 TL.setArgLocInfo(I, TSTL.getArgLocInfo(I));
5967 } else {
5968 // FIXME: Poor source-location information here.
5969 TL.initializeLocal(Context, TemplateLoc);
5971 TL.setKeywordLoc(TypenameLoc);
5972 TL.setQualifierRange(SS.getRange());
5973 return CreateParsedType(T, TSI);
5976 /// \brief Build the type that describes a C++ typename specifier,
5977 /// e.g., "typename T::type".
5978 QualType
5979 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
5980 NestedNameSpecifier *NNS, const IdentifierInfo &II,
5981 SourceLocation KeywordLoc, SourceRange NNSRange,
5982 SourceLocation IILoc) {
5983 CXXScopeSpec SS;
5984 SS.setScopeRep(NNS);
5985 SS.setRange(NNSRange);
5987 DeclContext *Ctx = computeDeclContext(SS);
5988 if (!Ctx) {
5989 // If the nested-name-specifier is dependent and couldn't be
5990 // resolved to a type, build a typename type.
5991 assert(NNS->isDependent());
5992 return Context.getDependentNameType(Keyword, NNS, &II);
5995 // If the nested-name-specifier refers to the current instantiation,
5996 // the "typename" keyword itself is superfluous. In C++03, the
5997 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
5998 // allows such extraneous "typename" keywords, and we retroactively
5999 // apply this DR to C++03 code with only a warning. In any case we continue.
6001 if (RequireCompleteDeclContext(SS, Ctx))
6002 return QualType();
6004 DeclarationName Name(&II);
6005 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
6006 LookupQualifiedName(Result, Ctx);
6007 unsigned DiagID = 0;
6008 Decl *Referenced = 0;
6009 switch (Result.getResultKind()) {
6010 case LookupResult::NotFound:
6011 DiagID = diag::err_typename_nested_not_found;
6012 break;
6014 case LookupResult::FoundUnresolvedValue: {
6015 // We found a using declaration that is a value. Most likely, the using
6016 // declaration itself is meant to have the 'typename' keyword.
6017 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
6018 IILoc);
6019 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
6020 << Name << Ctx << FullRange;
6021 if (UnresolvedUsingValueDecl *Using
6022 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
6023 SourceLocation Loc = Using->getTargetNestedNameRange().getBegin();
6024 Diag(Loc, diag::note_using_value_decl_missing_typename)
6025 << FixItHint::CreateInsertion(Loc, "typename ");
6028 // Fall through to create a dependent typename type, from which we can recover
6029 // better.
6031 case LookupResult::NotFoundInCurrentInstantiation:
6032 // Okay, it's a member of an unknown instantiation.
6033 return Context.getDependentNameType(Keyword, NNS, &II);
6035 case LookupResult::Found:
6036 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
6037 // We found a type. Build an ElaboratedType, since the
6038 // typename-specifier was just sugar.
6039 return Context.getElaboratedType(ETK_Typename, NNS,
6040 Context.getTypeDeclType(Type));
6043 DiagID = diag::err_typename_nested_not_type;
6044 Referenced = Result.getFoundDecl();
6045 break;
6048 llvm_unreachable("unresolved using decl in non-dependent context");
6049 return QualType();
6051 case LookupResult::FoundOverloaded:
6052 DiagID = diag::err_typename_nested_not_type;
6053 Referenced = *Result.begin();
6054 break;
6056 case LookupResult::Ambiguous:
6057 return QualType();
6060 // If we get here, it's because name lookup did not find a
6061 // type. Emit an appropriate diagnostic and return an error.
6062 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(),
6063 IILoc);
6064 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
6065 if (Referenced)
6066 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
6067 << Name;
6068 return QualType();
6071 namespace {
6072 // See Sema::RebuildTypeInCurrentInstantiation
6073 class CurrentInstantiationRebuilder
6074 : public TreeTransform<CurrentInstantiationRebuilder> {
6075 SourceLocation Loc;
6076 DeclarationName Entity;
6078 public:
6079 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
6081 CurrentInstantiationRebuilder(Sema &SemaRef,
6082 SourceLocation Loc,
6083 DeclarationName Entity)
6084 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
6085 Loc(Loc), Entity(Entity) { }
6087 /// \brief Determine whether the given type \p T has already been
6088 /// transformed.
6090 /// For the purposes of type reconstruction, a type has already been
6091 /// transformed if it is NULL or if it is not dependent.
6092 bool AlreadyTransformed(QualType T) {
6093 return T.isNull() || !T->isDependentType();
6096 /// \brief Returns the location of the entity whose type is being
6097 /// rebuilt.
6098 SourceLocation getBaseLocation() { return Loc; }
6100 /// \brief Returns the name of the entity whose type is being rebuilt.
6101 DeclarationName getBaseEntity() { return Entity; }
6103 /// \brief Sets the "base" location and entity when that
6104 /// information is known based on another transformation.
6105 void setBase(SourceLocation Loc, DeclarationName Entity) {
6106 this->Loc = Loc;
6107 this->Entity = Entity;
6112 /// \brief Rebuilds a type within the context of the current instantiation.
6114 /// The type \p T is part of the type of an out-of-line member definition of
6115 /// a class template (or class template partial specialization) that was parsed
6116 /// and constructed before we entered the scope of the class template (or
6117 /// partial specialization thereof). This routine will rebuild that type now
6118 /// that we have entered the declarator's scope, which may produce different
6119 /// canonical types, e.g.,
6121 /// \code
6122 /// template<typename T>
6123 /// struct X {
6124 /// typedef T* pointer;
6125 /// pointer data();
6126 /// };
6128 /// template<typename T>
6129 /// typename X<T>::pointer X<T>::data() { ... }
6130 /// \endcode
6132 /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
6133 /// since we do not know that we can look into X<T> when we parsed the type.
6134 /// This function will rebuild the type, performing the lookup of "pointer"
6135 /// in X<T> and returning an ElaboratedType whose canonical type is the same
6136 /// as the canonical type of T*, allowing the return types of the out-of-line
6137 /// definition and the declaration to match.
6138 TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
6139 SourceLocation Loc,
6140 DeclarationName Name) {
6141 if (!T || !T->getType()->isDependentType())
6142 return T;
6144 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
6145 return Rebuilder.TransformType(T);
6148 ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
6149 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
6150 DeclarationName());
6151 return Rebuilder.TransformExpr(E);
6154 bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
6155 if (SS.isInvalid()) return true;
6157 NestedNameSpecifier *NNS = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
6158 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
6159 DeclarationName());
6160 NestedNameSpecifier *Rebuilt =
6161 Rebuilder.TransformNestedNameSpecifier(NNS, SS.getRange());
6162 if (!Rebuilt) return true;
6164 SS.setScopeRep(Rebuilt);
6165 return false;
6168 /// \brief Produces a formatted string that describes the binding of
6169 /// template parameters to template arguments.
6170 std::string
6171 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6172 const TemplateArgumentList &Args) {
6173 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
6176 std::string
6177 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6178 const TemplateArgument *Args,
6179 unsigned NumArgs) {
6180 llvm::SmallString<128> Str;
6181 llvm::raw_svector_ostream Out(Str);
6183 if (!Params || Params->size() == 0 || NumArgs == 0)
6184 return std::string();
6186 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
6187 if (I >= NumArgs)
6188 break;
6190 if (I == 0)
6191 Out << "[with ";
6192 else
6193 Out << ", ";
6195 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
6196 Out << Id->getName();
6197 } else {
6198 Out << '$' << I;
6201 Out << " = ";
6202 Args[I].print(Context.PrintingPolicy, Out);
6205 Out << ']';
6206 return Out.str();