SemaTemplate.cpp revision 51ffb0c9d43b2d3fd210e51ecdd67ba5d1790d70
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//===----------------------------------------------------------------------===/ 11 12#include "Sema.h" 13#include "Lookup.h" 14#include "TreeTransform.h" 15#include "clang/AST/ASTContext.h" 16#include "clang/AST/Expr.h" 17#include "clang/AST/ExprCXX.h" 18#include "clang/AST/DeclTemplate.h" 19#include "clang/Parse/DeclSpec.h" 20#include "clang/Parse/Template.h" 21#include "clang/Basic/LangOptions.h" 22#include "clang/Basic/PartialDiagnostic.h" 23#include "llvm/Support/Compiler.h" 24#include "llvm/ADT/StringExtras.h" 25using namespace clang; 26 27/// \brief Determine whether the declaration found is acceptable as the name 28/// of a template and, if so, return that template declaration. Otherwise, 29/// returns NULL. 30static NamedDecl *isAcceptableTemplateName(ASTContext &Context, NamedDecl *D) { 31 if (!D) 32 return 0; 33 34 if (isa<TemplateDecl>(D)) 35 return D; 36 37 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) { 38 // C++ [temp.local]p1: 39 // Like normal (non-template) classes, class templates have an 40 // injected-class-name (Clause 9). The injected-class-name 41 // can be used with or without a template-argument-list. When 42 // it is used without a template-argument-list, it is 43 // equivalent to the injected-class-name followed by the 44 // template-parameters of the class template enclosed in 45 // <>. When it is used with a template-argument-list, it 46 // refers to the specified class template specialization, 47 // which could be the current specialization or another 48 // specialization. 49 if (Record->isInjectedClassName()) { 50 Record = cast<CXXRecordDecl>(Record->getDeclContext()); 51 if (Record->getDescribedClassTemplate()) 52 return Record->getDescribedClassTemplate(); 53 54 if (ClassTemplateSpecializationDecl *Spec 55 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) 56 return Spec->getSpecializedTemplate(); 57 } 58 59 return 0; 60 } 61 62 OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D); 63 if (!Ovl) 64 return 0; 65 66 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(), 67 FEnd = Ovl->function_end(); 68 F != FEnd; ++F) { 69 if (FunctionTemplateDecl *FuncTmpl = dyn_cast<FunctionTemplateDecl>(*F)) { 70 // We've found a function template. Determine whether there are 71 // any other function templates we need to bundle together in an 72 // OverloadedFunctionDecl 73 for (++F; F != FEnd; ++F) { 74 if (isa<FunctionTemplateDecl>(*F)) 75 break; 76 } 77 78 if (F != FEnd) { 79 // Build an overloaded function decl containing only the 80 // function templates in Ovl. 81 OverloadedFunctionDecl *OvlTemplate 82 = OverloadedFunctionDecl::Create(Context, 83 Ovl->getDeclContext(), 84 Ovl->getDeclName()); 85 OvlTemplate->addOverload(FuncTmpl); 86 OvlTemplate->addOverload(*F); 87 for (++F; F != FEnd; ++F) { 88 if (isa<FunctionTemplateDecl>(*F)) 89 OvlTemplate->addOverload(*F); 90 } 91 92 return OvlTemplate; 93 } 94 95 return FuncTmpl; 96 } 97 } 98 99 return 0; 100} 101 102static void FilterAcceptableTemplateNames(ASTContext &C, LookupResult &R) { 103 LookupResult::Filter filter = R.makeFilter(); 104 while (filter.hasNext()) { 105 NamedDecl *Orig = filter.next(); 106 NamedDecl *Repl = isAcceptableTemplateName(C, Orig->getUnderlyingDecl()); 107 if (!Repl) 108 filter.erase(); 109 else if (Repl != Orig) 110 filter.replace(Repl); 111 } 112 filter.done(); 113} 114 115TemplateNameKind Sema::isTemplateName(Scope *S, 116 const CXXScopeSpec &SS, 117 UnqualifiedId &Name, 118 TypeTy *ObjectTypePtr, 119 bool EnteringContext, 120 TemplateTy &TemplateResult) { 121 DeclarationName TName; 122 123 switch (Name.getKind()) { 124 case UnqualifiedId::IK_Identifier: 125 TName = DeclarationName(Name.Identifier); 126 break; 127 128 case UnqualifiedId::IK_OperatorFunctionId: 129 TName = Context.DeclarationNames.getCXXOperatorName( 130 Name.OperatorFunctionId.Operator); 131 break; 132 133 default: 134 return TNK_Non_template; 135 } 136 137 QualType ObjectType = QualType::getFromOpaquePtr(ObjectTypePtr); 138 139 LookupResult R(*this, TName, SourceLocation(), LookupOrdinaryName); 140 R.suppressDiagnostics(); 141 LookupTemplateName(R, S, SS, ObjectType, EnteringContext); 142 if (R.empty()) 143 return TNK_Non_template; 144 145 NamedDecl *Template = R.getAsSingleDecl(Context); 146 147 if (SS.isSet() && !SS.isInvalid()) { 148 NestedNameSpecifier *Qualifier 149 = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 150 if (OverloadedFunctionDecl *Ovl 151 = dyn_cast<OverloadedFunctionDecl>(Template)) 152 TemplateResult 153 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false, 154 Ovl)); 155 else 156 TemplateResult 157 = TemplateTy::make(Context.getQualifiedTemplateName(Qualifier, false, 158 cast<TemplateDecl>(Template))); 159 } else if (OverloadedFunctionDecl *Ovl 160 = dyn_cast<OverloadedFunctionDecl>(Template)) { 161 TemplateResult = TemplateTy::make(TemplateName(Ovl)); 162 } else { 163 TemplateResult = TemplateTy::make( 164 TemplateName(cast<TemplateDecl>(Template))); 165 } 166 167 if (isa<ClassTemplateDecl>(Template) || 168 isa<TemplateTemplateParmDecl>(Template)) 169 return TNK_Type_template; 170 171 assert((isa<FunctionTemplateDecl>(Template) || 172 isa<OverloadedFunctionDecl>(Template)) && 173 "Unhandled template kind in Sema::isTemplateName"); 174 return TNK_Function_template; 175} 176 177void Sema::LookupTemplateName(LookupResult &Found, 178 Scope *S, const CXXScopeSpec &SS, 179 QualType ObjectType, 180 bool EnteringContext) { 181 // Determine where to perform name lookup 182 DeclContext *LookupCtx = 0; 183 bool isDependent = false; 184 if (!ObjectType.isNull()) { 185 // This nested-name-specifier occurs in a member access expression, e.g., 186 // x->B::f, and we are looking into the type of the object. 187 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist"); 188 LookupCtx = computeDeclContext(ObjectType); 189 isDependent = ObjectType->isDependentType(); 190 assert((isDependent || !ObjectType->isIncompleteType()) && 191 "Caller should have completed object type"); 192 } else if (SS.isSet()) { 193 // This nested-name-specifier occurs after another nested-name-specifier, 194 // so long into the context associated with the prior nested-name-specifier. 195 LookupCtx = computeDeclContext(SS, EnteringContext); 196 isDependent = isDependentScopeSpecifier(SS); 197 198 // The declaration context must be complete. 199 if (LookupCtx && RequireCompleteDeclContext(SS)) 200 return; 201 } 202 203 bool ObjectTypeSearchedInScope = false; 204 if (LookupCtx) { 205 // Perform "qualified" name lookup into the declaration context we 206 // computed, which is either the type of the base of a member access 207 // expression or the declaration context associated with a prior 208 // nested-name-specifier. 209 LookupQualifiedName(Found, LookupCtx); 210 211 if (!ObjectType.isNull() && Found.empty()) { 212 // C++ [basic.lookup.classref]p1: 213 // In a class member access expression (5.2.5), if the . or -> token is 214 // immediately followed by an identifier followed by a <, the 215 // identifier must be looked up to determine whether the < is the 216 // beginning of a template argument list (14.2) or a less-than operator. 217 // The identifier is first looked up in the class of the object 218 // expression. If the identifier is not found, it is then looked up in 219 // the context of the entire postfix-expression and shall name a class 220 // or function template. 221 // 222 // FIXME: When we're instantiating a template, do we actually have to 223 // look in the scope of the template? Seems fishy... 224 if (S) LookupName(Found, S); 225 ObjectTypeSearchedInScope = true; 226 } 227 } else if (isDependent) { 228 // We cannot look into a dependent object type or 229 return; 230 } else { 231 // Perform unqualified name lookup in the current scope. 232 LookupName(Found, S); 233 } 234 235 // FIXME: Cope with ambiguous name-lookup results. 236 assert(!Found.isAmbiguous() && 237 "Cannot handle template name-lookup ambiguities"); 238 239 FilterAcceptableTemplateNames(Context, Found); 240 if (Found.empty()) 241 return; 242 243 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) { 244 // C++ [basic.lookup.classref]p1: 245 // [...] If the lookup in the class of the object expression finds a 246 // template, the name is also looked up in the context of the entire 247 // postfix-expression and [...] 248 // 249 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(), 250 LookupOrdinaryName); 251 LookupName(FoundOuter, S); 252 FilterAcceptableTemplateNames(Context, FoundOuter); 253 // FIXME: Handle ambiguities in this lookup better 254 255 if (FoundOuter.empty()) { 256 // - if the name is not found, the name found in the class of the 257 // object expression is used, otherwise 258 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) { 259 // - if the name is found in the context of the entire 260 // postfix-expression and does not name a class template, the name 261 // found in the class of the object expression is used, otherwise 262 } else { 263 // - if the name found is a class template, it must refer to the same 264 // entity as the one found in the class of the object expression, 265 // otherwise the program is ill-formed. 266 if (!Found.isSingleResult() || 267 Found.getFoundDecl()->getCanonicalDecl() 268 != FoundOuter.getFoundDecl()->getCanonicalDecl()) { 269 Diag(Found.getNameLoc(), 270 diag::err_nested_name_member_ref_lookup_ambiguous) 271 << Found.getLookupName(); 272 Diag(Found.getRepresentativeDecl()->getLocation(), 273 diag::note_ambig_member_ref_object_type) 274 << ObjectType; 275 Diag(FoundOuter.getFoundDecl()->getLocation(), 276 diag::note_ambig_member_ref_scope); 277 278 // Recover by taking the template that we found in the object 279 // expression's type. 280 } 281 } 282 } 283} 284 285/// Constructs a full type for the given nested-name-specifier. 286static QualType GetTypeForQualifier(ASTContext &Context, 287 NestedNameSpecifier *Qualifier) { 288 // Three possibilities: 289 290 // 1. A namespace (global or not). 291 assert(!Qualifier->getAsNamespace() && "can't construct type for namespace"); 292 293 // 2. A type (templated or not). 294 Type *Ty = Qualifier->getAsType(); 295 if (Ty) return QualType(Ty, 0); 296 297 // 3. A dependent identifier. 298 assert(Qualifier->getAsIdentifier()); 299 return Context.getTypenameType(Qualifier->getPrefix(), 300 Qualifier->getAsIdentifier()); 301} 302 303static bool HasDependentTypeAsBase(ASTContext &Context, 304 CXXRecordDecl *Record, 305 CanQualType T) { 306 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(), 307 E = Record->bases_end(); I != E; ++I) { 308 CanQualType BaseT = Context.getCanonicalType((*I).getType()); 309 if (BaseT == T) 310 return true; 311 312 // We have to recurse here to cover some really bizarre cases. 313 // Obviously, we can only have the dependent type as an indirect 314 // base class through a dependent base class, and usually it's 315 // impossible to know which instantiation a dependent base class 316 // will have. But! If we're actually *inside* the dependent base 317 // class, then we know its instantiation and can therefore be 318 // reasonably expected to look into it. 319 320 // template <class T> class A : Base<T> { 321 // class Inner : A<T> { 322 // void foo() { 323 // Base<T>::foo(); // statically known to be an implicit member 324 // reference 325 // } 326 // }; 327 // }; 328 329 CanQual<RecordType> RT = BaseT->getAs<RecordType>(); 330 331 // Base might be a dependent member type, in which case we 332 // obviously can't look into it. 333 if (!RT) continue; 334 335 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(RT->getDecl()); 336 if (BaseRecord->isDefinition() && 337 HasDependentTypeAsBase(Context, BaseRecord, T)) 338 return true; 339 } 340 341 return false; 342} 343 344/// Checks whether the given dependent nested-name specifier 345/// introduces an implicit member reference. This is only true if the 346/// nested-name specifier names a type identical to one of the current 347/// instance method's context's (possibly indirect) base classes. 348static bool IsImplicitDependentMemberReference(Sema &SemaRef, 349 NestedNameSpecifier *Qualifier, 350 QualType &ThisType) { 351 // If the context isn't a C++ method, then it isn't an implicit 352 // member reference. 353 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext); 354 if (!MD || MD->isStatic()) 355 return false; 356 357 ASTContext &Context = SemaRef.Context; 358 359 // We want to check whether the method's context is known to inherit 360 // from the type named by the nested name specifier. The trivial 361 // case here is: 362 // template <class T> class Base { ... }; 363 // template <class T> class Derived : Base<T> { 364 // void foo() { 365 // Base<T>::foo(); 366 // } 367 // }; 368 369 QualType QT = GetTypeForQualifier(Context, Qualifier); 370 CanQualType T = Context.getCanonicalType(QT); 371 372 // And now, just walk the non-dependent type hierarchy, trying to 373 // find the given type as a literal base class. 374 CXXRecordDecl *Record = cast<CXXRecordDecl>(MD->getParent()); 375 if (Context.getCanonicalType(Context.getTypeDeclType(Record)) == T || 376 HasDependentTypeAsBase(Context, Record, T)) { 377 ThisType = MD->getThisType(Context); 378 return true; 379 } 380 381 return false; 382} 383 384/// ActOnDependentIdExpression - Handle a dependent declaration name 385/// that was just parsed. 386Sema::OwningExprResult 387Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS, 388 DeclarationName Name, 389 SourceLocation NameLoc, 390 bool CheckForImplicitMember, 391 const TemplateArgumentListInfo *TemplateArgs) { 392 NestedNameSpecifier *Qualifier 393 = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 394 395 QualType ThisType; 396 if (CheckForImplicitMember && 397 IsImplicitDependentMemberReference(*this, Qualifier, ThisType)) { 398 Expr *This = new (Context) CXXThisExpr(SourceLocation(), ThisType); 399 400 // Since the 'this' expression is synthesized, we don't need to 401 // perform the double-lookup check. 402 NamedDecl *FirstQualifierInScope = 0; 403 404 return Owned(CXXDependentScopeMemberExpr::Create(Context, This, true, 405 /*Op*/ SourceLocation(), 406 Qualifier, SS.getRange(), 407 FirstQualifierInScope, 408 Name, NameLoc, 409 TemplateArgs)); 410 } 411 412 return BuildDependentDeclRefExpr(SS, Name, NameLoc, TemplateArgs); 413} 414 415Sema::OwningExprResult 416Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS, 417 DeclarationName Name, 418 SourceLocation NameLoc, 419 const TemplateArgumentListInfo *TemplateArgs) { 420 return Owned(DependentScopeDeclRefExpr::Create(Context, 421 static_cast<NestedNameSpecifier*>(SS.getScopeRep()), 422 SS.getRange(), 423 Name, NameLoc, 424 TemplateArgs)); 425} 426 427/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining 428/// that the template parameter 'PrevDecl' is being shadowed by a new 429/// declaration at location Loc. Returns true to indicate that this is 430/// an error, and false otherwise. 431bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) { 432 assert(PrevDecl->isTemplateParameter() && "Not a template parameter"); 433 434 // Microsoft Visual C++ permits template parameters to be shadowed. 435 if (getLangOptions().Microsoft) 436 return false; 437 438 // C++ [temp.local]p4: 439 // A template-parameter shall not be redeclared within its 440 // scope (including nested scopes). 441 Diag(Loc, diag::err_template_param_shadow) 442 << cast<NamedDecl>(PrevDecl)->getDeclName(); 443 Diag(PrevDecl->getLocation(), diag::note_template_param_here); 444 return true; 445} 446 447/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset 448/// the parameter D to reference the templated declaration and return a pointer 449/// to the template declaration. Otherwise, do nothing to D and return null. 450TemplateDecl *Sema::AdjustDeclIfTemplate(DeclPtrTy &D) { 451 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D.getAs<Decl>())) { 452 D = DeclPtrTy::make(Temp->getTemplatedDecl()); 453 return Temp; 454 } 455 return 0; 456} 457 458static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef, 459 const ParsedTemplateArgument &Arg) { 460 461 switch (Arg.getKind()) { 462 case ParsedTemplateArgument::Type: { 463 DeclaratorInfo *DI; 464 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI); 465 if (!DI) 466 DI = SemaRef.Context.getTrivialDeclaratorInfo(T, Arg.getLocation()); 467 return TemplateArgumentLoc(TemplateArgument(T), DI); 468 } 469 470 case ParsedTemplateArgument::NonType: { 471 Expr *E = static_cast<Expr *>(Arg.getAsExpr()); 472 return TemplateArgumentLoc(TemplateArgument(E), E); 473 } 474 475 case ParsedTemplateArgument::Template: { 476 TemplateName Template 477 = TemplateName::getFromVoidPointer(Arg.getAsTemplate().get()); 478 return TemplateArgumentLoc(TemplateArgument(Template), 479 Arg.getScopeSpec().getRange(), 480 Arg.getLocation()); 481 } 482 } 483 484 llvm::llvm_unreachable("Unhandled parsed template argument"); 485 return TemplateArgumentLoc(); 486} 487 488/// \brief Translates template arguments as provided by the parser 489/// into template arguments used by semantic analysis. 490void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn, 491 TemplateArgumentListInfo &TemplateArgs) { 492 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I) 493 TemplateArgs.addArgument(translateTemplateArgument(*this, 494 TemplateArgsIn[I])); 495} 496 497/// ActOnTypeParameter - Called when a C++ template type parameter 498/// (e.g., "typename T") has been parsed. Typename specifies whether 499/// the keyword "typename" was used to declare the type parameter 500/// (otherwise, "class" was used), and KeyLoc is the location of the 501/// "class" or "typename" keyword. ParamName is the name of the 502/// parameter (NULL indicates an unnamed template parameter) and 503/// ParamName is the location of the parameter name (if any). 504/// If the type parameter has a default argument, it will be added 505/// later via ActOnTypeParameterDefault. 506Sema::DeclPtrTy Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis, 507 SourceLocation EllipsisLoc, 508 SourceLocation KeyLoc, 509 IdentifierInfo *ParamName, 510 SourceLocation ParamNameLoc, 511 unsigned Depth, unsigned Position) { 512 assert(S->isTemplateParamScope() && 513 "Template type parameter not in template parameter scope!"); 514 bool Invalid = false; 515 516 if (ParamName) { 517 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName); 518 if (PrevDecl && PrevDecl->isTemplateParameter()) 519 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc, 520 PrevDecl); 521 } 522 523 SourceLocation Loc = ParamNameLoc; 524 if (!ParamName) 525 Loc = KeyLoc; 526 527 TemplateTypeParmDecl *Param 528 = TemplateTypeParmDecl::Create(Context, CurContext, Loc, 529 Depth, Position, ParamName, Typename, 530 Ellipsis); 531 if (Invalid) 532 Param->setInvalidDecl(); 533 534 if (ParamName) { 535 // Add the template parameter into the current scope. 536 S->AddDecl(DeclPtrTy::make(Param)); 537 IdResolver.AddDecl(Param); 538 } 539 540 return DeclPtrTy::make(Param); 541} 542 543/// ActOnTypeParameterDefault - Adds a default argument (the type 544/// Default) to the given template type parameter (TypeParam). 545void Sema::ActOnTypeParameterDefault(DeclPtrTy TypeParam, 546 SourceLocation EqualLoc, 547 SourceLocation DefaultLoc, 548 TypeTy *DefaultT) { 549 TemplateTypeParmDecl *Parm 550 = cast<TemplateTypeParmDecl>(TypeParam.getAs<Decl>()); 551 552 DeclaratorInfo *DefaultDInfo; 553 GetTypeFromParser(DefaultT, &DefaultDInfo); 554 555 assert(DefaultDInfo && "expected source information for type"); 556 557 // C++0x [temp.param]p9: 558 // A default template-argument may be specified for any kind of 559 // template-parameter that is not a template parameter pack. 560 if (Parm->isParameterPack()) { 561 Diag(DefaultLoc, diag::err_template_param_pack_default_arg); 562 return; 563 } 564 565 // C++ [temp.param]p14: 566 // A template-parameter shall not be used in its own default argument. 567 // FIXME: Implement this check! Needs a recursive walk over the types. 568 569 // Check the template argument itself. 570 if (CheckTemplateArgument(Parm, DefaultDInfo)) { 571 Parm->setInvalidDecl(); 572 return; 573 } 574 575 Parm->setDefaultArgument(DefaultDInfo, false); 576} 577 578/// \brief Check that the type of a non-type template parameter is 579/// well-formed. 580/// 581/// \returns the (possibly-promoted) parameter type if valid; 582/// otherwise, produces a diagnostic and returns a NULL type. 583QualType 584Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) { 585 // C++ [temp.param]p4: 586 // 587 // A non-type template-parameter shall have one of the following 588 // (optionally cv-qualified) types: 589 // 590 // -- integral or enumeration type, 591 if (T->isIntegralType() || T->isEnumeralType() || 592 // -- pointer to object or pointer to function, 593 (T->isPointerType() && 594 (T->getAs<PointerType>()->getPointeeType()->isObjectType() || 595 T->getAs<PointerType>()->getPointeeType()->isFunctionType())) || 596 // -- reference to object or reference to function, 597 T->isReferenceType() || 598 // -- pointer to member. 599 T->isMemberPointerType() || 600 // If T is a dependent type, we can't do the check now, so we 601 // assume that it is well-formed. 602 T->isDependentType()) 603 return T; 604 // C++ [temp.param]p8: 605 // 606 // A non-type template-parameter of type "array of T" or 607 // "function returning T" is adjusted to be of type "pointer to 608 // T" or "pointer to function returning T", respectively. 609 else if (T->isArrayType()) 610 // FIXME: Keep the type prior to promotion? 611 return Context.getArrayDecayedType(T); 612 else if (T->isFunctionType()) 613 // FIXME: Keep the type prior to promotion? 614 return Context.getPointerType(T); 615 616 Diag(Loc, diag::err_template_nontype_parm_bad_type) 617 << T; 618 619 return QualType(); 620} 621 622/// ActOnNonTypeTemplateParameter - Called when a C++ non-type 623/// template parameter (e.g., "int Size" in "template<int Size> 624/// class Array") has been parsed. S is the current scope and D is 625/// the parsed declarator. 626Sema::DeclPtrTy Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, 627 unsigned Depth, 628 unsigned Position) { 629 DeclaratorInfo *DInfo = 0; 630 QualType T = GetTypeForDeclarator(D, S, &DInfo); 631 632 assert(S->isTemplateParamScope() && 633 "Non-type template parameter not in template parameter scope!"); 634 bool Invalid = false; 635 636 IdentifierInfo *ParamName = D.getIdentifier(); 637 if (ParamName) { 638 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, LookupTagName); 639 if (PrevDecl && PrevDecl->isTemplateParameter()) 640 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 641 PrevDecl); 642 } 643 644 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc()); 645 if (T.isNull()) { 646 T = Context.IntTy; // Recover with an 'int' type. 647 Invalid = true; 648 } 649 650 NonTypeTemplateParmDecl *Param 651 = NonTypeTemplateParmDecl::Create(Context, CurContext, D.getIdentifierLoc(), 652 Depth, Position, ParamName, T, DInfo); 653 if (Invalid) 654 Param->setInvalidDecl(); 655 656 if (D.getIdentifier()) { 657 // Add the template parameter into the current scope. 658 S->AddDecl(DeclPtrTy::make(Param)); 659 IdResolver.AddDecl(Param); 660 } 661 return DeclPtrTy::make(Param); 662} 663 664/// \brief Adds a default argument to the given non-type template 665/// parameter. 666void Sema::ActOnNonTypeTemplateParameterDefault(DeclPtrTy TemplateParamD, 667 SourceLocation EqualLoc, 668 ExprArg DefaultE) { 669 NonTypeTemplateParmDecl *TemplateParm 670 = cast<NonTypeTemplateParmDecl>(TemplateParamD.getAs<Decl>()); 671 Expr *Default = static_cast<Expr *>(DefaultE.get()); 672 673 // C++ [temp.param]p14: 674 // A template-parameter shall not be used in its own default argument. 675 // FIXME: Implement this check! Needs a recursive walk over the types. 676 677 // Check the well-formedness of the default template argument. 678 TemplateArgument Converted; 679 if (CheckTemplateArgument(TemplateParm, TemplateParm->getType(), Default, 680 Converted)) { 681 TemplateParm->setInvalidDecl(); 682 return; 683 } 684 685 TemplateParm->setDefaultArgument(DefaultE.takeAs<Expr>()); 686} 687 688 689/// ActOnTemplateTemplateParameter - Called when a C++ template template 690/// parameter (e.g. T in template <template <typename> class T> class array) 691/// has been parsed. S is the current scope. 692Sema::DeclPtrTy Sema::ActOnTemplateTemplateParameter(Scope* S, 693 SourceLocation TmpLoc, 694 TemplateParamsTy *Params, 695 IdentifierInfo *Name, 696 SourceLocation NameLoc, 697 unsigned Depth, 698 unsigned Position) { 699 assert(S->isTemplateParamScope() && 700 "Template template parameter not in template parameter scope!"); 701 702 // Construct the parameter object. 703 TemplateTemplateParmDecl *Param = 704 TemplateTemplateParmDecl::Create(Context, CurContext, TmpLoc, Depth, 705 Position, Name, 706 (TemplateParameterList*)Params); 707 708 // Make sure the parameter is valid. 709 // FIXME: Decl object is not currently invalidated anywhere so this doesn't 710 // do anything yet. However, if the template parameter list or (eventual) 711 // default value is ever invalidated, that will propagate here. 712 bool Invalid = false; 713 if (Invalid) { 714 Param->setInvalidDecl(); 715 } 716 717 // If the tt-param has a name, then link the identifier into the scope 718 // and lookup mechanisms. 719 if (Name) { 720 S->AddDecl(DeclPtrTy::make(Param)); 721 IdResolver.AddDecl(Param); 722 } 723 724 return DeclPtrTy::make(Param); 725} 726 727/// \brief Adds a default argument to the given template template 728/// parameter. 729void Sema::ActOnTemplateTemplateParameterDefault(DeclPtrTy TemplateParamD, 730 SourceLocation EqualLoc, 731 const ParsedTemplateArgument &Default) { 732 TemplateTemplateParmDecl *TemplateParm 733 = cast<TemplateTemplateParmDecl>(TemplateParamD.getAs<Decl>()); 734 735 // C++ [temp.param]p14: 736 // A template-parameter shall not be used in its own default argument. 737 // FIXME: Implement this check! Needs a recursive walk over the types. 738 739 // Check only that we have a template template argument. We don't want to 740 // try to check well-formedness now, because our template template parameter 741 // might have dependent types in its template parameters, which we wouldn't 742 // be able to match now. 743 // 744 // If none of the template template parameter's template arguments mention 745 // other template parameters, we could actually perform more checking here. 746 // However, it isn't worth doing. 747 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default); 748 if (DefaultArg.getArgument().getAsTemplate().isNull()) { 749 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template) 750 << DefaultArg.getSourceRange(); 751 return; 752 } 753 754 TemplateParm->setDefaultArgument(DefaultArg); 755} 756 757/// ActOnTemplateParameterList - Builds a TemplateParameterList that 758/// contains the template parameters in Params/NumParams. 759Sema::TemplateParamsTy * 760Sema::ActOnTemplateParameterList(unsigned Depth, 761 SourceLocation ExportLoc, 762 SourceLocation TemplateLoc, 763 SourceLocation LAngleLoc, 764 DeclPtrTy *Params, unsigned NumParams, 765 SourceLocation RAngleLoc) { 766 if (ExportLoc.isValid()) 767 Diag(ExportLoc, diag::warn_template_export_unsupported); 768 769 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc, 770 (NamedDecl**)Params, NumParams, 771 RAngleLoc); 772} 773 774Sema::DeclResult 775Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, 776 SourceLocation KWLoc, const CXXScopeSpec &SS, 777 IdentifierInfo *Name, SourceLocation NameLoc, 778 AttributeList *Attr, 779 TemplateParameterList *TemplateParams, 780 AccessSpecifier AS) { 781 assert(TemplateParams && TemplateParams->size() > 0 && 782 "No template parameters"); 783 assert(TUK != TUK_Reference && "Can only declare or define class templates"); 784 bool Invalid = false; 785 786 // Check that we can declare a template here. 787 if (CheckTemplateDeclScope(S, TemplateParams)) 788 return true; 789 790 TagDecl::TagKind Kind = TagDecl::getTagKindForTypeSpec(TagSpec); 791 assert(Kind != TagDecl::TK_enum && "can't build template of enumerated type"); 792 793 // There is no such thing as an unnamed class template. 794 if (!Name) { 795 Diag(KWLoc, diag::err_template_unnamed_class); 796 return true; 797 } 798 799 // Find any previous declaration with this name. 800 DeclContext *SemanticContext; 801 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName, 802 ForRedeclaration); 803 if (SS.isNotEmpty() && !SS.isInvalid()) { 804 if (RequireCompleteDeclContext(SS)) 805 return true; 806 807 SemanticContext = computeDeclContext(SS, true); 808 if (!SemanticContext) { 809 // FIXME: Produce a reasonable diagnostic here 810 return true; 811 } 812 813 LookupQualifiedName(Previous, SemanticContext); 814 } else { 815 SemanticContext = CurContext; 816 LookupName(Previous, S); 817 } 818 819 assert(!Previous.isAmbiguous() && "Ambiguity in class template redecl?"); 820 NamedDecl *PrevDecl = 0; 821 if (Previous.begin() != Previous.end()) 822 PrevDecl = *Previous.begin(); 823 824 if (PrevDecl && TUK == TUK_Friend) { 825 // C++ [namespace.memdef]p3: 826 // [...] When looking for a prior declaration of a class or a function 827 // declared as a friend, and when the name of the friend class or 828 // function is neither a qualified name nor a template-id, scopes outside 829 // the innermost enclosing namespace scope are not considered. 830 DeclContext *OutermostContext = CurContext; 831 while (!OutermostContext->isFileContext()) 832 OutermostContext = OutermostContext->getLookupParent(); 833 834 if (OutermostContext->Equals(PrevDecl->getDeclContext()) || 835 OutermostContext->Encloses(PrevDecl->getDeclContext())) { 836 SemanticContext = PrevDecl->getDeclContext(); 837 } else { 838 // Declarations in outer scopes don't matter. However, the outermost 839 // context we computed is the semantic context for our new 840 // declaration. 841 PrevDecl = 0; 842 SemanticContext = OutermostContext; 843 } 844 845 if (CurContext->isDependentContext()) { 846 // If this is a dependent context, we don't want to link the friend 847 // class template to the template in scope, because that would perform 848 // checking of the template parameter lists that can't be performed 849 // until the outer context is instantiated. 850 PrevDecl = 0; 851 } 852 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S)) 853 PrevDecl = 0; 854 855 // If there is a previous declaration with the same name, check 856 // whether this is a valid redeclaration. 857 ClassTemplateDecl *PrevClassTemplate 858 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl); 859 860 // We may have found the injected-class-name of a class template, 861 // class template partial specialization, or class template specialization. 862 // In these cases, grab the template that is being defined or specialized. 863 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) && 864 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) { 865 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext()); 866 PrevClassTemplate 867 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate(); 868 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) { 869 PrevClassTemplate 870 = cast<ClassTemplateSpecializationDecl>(PrevDecl) 871 ->getSpecializedTemplate(); 872 } 873 } 874 875 if (PrevClassTemplate) { 876 // Ensure that the template parameter lists are compatible. 877 if (!TemplateParameterListsAreEqual(TemplateParams, 878 PrevClassTemplate->getTemplateParameters(), 879 /*Complain=*/true, 880 TPL_TemplateMatch)) 881 return true; 882 883 // C++ [temp.class]p4: 884 // In a redeclaration, partial specialization, explicit 885 // specialization or explicit instantiation of a class template, 886 // the class-key shall agree in kind with the original class 887 // template declaration (7.1.5.3). 888 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl(); 889 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) { 890 Diag(KWLoc, diag::err_use_with_wrong_tag) 891 << Name 892 << CodeModificationHint::CreateReplacement(KWLoc, 893 PrevRecordDecl->getKindName()); 894 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use); 895 Kind = PrevRecordDecl->getTagKind(); 896 } 897 898 // Check for redefinition of this class template. 899 if (TUK == TUK_Definition) { 900 if (TagDecl *Def = PrevRecordDecl->getDefinition(Context)) { 901 Diag(NameLoc, diag::err_redefinition) << Name; 902 Diag(Def->getLocation(), diag::note_previous_definition); 903 // FIXME: Would it make sense to try to "forget" the previous 904 // definition, as part of error recovery? 905 return true; 906 } 907 } 908 } else if (PrevDecl && PrevDecl->isTemplateParameter()) { 909 // Maybe we will complain about the shadowed template parameter. 910 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl); 911 // Just pretend that we didn't see the previous declaration. 912 PrevDecl = 0; 913 } else if (PrevDecl) { 914 // C++ [temp]p5: 915 // A class template shall not have the same name as any other 916 // template, class, function, object, enumeration, enumerator, 917 // namespace, or type in the same scope (3.3), except as specified 918 // in (14.5.4). 919 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 920 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 921 return true; 922 } 923 924 // Check the template parameter list of this declaration, possibly 925 // merging in the template parameter list from the previous class 926 // template declaration. 927 if (CheckTemplateParameterList(TemplateParams, 928 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0, 929 TPC_ClassTemplate)) 930 Invalid = true; 931 932 // FIXME: If we had a scope specifier, we better have a previous template 933 // declaration! 934 935 CXXRecordDecl *NewClass = 936 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc, 937 PrevClassTemplate? 938 PrevClassTemplate->getTemplatedDecl() : 0, 939 /*DelayTypeCreation=*/true); 940 941 ClassTemplateDecl *NewTemplate 942 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc, 943 DeclarationName(Name), TemplateParams, 944 NewClass, PrevClassTemplate); 945 NewClass->setDescribedClassTemplate(NewTemplate); 946 947 // Build the type for the class template declaration now. 948 QualType T = 949 Context.getTypeDeclType(NewClass, 950 PrevClassTemplate? 951 PrevClassTemplate->getTemplatedDecl() : 0); 952 assert(T->isDependentType() && "Class template type is not dependent?"); 953 (void)T; 954 955 // If we are providing an explicit specialization of a member that is a 956 // class template, make a note of that. 957 if (PrevClassTemplate && 958 PrevClassTemplate->getInstantiatedFromMemberTemplate()) 959 PrevClassTemplate->setMemberSpecialization(); 960 961 // Set the access specifier. 962 if (!Invalid && TUK != TUK_Friend) 963 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS); 964 965 // Set the lexical context of these templates 966 NewClass->setLexicalDeclContext(CurContext); 967 NewTemplate->setLexicalDeclContext(CurContext); 968 969 if (TUK == TUK_Definition) 970 NewClass->startDefinition(); 971 972 if (Attr) 973 ProcessDeclAttributeList(S, NewClass, Attr); 974 975 if (TUK != TUK_Friend) 976 PushOnScopeChains(NewTemplate, S); 977 else { 978 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) { 979 NewTemplate->setAccess(PrevClassTemplate->getAccess()); 980 NewClass->setAccess(PrevClassTemplate->getAccess()); 981 } 982 983 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */ 984 PrevClassTemplate != NULL); 985 986 // Friend templates are visible in fairly strange ways. 987 if (!CurContext->isDependentContext()) { 988 DeclContext *DC = SemanticContext->getLookupContext(); 989 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false); 990 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 991 PushOnScopeChains(NewTemplate, EnclosingScope, 992 /* AddToContext = */ false); 993 } 994 995 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, 996 NewClass->getLocation(), 997 NewTemplate, 998 /*FIXME:*/NewClass->getLocation()); 999 Friend->setAccess(AS_public); 1000 CurContext->addDecl(Friend); 1001 } 1002 1003 if (Invalid) { 1004 NewTemplate->setInvalidDecl(); 1005 NewClass->setInvalidDecl(); 1006 } 1007 return DeclPtrTy::make(NewTemplate); 1008} 1009 1010/// \brief Diagnose the presence of a default template argument on a 1011/// template parameter, which is ill-formed in certain contexts. 1012/// 1013/// \returns true if the default template argument should be dropped. 1014static bool DiagnoseDefaultTemplateArgument(Sema &S, 1015 Sema::TemplateParamListContext TPC, 1016 SourceLocation ParamLoc, 1017 SourceRange DefArgRange) { 1018 switch (TPC) { 1019 case Sema::TPC_ClassTemplate: 1020 return false; 1021 1022 case Sema::TPC_FunctionTemplate: 1023 // C++ [temp.param]p9: 1024 // A default template-argument shall not be specified in a 1025 // function template declaration or a function template 1026 // definition [...] 1027 // (This sentence is not in C++0x, per DR226). 1028 if (!S.getLangOptions().CPlusPlus0x) 1029 S.Diag(ParamLoc, 1030 diag::err_template_parameter_default_in_function_template) 1031 << DefArgRange; 1032 return false; 1033 1034 case Sema::TPC_ClassTemplateMember: 1035 // C++0x [temp.param]p9: 1036 // A default template-argument shall not be specified in the 1037 // template-parameter-lists of the definition of a member of a 1038 // class template that appears outside of the member's class. 1039 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member) 1040 << DefArgRange; 1041 return true; 1042 1043 case Sema::TPC_FriendFunctionTemplate: 1044 // C++ [temp.param]p9: 1045 // A default template-argument shall not be specified in a 1046 // friend template declaration. 1047 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template) 1048 << DefArgRange; 1049 return true; 1050 1051 // FIXME: C++0x [temp.param]p9 allows default template-arguments 1052 // for friend function templates if there is only a single 1053 // declaration (and it is a definition). Strange! 1054 } 1055 1056 return false; 1057} 1058 1059/// \brief Checks the validity of a template parameter list, possibly 1060/// considering the template parameter list from a previous 1061/// declaration. 1062/// 1063/// If an "old" template parameter list is provided, it must be 1064/// equivalent (per TemplateParameterListsAreEqual) to the "new" 1065/// template parameter list. 1066/// 1067/// \param NewParams Template parameter list for a new template 1068/// declaration. This template parameter list will be updated with any 1069/// default arguments that are carried through from the previous 1070/// template parameter list. 1071/// 1072/// \param OldParams If provided, template parameter list from a 1073/// previous declaration of the same template. Default template 1074/// arguments will be merged from the old template parameter list to 1075/// the new template parameter list. 1076/// 1077/// \param TPC Describes the context in which we are checking the given 1078/// template parameter list. 1079/// 1080/// \returns true if an error occurred, false otherwise. 1081bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams, 1082 TemplateParameterList *OldParams, 1083 TemplateParamListContext TPC) { 1084 bool Invalid = false; 1085 1086 // C++ [temp.param]p10: 1087 // The set of default template-arguments available for use with a 1088 // template declaration or definition is obtained by merging the 1089 // default arguments from the definition (if in scope) and all 1090 // declarations in scope in the same way default function 1091 // arguments are (8.3.6). 1092 bool SawDefaultArgument = false; 1093 SourceLocation PreviousDefaultArgLoc; 1094 1095 bool SawParameterPack = false; 1096 SourceLocation ParameterPackLoc; 1097 1098 // Dummy initialization to avoid warnings. 1099 TemplateParameterList::iterator OldParam = NewParams->end(); 1100 if (OldParams) 1101 OldParam = OldParams->begin(); 1102 1103 for (TemplateParameterList::iterator NewParam = NewParams->begin(), 1104 NewParamEnd = NewParams->end(); 1105 NewParam != NewParamEnd; ++NewParam) { 1106 // Variables used to diagnose redundant default arguments 1107 bool RedundantDefaultArg = false; 1108 SourceLocation OldDefaultLoc; 1109 SourceLocation NewDefaultLoc; 1110 1111 // Variables used to diagnose missing default arguments 1112 bool MissingDefaultArg = false; 1113 1114 // C++0x [temp.param]p11: 1115 // If a template parameter of a class template is a template parameter pack, 1116 // it must be the last template parameter. 1117 if (SawParameterPack) { 1118 Diag(ParameterPackLoc, 1119 diag::err_template_param_pack_must_be_last_template_parameter); 1120 Invalid = true; 1121 } 1122 1123 if (TemplateTypeParmDecl *NewTypeParm 1124 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) { 1125 // Check the presence of a default argument here. 1126 if (NewTypeParm->hasDefaultArgument() && 1127 DiagnoseDefaultTemplateArgument(*this, TPC, 1128 NewTypeParm->getLocation(), 1129 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc() 1130 .getFullSourceRange())) 1131 NewTypeParm->removeDefaultArgument(); 1132 1133 // Merge default arguments for template type parameters. 1134 TemplateTypeParmDecl *OldTypeParm 1135 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0; 1136 1137 if (NewTypeParm->isParameterPack()) { 1138 assert(!NewTypeParm->hasDefaultArgument() && 1139 "Parameter packs can't have a default argument!"); 1140 SawParameterPack = true; 1141 ParameterPackLoc = NewTypeParm->getLocation(); 1142 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() && 1143 NewTypeParm->hasDefaultArgument()) { 1144 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc(); 1145 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc(); 1146 SawDefaultArgument = true; 1147 RedundantDefaultArg = true; 1148 PreviousDefaultArgLoc = NewDefaultLoc; 1149 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) { 1150 // Merge the default argument from the old declaration to the 1151 // new declaration. 1152 SawDefaultArgument = true; 1153 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(), 1154 true); 1155 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc(); 1156 } else if (NewTypeParm->hasDefaultArgument()) { 1157 SawDefaultArgument = true; 1158 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc(); 1159 } else if (SawDefaultArgument) 1160 MissingDefaultArg = true; 1161 } else if (NonTypeTemplateParmDecl *NewNonTypeParm 1162 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) { 1163 // Check the presence of a default argument here. 1164 if (NewNonTypeParm->hasDefaultArgument() && 1165 DiagnoseDefaultTemplateArgument(*this, TPC, 1166 NewNonTypeParm->getLocation(), 1167 NewNonTypeParm->getDefaultArgument()->getSourceRange())) { 1168 NewNonTypeParm->getDefaultArgument()->Destroy(Context); 1169 NewNonTypeParm->setDefaultArgument(0); 1170 } 1171 1172 // Merge default arguments for non-type template parameters 1173 NonTypeTemplateParmDecl *OldNonTypeParm 1174 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0; 1175 if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() && 1176 NewNonTypeParm->hasDefaultArgument()) { 1177 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc(); 1178 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc(); 1179 SawDefaultArgument = true; 1180 RedundantDefaultArg = true; 1181 PreviousDefaultArgLoc = NewDefaultLoc; 1182 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) { 1183 // Merge the default argument from the old declaration to the 1184 // new declaration. 1185 SawDefaultArgument = true; 1186 // FIXME: We need to create a new kind of "default argument" 1187 // expression that points to a previous template template 1188 // parameter. 1189 NewNonTypeParm->setDefaultArgument( 1190 OldNonTypeParm->getDefaultArgument()); 1191 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc(); 1192 } else if (NewNonTypeParm->hasDefaultArgument()) { 1193 SawDefaultArgument = true; 1194 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc(); 1195 } else if (SawDefaultArgument) 1196 MissingDefaultArg = true; 1197 } else { 1198 // Check the presence of a default argument here. 1199 TemplateTemplateParmDecl *NewTemplateParm 1200 = cast<TemplateTemplateParmDecl>(*NewParam); 1201 if (NewTemplateParm->hasDefaultArgument() && 1202 DiagnoseDefaultTemplateArgument(*this, TPC, 1203 NewTemplateParm->getLocation(), 1204 NewTemplateParm->getDefaultArgument().getSourceRange())) 1205 NewTemplateParm->setDefaultArgument(TemplateArgumentLoc()); 1206 1207 // Merge default arguments for template template parameters 1208 TemplateTemplateParmDecl *OldTemplateParm 1209 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0; 1210 if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() && 1211 NewTemplateParm->hasDefaultArgument()) { 1212 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation(); 1213 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation(); 1214 SawDefaultArgument = true; 1215 RedundantDefaultArg = true; 1216 PreviousDefaultArgLoc = NewDefaultLoc; 1217 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) { 1218 // Merge the default argument from the old declaration to the 1219 // new declaration. 1220 SawDefaultArgument = true; 1221 // FIXME: We need to create a new kind of "default argument" expression 1222 // that points to a previous template template parameter. 1223 NewTemplateParm->setDefaultArgument( 1224 OldTemplateParm->getDefaultArgument()); 1225 PreviousDefaultArgLoc 1226 = OldTemplateParm->getDefaultArgument().getLocation(); 1227 } else if (NewTemplateParm->hasDefaultArgument()) { 1228 SawDefaultArgument = true; 1229 PreviousDefaultArgLoc 1230 = NewTemplateParm->getDefaultArgument().getLocation(); 1231 } else if (SawDefaultArgument) 1232 MissingDefaultArg = true; 1233 } 1234 1235 if (RedundantDefaultArg) { 1236 // C++ [temp.param]p12: 1237 // A template-parameter shall not be given default arguments 1238 // by two different declarations in the same scope. 1239 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition); 1240 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg); 1241 Invalid = true; 1242 } else if (MissingDefaultArg) { 1243 // C++ [temp.param]p11: 1244 // If a template-parameter has a default template-argument, 1245 // all subsequent template-parameters shall have a default 1246 // template-argument supplied. 1247 Diag((*NewParam)->getLocation(), 1248 diag::err_template_param_default_arg_missing); 1249 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg); 1250 Invalid = true; 1251 } 1252 1253 // If we have an old template parameter list that we're merging 1254 // in, move on to the next parameter. 1255 if (OldParams) 1256 ++OldParam; 1257 } 1258 1259 return Invalid; 1260} 1261 1262/// \brief Match the given template parameter lists to the given scope 1263/// specifier, returning the template parameter list that applies to the 1264/// name. 1265/// 1266/// \param DeclStartLoc the start of the declaration that has a scope 1267/// specifier or a template parameter list. 1268/// 1269/// \param SS the scope specifier that will be matched to the given template 1270/// parameter lists. This scope specifier precedes a qualified name that is 1271/// being declared. 1272/// 1273/// \param ParamLists the template parameter lists, from the outermost to the 1274/// innermost template parameter lists. 1275/// 1276/// \param NumParamLists the number of template parameter lists in ParamLists. 1277/// 1278/// \param IsExplicitSpecialization will be set true if the entity being 1279/// declared is an explicit specialization, false otherwise. 1280/// 1281/// \returns the template parameter list, if any, that corresponds to the 1282/// name that is preceded by the scope specifier @p SS. This template 1283/// parameter list may be have template parameters (if we're declaring a 1284/// template) or may have no template parameters (if we're declaring a 1285/// template specialization), or may be NULL (if we were's declaring isn't 1286/// itself a template). 1287TemplateParameterList * 1288Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, 1289 const CXXScopeSpec &SS, 1290 TemplateParameterList **ParamLists, 1291 unsigned NumParamLists, 1292 bool &IsExplicitSpecialization) { 1293 IsExplicitSpecialization = false; 1294 1295 // Find the template-ids that occur within the nested-name-specifier. These 1296 // template-ids will match up with the template parameter lists. 1297 llvm::SmallVector<const TemplateSpecializationType *, 4> 1298 TemplateIdsInSpecifier; 1299 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4> 1300 ExplicitSpecializationsInSpecifier; 1301 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep(); 1302 NNS; NNS = NNS->getPrefix()) { 1303 if (const TemplateSpecializationType *SpecType 1304 = dyn_cast_or_null<TemplateSpecializationType>(NNS->getAsType())) { 1305 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl(); 1306 if (!Template) 1307 continue; // FIXME: should this be an error? probably... 1308 1309 if (const RecordType *Record = SpecType->getAs<RecordType>()) { 1310 ClassTemplateSpecializationDecl *SpecDecl 1311 = cast<ClassTemplateSpecializationDecl>(Record->getDecl()); 1312 // If the nested name specifier refers to an explicit specialization, 1313 // we don't need a template<> header. 1314 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) { 1315 ExplicitSpecializationsInSpecifier.push_back(SpecDecl); 1316 continue; 1317 } 1318 } 1319 1320 TemplateIdsInSpecifier.push_back(SpecType); 1321 } 1322 } 1323 1324 // Reverse the list of template-ids in the scope specifier, so that we can 1325 // more easily match up the template-ids and the template parameter lists. 1326 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end()); 1327 1328 SourceLocation FirstTemplateLoc = DeclStartLoc; 1329 if (NumParamLists) 1330 FirstTemplateLoc = ParamLists[0]->getTemplateLoc(); 1331 1332 // Match the template-ids found in the specifier to the template parameter 1333 // lists. 1334 unsigned Idx = 0; 1335 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size(); 1336 Idx != NumTemplateIds; ++Idx) { 1337 QualType TemplateId = QualType(TemplateIdsInSpecifier[Idx], 0); 1338 bool DependentTemplateId = TemplateId->isDependentType(); 1339 if (Idx >= NumParamLists) { 1340 // We have a template-id without a corresponding template parameter 1341 // list. 1342 if (DependentTemplateId) { 1343 // FIXME: the location information here isn't great. 1344 Diag(SS.getRange().getBegin(), 1345 diag::err_template_spec_needs_template_parameters) 1346 << TemplateId 1347 << SS.getRange(); 1348 } else { 1349 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header) 1350 << SS.getRange() 1351 << CodeModificationHint::CreateInsertion(FirstTemplateLoc, 1352 "template<> "); 1353 IsExplicitSpecialization = true; 1354 } 1355 return 0; 1356 } 1357 1358 // Check the template parameter list against its corresponding template-id. 1359 if (DependentTemplateId) { 1360 TemplateDecl *Template 1361 = TemplateIdsInSpecifier[Idx]->getTemplateName().getAsTemplateDecl(); 1362 1363 if (ClassTemplateDecl *ClassTemplate 1364 = dyn_cast<ClassTemplateDecl>(Template)) { 1365 TemplateParameterList *ExpectedTemplateParams = 0; 1366 // Is this template-id naming the primary template? 1367 if (Context.hasSameType(TemplateId, 1368 ClassTemplate->getInjectedClassNameType(Context))) 1369 ExpectedTemplateParams = ClassTemplate->getTemplateParameters(); 1370 // ... or a partial specialization? 1371 else if (ClassTemplatePartialSpecializationDecl *PartialSpec 1372 = ClassTemplate->findPartialSpecialization(TemplateId)) 1373 ExpectedTemplateParams = PartialSpec->getTemplateParameters(); 1374 1375 if (ExpectedTemplateParams) 1376 TemplateParameterListsAreEqual(ParamLists[Idx], 1377 ExpectedTemplateParams, 1378 true, TPL_TemplateMatch); 1379 } 1380 1381 CheckTemplateParameterList(ParamLists[Idx], 0, TPC_ClassTemplateMember); 1382 } else if (ParamLists[Idx]->size() > 0) 1383 Diag(ParamLists[Idx]->getTemplateLoc(), 1384 diag::err_template_param_list_matches_nontemplate) 1385 << TemplateId 1386 << ParamLists[Idx]->getSourceRange(); 1387 else 1388 IsExplicitSpecialization = true; 1389 } 1390 1391 // If there were at least as many template-ids as there were template 1392 // parameter lists, then there are no template parameter lists remaining for 1393 // the declaration itself. 1394 if (Idx >= NumParamLists) 1395 return 0; 1396 1397 // If there were too many template parameter lists, complain about that now. 1398 if (Idx != NumParamLists - 1) { 1399 while (Idx < NumParamLists - 1) { 1400 bool isExplicitSpecHeader = ParamLists[Idx]->size() == 0; 1401 Diag(ParamLists[Idx]->getTemplateLoc(), 1402 isExplicitSpecHeader? diag::warn_template_spec_extra_headers 1403 : diag::err_template_spec_extra_headers) 1404 << SourceRange(ParamLists[Idx]->getTemplateLoc(), 1405 ParamLists[Idx]->getRAngleLoc()); 1406 1407 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) { 1408 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(), 1409 diag::note_explicit_template_spec_does_not_need_header) 1410 << ExplicitSpecializationsInSpecifier.back(); 1411 ExplicitSpecializationsInSpecifier.pop_back(); 1412 } 1413 1414 ++Idx; 1415 } 1416 } 1417 1418 // Return the last template parameter list, which corresponds to the 1419 // entity being declared. 1420 return ParamLists[NumParamLists - 1]; 1421} 1422 1423QualType Sema::CheckTemplateIdType(TemplateName Name, 1424 SourceLocation TemplateLoc, 1425 const TemplateArgumentListInfo &TemplateArgs) { 1426 TemplateDecl *Template = Name.getAsTemplateDecl(); 1427 if (!Template) { 1428 // The template name does not resolve to a template, so we just 1429 // build a dependent template-id type. 1430 return Context.getTemplateSpecializationType(Name, TemplateArgs); 1431 } 1432 1433 // Check that the template argument list is well-formed for this 1434 // template. 1435 TemplateArgumentListBuilder Converted(Template->getTemplateParameters(), 1436 TemplateArgs.size()); 1437 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs, 1438 false, Converted)) 1439 return QualType(); 1440 1441 assert((Converted.structuredSize() == 1442 Template->getTemplateParameters()->size()) && 1443 "Converted template argument list is too short!"); 1444 1445 QualType CanonType; 1446 1447 if (Name.isDependent() || 1448 TemplateSpecializationType::anyDependentTemplateArguments( 1449 TemplateArgs)) { 1450 // This class template specialization is a dependent 1451 // type. Therefore, its canonical type is another class template 1452 // specialization type that contains all of the converted 1453 // arguments in canonical form. This ensures that, e.g., A<T> and 1454 // A<T, T> have identical types when A is declared as: 1455 // 1456 // template<typename T, typename U = T> struct A; 1457 TemplateName CanonName = Context.getCanonicalTemplateName(Name); 1458 CanonType = Context.getTemplateSpecializationType(CanonName, 1459 Converted.getFlatArguments(), 1460 Converted.flatSize()); 1461 1462 // FIXME: CanonType is not actually the canonical type, and unfortunately 1463 // it is a TemplateSpecializationType that we will never use again. 1464 // In the future, we need to teach getTemplateSpecializationType to only 1465 // build the canonical type and return that to us. 1466 CanonType = Context.getCanonicalType(CanonType); 1467 } else if (ClassTemplateDecl *ClassTemplate 1468 = dyn_cast<ClassTemplateDecl>(Template)) { 1469 // Find the class template specialization declaration that 1470 // corresponds to these arguments. 1471 llvm::FoldingSetNodeID ID; 1472 ClassTemplateSpecializationDecl::Profile(ID, 1473 Converted.getFlatArguments(), 1474 Converted.flatSize(), 1475 Context); 1476 void *InsertPos = 0; 1477 ClassTemplateSpecializationDecl *Decl 1478 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos); 1479 if (!Decl) { 1480 // This is the first time we have referenced this class template 1481 // specialization. Create the canonical declaration and add it to 1482 // the set of specializations. 1483 Decl = ClassTemplateSpecializationDecl::Create(Context, 1484 ClassTemplate->getDeclContext(), 1485 ClassTemplate->getLocation(), 1486 ClassTemplate, 1487 Converted, 0); 1488 ClassTemplate->getSpecializations().InsertNode(Decl, InsertPos); 1489 Decl->setLexicalDeclContext(CurContext); 1490 } 1491 1492 CanonType = Context.getTypeDeclType(Decl); 1493 } 1494 1495 // Build the fully-sugared type for this class template 1496 // specialization, which refers back to the class template 1497 // specialization we created or found. 1498 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType); 1499} 1500 1501Action::TypeResult 1502Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc, 1503 SourceLocation LAngleLoc, 1504 ASTTemplateArgsPtr TemplateArgsIn, 1505 SourceLocation RAngleLoc) { 1506 TemplateName Template = TemplateD.getAsVal<TemplateName>(); 1507 1508 // Translate the parser's template argument list in our AST format. 1509 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); 1510 translateTemplateArguments(TemplateArgsIn, TemplateArgs); 1511 1512 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs); 1513 TemplateArgsIn.release(); 1514 1515 if (Result.isNull()) 1516 return true; 1517 1518 DeclaratorInfo *DI = Context.CreateDeclaratorInfo(Result); 1519 TemplateSpecializationTypeLoc TL 1520 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc()); 1521 TL.setTemplateNameLoc(TemplateLoc); 1522 TL.setLAngleLoc(LAngleLoc); 1523 TL.setRAngleLoc(RAngleLoc); 1524 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 1525 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo()); 1526 1527 return CreateLocInfoType(Result, DI).getAsOpaquePtr(); 1528} 1529 1530Sema::TypeResult Sema::ActOnTagTemplateIdType(TypeResult TypeResult, 1531 TagUseKind TUK, 1532 DeclSpec::TST TagSpec, 1533 SourceLocation TagLoc) { 1534 if (TypeResult.isInvalid()) 1535 return Sema::TypeResult(); 1536 1537 // FIXME: preserve source info, ideally without copying the DI. 1538 DeclaratorInfo *DI; 1539 QualType Type = GetTypeFromParser(TypeResult.get(), &DI); 1540 1541 // Verify the tag specifier. 1542 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec); 1543 1544 if (const RecordType *RT = Type->getAs<RecordType>()) { 1545 RecordDecl *D = RT->getDecl(); 1546 1547 IdentifierInfo *Id = D->getIdentifier(); 1548 assert(Id && "templated class must have an identifier"); 1549 1550 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) { 1551 Diag(TagLoc, diag::err_use_with_wrong_tag) 1552 << Type 1553 << CodeModificationHint::CreateReplacement(SourceRange(TagLoc), 1554 D->getKindName()); 1555 Diag(D->getLocation(), diag::note_previous_use); 1556 } 1557 } 1558 1559 QualType ElabType = Context.getElaboratedType(Type, TagKind); 1560 1561 return ElabType.getAsOpaquePtr(); 1562} 1563 1564Sema::OwningExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS, 1565 LookupResult &R, 1566 bool RequiresADL, 1567 const TemplateArgumentListInfo &TemplateArgs) { 1568 // FIXME: Can we do any checking at this point? I guess we could check the 1569 // template arguments that we have against the template name, if the template 1570 // name refers to a single template. That's not a terribly common case, 1571 // though. 1572 1573 // These should be filtered out by our callers. 1574 assert(!R.empty() && "empty lookup results when building templateid"); 1575 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid"); 1576 1577 NestedNameSpecifier *Qualifier = 0; 1578 SourceRange QualifierRange; 1579 if (SS.isSet()) { 1580 Qualifier = static_cast<NestedNameSpecifier*>(SS.getScopeRep()); 1581 QualifierRange = SS.getRange(); 1582 } 1583 1584 bool Dependent 1585 = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 1586 &TemplateArgs); 1587 UnresolvedLookupExpr *ULE 1588 = UnresolvedLookupExpr::Create(Context, Dependent, 1589 Qualifier, QualifierRange, 1590 R.getLookupName(), R.getNameLoc(), 1591 RequiresADL, TemplateArgs); 1592 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 1593 ULE->addDecl(*I); 1594 1595 return Owned(ULE); 1596} 1597 1598// We actually only call this from template instantiation. 1599Sema::OwningExprResult 1600Sema::BuildQualifiedTemplateIdExpr(const CXXScopeSpec &SS, 1601 DeclarationName Name, 1602 SourceLocation NameLoc, 1603 const TemplateArgumentListInfo &TemplateArgs) { 1604 DeclContext *DC; 1605 if (!(DC = computeDeclContext(SS, false)) || 1606 DC->isDependentContext() || 1607 RequireCompleteDeclContext(SS)) 1608 return BuildDependentDeclRefExpr(SS, Name, NameLoc, &TemplateArgs); 1609 1610 LookupResult R(*this, Name, NameLoc, LookupOrdinaryName); 1611 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false); 1612 1613 if (R.isAmbiguous()) 1614 return ExprError(); 1615 1616 if (R.empty()) { 1617 Diag(NameLoc, diag::err_template_kw_refers_to_non_template) 1618 << Name << SS.getRange(); 1619 return ExprError(); 1620 } 1621 1622 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) { 1623 Diag(NameLoc, diag::err_template_kw_refers_to_class_template) 1624 << (NestedNameSpecifier*) SS.getScopeRep() << Name << SS.getRange(); 1625 Diag(Temp->getLocation(), diag::note_referenced_class_template); 1626 return ExprError(); 1627 } 1628 1629 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs); 1630} 1631 1632/// \brief Form a dependent template name. 1633/// 1634/// This action forms a dependent template name given the template 1635/// name and its (presumably dependent) scope specifier. For 1636/// example, given "MetaFun::template apply", the scope specifier \p 1637/// SS will be "MetaFun::", \p TemplateKWLoc contains the location 1638/// of the "template" keyword, and "apply" is the \p Name. 1639Sema::TemplateTy 1640Sema::ActOnDependentTemplateName(SourceLocation TemplateKWLoc, 1641 const CXXScopeSpec &SS, 1642 UnqualifiedId &Name, 1643 TypeTy *ObjectType, 1644 bool EnteringContext) { 1645 if ((ObjectType && 1646 computeDeclContext(QualType::getFromOpaquePtr(ObjectType))) || 1647 (SS.isSet() && computeDeclContext(SS, EnteringContext))) { 1648 // C++0x [temp.names]p5: 1649 // If a name prefixed by the keyword template is not the name of 1650 // a template, the program is ill-formed. [Note: the keyword 1651 // template may not be applied to non-template members of class 1652 // templates. -end note ] [ Note: as is the case with the 1653 // typename prefix, the template prefix is allowed in cases 1654 // where it is not strictly necessary; i.e., when the 1655 // nested-name-specifier or the expression on the left of the -> 1656 // or . is not dependent on a template-parameter, or the use 1657 // does not appear in the scope of a template. -end note] 1658 // 1659 // Note: C++03 was more strict here, because it banned the use of 1660 // the "template" keyword prior to a template-name that was not a 1661 // dependent name. C++ DR468 relaxed this requirement (the 1662 // "template" keyword is now permitted). We follow the C++0x 1663 // rules, even in C++03 mode, retroactively applying the DR. 1664 TemplateTy Template; 1665 TemplateNameKind TNK = isTemplateName(0, SS, Name, ObjectType, 1666 EnteringContext, Template); 1667 if (TNK == TNK_Non_template) { 1668 Diag(Name.getSourceRange().getBegin(), 1669 diag::err_template_kw_refers_to_non_template) 1670 << GetNameFromUnqualifiedId(Name) 1671 << Name.getSourceRange(); 1672 return TemplateTy(); 1673 } 1674 1675 return Template; 1676 } 1677 1678 NestedNameSpecifier *Qualifier 1679 = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 1680 1681 switch (Name.getKind()) { 1682 case UnqualifiedId::IK_Identifier: 1683 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, 1684 Name.Identifier)); 1685 1686 case UnqualifiedId::IK_OperatorFunctionId: 1687 return TemplateTy::make(Context.getDependentTemplateName(Qualifier, 1688 Name.OperatorFunctionId.Operator)); 1689 1690 default: 1691 break; 1692 } 1693 1694 Diag(Name.getSourceRange().getBegin(), 1695 diag::err_template_kw_refers_to_non_template) 1696 << GetNameFromUnqualifiedId(Name) 1697 << Name.getSourceRange(); 1698 return TemplateTy(); 1699} 1700 1701bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, 1702 const TemplateArgumentLoc &AL, 1703 TemplateArgumentListBuilder &Converted) { 1704 const TemplateArgument &Arg = AL.getArgument(); 1705 1706 // Check template type parameter. 1707 if (Arg.getKind() != TemplateArgument::Type) { 1708 // C++ [temp.arg.type]p1: 1709 // A template-argument for a template-parameter which is a 1710 // type shall be a type-id. 1711 1712 // We have a template type parameter but the template argument 1713 // is not a type. 1714 SourceRange SR = AL.getSourceRange(); 1715 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR; 1716 Diag(Param->getLocation(), diag::note_template_param_here); 1717 1718 return true; 1719 } 1720 1721 if (CheckTemplateArgument(Param, AL.getSourceDeclaratorInfo())) 1722 return true; 1723 1724 // Add the converted template type argument. 1725 Converted.Append( 1726 TemplateArgument(Context.getCanonicalType(Arg.getAsType()))); 1727 return false; 1728} 1729 1730/// \brief Substitute template arguments into the default template argument for 1731/// the given template type parameter. 1732/// 1733/// \param SemaRef the semantic analysis object for which we are performing 1734/// the substitution. 1735/// 1736/// \param Template the template that we are synthesizing template arguments 1737/// for. 1738/// 1739/// \param TemplateLoc the location of the template name that started the 1740/// template-id we are checking. 1741/// 1742/// \param RAngleLoc the location of the right angle bracket ('>') that 1743/// terminates the template-id. 1744/// 1745/// \param Param the template template parameter whose default we are 1746/// substituting into. 1747/// 1748/// \param Converted the list of template arguments provided for template 1749/// parameters that precede \p Param in the template parameter list. 1750/// 1751/// \returns the substituted template argument, or NULL if an error occurred. 1752static DeclaratorInfo * 1753SubstDefaultTemplateArgument(Sema &SemaRef, 1754 TemplateDecl *Template, 1755 SourceLocation TemplateLoc, 1756 SourceLocation RAngleLoc, 1757 TemplateTypeParmDecl *Param, 1758 TemplateArgumentListBuilder &Converted) { 1759 DeclaratorInfo *ArgType = Param->getDefaultArgumentInfo(); 1760 1761 // If the argument type is dependent, instantiate it now based 1762 // on the previously-computed template arguments. 1763 if (ArgType->getType()->isDependentType()) { 1764 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted, 1765 /*TakeArgs=*/false); 1766 1767 MultiLevelTemplateArgumentList AllTemplateArgs 1768 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs); 1769 1770 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, 1771 Template, Converted.getFlatArguments(), 1772 Converted.flatSize(), 1773 SourceRange(TemplateLoc, RAngleLoc)); 1774 1775 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs, 1776 Param->getDefaultArgumentLoc(), 1777 Param->getDeclName()); 1778 } 1779 1780 return ArgType; 1781} 1782 1783/// \brief Substitute template arguments into the default template argument for 1784/// the given non-type template parameter. 1785/// 1786/// \param SemaRef the semantic analysis object for which we are performing 1787/// the substitution. 1788/// 1789/// \param Template the template that we are synthesizing template arguments 1790/// for. 1791/// 1792/// \param TemplateLoc the location of the template name that started the 1793/// template-id we are checking. 1794/// 1795/// \param RAngleLoc the location of the right angle bracket ('>') that 1796/// terminates the template-id. 1797/// 1798/// \param Param the non-type template parameter whose default we are 1799/// substituting into. 1800/// 1801/// \param Converted the list of template arguments provided for template 1802/// parameters that precede \p Param in the template parameter list. 1803/// 1804/// \returns the substituted template argument, or NULL if an error occurred. 1805static Sema::OwningExprResult 1806SubstDefaultTemplateArgument(Sema &SemaRef, 1807 TemplateDecl *Template, 1808 SourceLocation TemplateLoc, 1809 SourceLocation RAngleLoc, 1810 NonTypeTemplateParmDecl *Param, 1811 TemplateArgumentListBuilder &Converted) { 1812 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted, 1813 /*TakeArgs=*/false); 1814 1815 MultiLevelTemplateArgumentList AllTemplateArgs 1816 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs); 1817 1818 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, 1819 Template, Converted.getFlatArguments(), 1820 Converted.flatSize(), 1821 SourceRange(TemplateLoc, RAngleLoc)); 1822 1823 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs); 1824} 1825 1826/// \brief Substitute template arguments into the default template argument for 1827/// the given template template parameter. 1828/// 1829/// \param SemaRef the semantic analysis object for which we are performing 1830/// the substitution. 1831/// 1832/// \param Template the template that we are synthesizing template arguments 1833/// for. 1834/// 1835/// \param TemplateLoc the location of the template name that started the 1836/// template-id we are checking. 1837/// 1838/// \param RAngleLoc the location of the right angle bracket ('>') that 1839/// terminates the template-id. 1840/// 1841/// \param Param the template template parameter whose default we are 1842/// substituting into. 1843/// 1844/// \param Converted the list of template arguments provided for template 1845/// parameters that precede \p Param in the template parameter list. 1846/// 1847/// \returns the substituted template argument, or NULL if an error occurred. 1848static TemplateName 1849SubstDefaultTemplateArgument(Sema &SemaRef, 1850 TemplateDecl *Template, 1851 SourceLocation TemplateLoc, 1852 SourceLocation RAngleLoc, 1853 TemplateTemplateParmDecl *Param, 1854 TemplateArgumentListBuilder &Converted) { 1855 TemplateArgumentList TemplateArgs(SemaRef.Context, Converted, 1856 /*TakeArgs=*/false); 1857 1858 MultiLevelTemplateArgumentList AllTemplateArgs 1859 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs); 1860 1861 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, 1862 Template, Converted.getFlatArguments(), 1863 Converted.flatSize(), 1864 SourceRange(TemplateLoc, RAngleLoc)); 1865 1866 return SemaRef.SubstTemplateName( 1867 Param->getDefaultArgument().getArgument().getAsTemplate(), 1868 Param->getDefaultArgument().getTemplateNameLoc(), 1869 AllTemplateArgs); 1870} 1871 1872/// \brief If the given template parameter has a default template 1873/// argument, substitute into that default template argument and 1874/// return the corresponding template argument. 1875TemplateArgumentLoc 1876Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, 1877 SourceLocation TemplateLoc, 1878 SourceLocation RAngleLoc, 1879 Decl *Param, 1880 TemplateArgumentListBuilder &Converted) { 1881 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) { 1882 if (!TypeParm->hasDefaultArgument()) 1883 return TemplateArgumentLoc(); 1884 1885 DeclaratorInfo *DI = SubstDefaultTemplateArgument(*this, Template, 1886 TemplateLoc, 1887 RAngleLoc, 1888 TypeParm, 1889 Converted); 1890 if (DI) 1891 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI); 1892 1893 return TemplateArgumentLoc(); 1894 } 1895 1896 if (NonTypeTemplateParmDecl *NonTypeParm 1897 = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 1898 if (!NonTypeParm->hasDefaultArgument()) 1899 return TemplateArgumentLoc(); 1900 1901 OwningExprResult Arg = SubstDefaultTemplateArgument(*this, Template, 1902 TemplateLoc, 1903 RAngleLoc, 1904 NonTypeParm, 1905 Converted); 1906 if (Arg.isInvalid()) 1907 return TemplateArgumentLoc(); 1908 1909 Expr *ArgE = Arg.takeAs<Expr>(); 1910 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE); 1911 } 1912 1913 TemplateTemplateParmDecl *TempTempParm 1914 = cast<TemplateTemplateParmDecl>(Param); 1915 if (!TempTempParm->hasDefaultArgument()) 1916 return TemplateArgumentLoc(); 1917 1918 TemplateName TName = SubstDefaultTemplateArgument(*this, Template, 1919 TemplateLoc, 1920 RAngleLoc, 1921 TempTempParm, 1922 Converted); 1923 if (TName.isNull()) 1924 return TemplateArgumentLoc(); 1925 1926 return TemplateArgumentLoc(TemplateArgument(TName), 1927 TempTempParm->getDefaultArgument().getTemplateQualifierRange(), 1928 TempTempParm->getDefaultArgument().getTemplateNameLoc()); 1929} 1930 1931/// \brief Check that the given template argument corresponds to the given 1932/// template parameter. 1933bool Sema::CheckTemplateArgument(NamedDecl *Param, 1934 const TemplateArgumentLoc &Arg, 1935 TemplateDecl *Template, 1936 SourceLocation TemplateLoc, 1937 SourceLocation RAngleLoc, 1938 TemplateArgumentListBuilder &Converted) { 1939 // Check template type parameters. 1940 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) 1941 return CheckTemplateTypeArgument(TTP, Arg, Converted); 1942 1943 // Check non-type template parameters. 1944 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) { 1945 // Do substitution on the type of the non-type template parameter 1946 // with the template arguments we've seen thus far. 1947 QualType NTTPType = NTTP->getType(); 1948 if (NTTPType->isDependentType()) { 1949 // Do substitution on the type of the non-type template parameter. 1950 InstantiatingTemplate Inst(*this, TemplateLoc, Template, 1951 NTTP, Converted.getFlatArguments(), 1952 Converted.flatSize(), 1953 SourceRange(TemplateLoc, RAngleLoc)); 1954 1955 TemplateArgumentList TemplateArgs(Context, Converted, 1956 /*TakeArgs=*/false); 1957 NTTPType = SubstType(NTTPType, 1958 MultiLevelTemplateArgumentList(TemplateArgs), 1959 NTTP->getLocation(), 1960 NTTP->getDeclName()); 1961 // If that worked, check the non-type template parameter type 1962 // for validity. 1963 if (!NTTPType.isNull()) 1964 NTTPType = CheckNonTypeTemplateParameterType(NTTPType, 1965 NTTP->getLocation()); 1966 if (NTTPType.isNull()) 1967 return true; 1968 } 1969 1970 switch (Arg.getArgument().getKind()) { 1971 case TemplateArgument::Null: 1972 assert(false && "Should never see a NULL template argument here"); 1973 return true; 1974 1975 case TemplateArgument::Expression: { 1976 Expr *E = Arg.getArgument().getAsExpr(); 1977 TemplateArgument Result; 1978 if (CheckTemplateArgument(NTTP, NTTPType, E, Result)) 1979 return true; 1980 1981 Converted.Append(Result); 1982 break; 1983 } 1984 1985 case TemplateArgument::Declaration: 1986 case TemplateArgument::Integral: 1987 // We've already checked this template argument, so just copy 1988 // it to the list of converted arguments. 1989 Converted.Append(Arg.getArgument()); 1990 break; 1991 1992 case TemplateArgument::Template: 1993 // We were given a template template argument. It may not be ill-formed; 1994 // see below. 1995 if (DependentTemplateName *DTN 1996 = Arg.getArgument().getAsTemplate().getAsDependentTemplateName()) { 1997 // We have a template argument such as \c T::template X, which we 1998 // parsed as a template template argument. However, since we now 1999 // know that we need a non-type template argument, convert this 2000 // template name into an expression. 2001 Expr *E = DependentScopeDeclRefExpr::Create(Context, 2002 DTN->getQualifier(), 2003 Arg.getTemplateQualifierRange(), 2004 DTN->getIdentifier(), 2005 Arg.getTemplateNameLoc()); 2006 2007 TemplateArgument Result; 2008 if (CheckTemplateArgument(NTTP, NTTPType, E, Result)) 2009 return true; 2010 2011 Converted.Append(Result); 2012 break; 2013 } 2014 2015 // We have a template argument that actually does refer to a class 2016 // template, template alias, or template template parameter, and 2017 // therefore cannot be a non-type template argument. 2018 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr) 2019 << Arg.getSourceRange(); 2020 2021 Diag(Param->getLocation(), diag::note_template_param_here); 2022 return true; 2023 2024 case TemplateArgument::Type: { 2025 // We have a non-type template parameter but the template 2026 // argument is a type. 2027 2028 // C++ [temp.arg]p2: 2029 // In a template-argument, an ambiguity between a type-id and 2030 // an expression is resolved to a type-id, regardless of the 2031 // form of the corresponding template-parameter. 2032 // 2033 // We warn specifically about this case, since it can be rather 2034 // confusing for users. 2035 QualType T = Arg.getArgument().getAsType(); 2036 SourceRange SR = Arg.getSourceRange(); 2037 if (T->isFunctionType()) 2038 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T; 2039 else 2040 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR; 2041 Diag(Param->getLocation(), diag::note_template_param_here); 2042 return true; 2043 } 2044 2045 case TemplateArgument::Pack: 2046 llvm::llvm_unreachable("Caller must expand template argument packs"); 2047 break; 2048 } 2049 2050 return false; 2051 } 2052 2053 2054 // Check template template parameters. 2055 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param); 2056 2057 // Substitute into the template parameter list of the template 2058 // template parameter, since previously-supplied template arguments 2059 // may appear within the template template parameter. 2060 { 2061 // Set up a template instantiation context. 2062 LocalInstantiationScope Scope(*this); 2063 InstantiatingTemplate Inst(*this, TemplateLoc, Template, 2064 TempParm, Converted.getFlatArguments(), 2065 Converted.flatSize(), 2066 SourceRange(TemplateLoc, RAngleLoc)); 2067 2068 TemplateArgumentList TemplateArgs(Context, Converted, 2069 /*TakeArgs=*/false); 2070 TempParm = cast_or_null<TemplateTemplateParmDecl>( 2071 SubstDecl(TempParm, CurContext, 2072 MultiLevelTemplateArgumentList(TemplateArgs))); 2073 if (!TempParm) 2074 return true; 2075 2076 // FIXME: TempParam is leaked. 2077 } 2078 2079 switch (Arg.getArgument().getKind()) { 2080 case TemplateArgument::Null: 2081 assert(false && "Should never see a NULL template argument here"); 2082 return true; 2083 2084 case TemplateArgument::Template: 2085 if (CheckTemplateArgument(TempParm, Arg)) 2086 return true; 2087 2088 Converted.Append(Arg.getArgument()); 2089 break; 2090 2091 case TemplateArgument::Expression: 2092 case TemplateArgument::Type: 2093 // We have a template template parameter but the template 2094 // argument does not refer to a template. 2095 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template); 2096 return true; 2097 2098 case TemplateArgument::Declaration: 2099 llvm::llvm_unreachable( 2100 "Declaration argument with template template parameter"); 2101 break; 2102 case TemplateArgument::Integral: 2103 llvm::llvm_unreachable( 2104 "Integral argument with template template parameter"); 2105 break; 2106 2107 case TemplateArgument::Pack: 2108 llvm::llvm_unreachable("Caller must expand template argument packs"); 2109 break; 2110 } 2111 2112 return false; 2113} 2114 2115/// \brief Check that the given template argument list is well-formed 2116/// for specializing the given template. 2117bool Sema::CheckTemplateArgumentList(TemplateDecl *Template, 2118 SourceLocation TemplateLoc, 2119 const TemplateArgumentListInfo &TemplateArgs, 2120 bool PartialTemplateArgs, 2121 TemplateArgumentListBuilder &Converted) { 2122 TemplateParameterList *Params = Template->getTemplateParameters(); 2123 unsigned NumParams = Params->size(); 2124 unsigned NumArgs = TemplateArgs.size(); 2125 bool Invalid = false; 2126 2127 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc(); 2128 2129 bool HasParameterPack = 2130 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack(); 2131 2132 if ((NumArgs > NumParams && !HasParameterPack) || 2133 (NumArgs < Params->getMinRequiredArguments() && 2134 !PartialTemplateArgs)) { 2135 // FIXME: point at either the first arg beyond what we can handle, 2136 // or the '>', depending on whether we have too many or too few 2137 // arguments. 2138 SourceRange Range; 2139 if (NumArgs > NumParams) 2140 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc); 2141 Diag(TemplateLoc, diag::err_template_arg_list_different_arity) 2142 << (NumArgs > NumParams) 2143 << (isa<ClassTemplateDecl>(Template)? 0 : 2144 isa<FunctionTemplateDecl>(Template)? 1 : 2145 isa<TemplateTemplateParmDecl>(Template)? 2 : 3) 2146 << Template << Range; 2147 Diag(Template->getLocation(), diag::note_template_decl_here) 2148 << Params->getSourceRange(); 2149 Invalid = true; 2150 } 2151 2152 // C++ [temp.arg]p1: 2153 // [...] The type and form of each template-argument specified in 2154 // a template-id shall match the type and form specified for the 2155 // corresponding parameter declared by the template in its 2156 // template-parameter-list. 2157 unsigned ArgIdx = 0; 2158 for (TemplateParameterList::iterator Param = Params->begin(), 2159 ParamEnd = Params->end(); 2160 Param != ParamEnd; ++Param, ++ArgIdx) { 2161 if (ArgIdx > NumArgs && PartialTemplateArgs) 2162 break; 2163 2164 // If we have a template parameter pack, check every remaining template 2165 // argument against that template parameter pack. 2166 if ((*Param)->isTemplateParameterPack()) { 2167 Converted.BeginPack(); 2168 for (; ArgIdx < NumArgs; ++ArgIdx) { 2169 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template, 2170 TemplateLoc, RAngleLoc, Converted)) { 2171 Invalid = true; 2172 break; 2173 } 2174 } 2175 Converted.EndPack(); 2176 continue; 2177 } 2178 2179 if (ArgIdx < NumArgs) { 2180 // Check the template argument we were given. 2181 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template, 2182 TemplateLoc, RAngleLoc, Converted)) 2183 return true; 2184 2185 continue; 2186 } 2187 2188 // We have a default template argument that we will use. 2189 TemplateArgumentLoc Arg; 2190 2191 // Retrieve the default template argument from the template 2192 // parameter. For each kind of template parameter, we substitute the 2193 // template arguments provided thus far and any "outer" template arguments 2194 // (when the template parameter was part of a nested template) into 2195 // the default argument. 2196 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) { 2197 if (!TTP->hasDefaultArgument()) { 2198 assert((Invalid || PartialTemplateArgs) && "Missing default argument"); 2199 break; 2200 } 2201 2202 DeclaratorInfo *ArgType = SubstDefaultTemplateArgument(*this, 2203 Template, 2204 TemplateLoc, 2205 RAngleLoc, 2206 TTP, 2207 Converted); 2208 if (!ArgType) 2209 return true; 2210 2211 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()), 2212 ArgType); 2213 } else if (NonTypeTemplateParmDecl *NTTP 2214 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) { 2215 if (!NTTP->hasDefaultArgument()) { 2216 assert((Invalid || PartialTemplateArgs) && "Missing default argument"); 2217 break; 2218 } 2219 2220 Sema::OwningExprResult E = SubstDefaultTemplateArgument(*this, Template, 2221 TemplateLoc, 2222 RAngleLoc, 2223 NTTP, 2224 Converted); 2225 if (E.isInvalid()) 2226 return true; 2227 2228 Expr *Ex = E.takeAs<Expr>(); 2229 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex); 2230 } else { 2231 TemplateTemplateParmDecl *TempParm 2232 = cast<TemplateTemplateParmDecl>(*Param); 2233 2234 if (!TempParm->hasDefaultArgument()) { 2235 assert((Invalid || PartialTemplateArgs) && "Missing default argument"); 2236 break; 2237 } 2238 2239 TemplateName Name = SubstDefaultTemplateArgument(*this, Template, 2240 TemplateLoc, 2241 RAngleLoc, 2242 TempParm, 2243 Converted); 2244 if (Name.isNull()) 2245 return true; 2246 2247 Arg = TemplateArgumentLoc(TemplateArgument(Name), 2248 TempParm->getDefaultArgument().getTemplateQualifierRange(), 2249 TempParm->getDefaultArgument().getTemplateNameLoc()); 2250 } 2251 2252 // Introduce an instantiation record that describes where we are using 2253 // the default template argument. 2254 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param, 2255 Converted.getFlatArguments(), 2256 Converted.flatSize(), 2257 SourceRange(TemplateLoc, RAngleLoc)); 2258 2259 // Check the default template argument. 2260 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, 2261 RAngleLoc, Converted)) 2262 return true; 2263 } 2264 2265 return Invalid; 2266} 2267 2268/// \brief Check a template argument against its corresponding 2269/// template type parameter. 2270/// 2271/// This routine implements the semantics of C++ [temp.arg.type]. It 2272/// returns true if an error occurred, and false otherwise. 2273bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param, 2274 DeclaratorInfo *ArgInfo) { 2275 assert(ArgInfo && "invalid DeclaratorInfo"); 2276 QualType Arg = ArgInfo->getType(); 2277 2278 // C++ [temp.arg.type]p2: 2279 // A local type, a type with no linkage, an unnamed type or a type 2280 // compounded from any of these types shall not be used as a 2281 // template-argument for a template type-parameter. 2282 // 2283 // FIXME: Perform the recursive and no-linkage type checks. 2284 const TagType *Tag = 0; 2285 if (const EnumType *EnumT = Arg->getAs<EnumType>()) 2286 Tag = EnumT; 2287 else if (const RecordType *RecordT = Arg->getAs<RecordType>()) 2288 Tag = RecordT; 2289 if (Tag && Tag->getDecl()->getDeclContext()->isFunctionOrMethod()) { 2290 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange(); 2291 return Diag(SR.getBegin(), diag::err_template_arg_local_type) 2292 << QualType(Tag, 0) << SR; 2293 } else if (Tag && !Tag->getDecl()->getDeclName() && 2294 !Tag->getDecl()->getTypedefForAnonDecl()) { 2295 SourceRange SR = ArgInfo->getTypeLoc().getFullSourceRange(); 2296 Diag(SR.getBegin(), diag::err_template_arg_unnamed_type) << SR; 2297 Diag(Tag->getDecl()->getLocation(), diag::note_template_unnamed_type_here); 2298 return true; 2299 } 2300 2301 return false; 2302} 2303 2304/// \brief Checks whether the given template argument is the address 2305/// of an object or function according to C++ [temp.arg.nontype]p1. 2306bool Sema::CheckTemplateArgumentAddressOfObjectOrFunction(Expr *Arg, 2307 NamedDecl *&Entity) { 2308 bool Invalid = false; 2309 2310 // See through any implicit casts we added to fix the type. 2311 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg)) 2312 Arg = Cast->getSubExpr(); 2313 2314 // C++0x allows nullptr, and there's no further checking to be done for that. 2315 if (Arg->getType()->isNullPtrType()) 2316 return false; 2317 2318 // C++ [temp.arg.nontype]p1: 2319 // 2320 // A template-argument for a non-type, non-template 2321 // template-parameter shall be one of: [...] 2322 // 2323 // -- the address of an object or function with external 2324 // linkage, including function templates and function 2325 // template-ids but excluding non-static class members, 2326 // expressed as & id-expression where the & is optional if 2327 // the name refers to a function or array, or if the 2328 // corresponding template-parameter is a reference; or 2329 DeclRefExpr *DRE = 0; 2330 2331 // Ignore (and complain about) any excess parentheses. 2332 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) { 2333 if (!Invalid) { 2334 Diag(Arg->getSourceRange().getBegin(), 2335 diag::err_template_arg_extra_parens) 2336 << Arg->getSourceRange(); 2337 Invalid = true; 2338 } 2339 2340 Arg = Parens->getSubExpr(); 2341 } 2342 2343 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) { 2344 if (UnOp->getOpcode() == UnaryOperator::AddrOf) 2345 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr()); 2346 } else 2347 DRE = dyn_cast<DeclRefExpr>(Arg); 2348 2349 if (!DRE || !isa<ValueDecl>(DRE->getDecl())) 2350 return Diag(Arg->getSourceRange().getBegin(), 2351 diag::err_template_arg_not_object_or_func_form) 2352 << Arg->getSourceRange(); 2353 2354 // Cannot refer to non-static data members 2355 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) 2356 return Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field) 2357 << Field << Arg->getSourceRange(); 2358 2359 // Cannot refer to non-static member functions 2360 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl())) 2361 if (!Method->isStatic()) 2362 return Diag(Arg->getSourceRange().getBegin(), 2363 diag::err_template_arg_method) 2364 << Method << Arg->getSourceRange(); 2365 2366 // Functions must have external linkage. 2367 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) { 2368 if (Func->getStorageClass() == FunctionDecl::Static) { 2369 Diag(Arg->getSourceRange().getBegin(), 2370 diag::err_template_arg_function_not_extern) 2371 << Func << Arg->getSourceRange(); 2372 Diag(Func->getLocation(), diag::note_template_arg_internal_object) 2373 << true; 2374 return true; 2375 } 2376 2377 // Okay: we've named a function with external linkage. 2378 Entity = Func; 2379 return Invalid; 2380 } 2381 2382 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 2383 if (!Var->hasGlobalStorage()) { 2384 Diag(Arg->getSourceRange().getBegin(), 2385 diag::err_template_arg_object_not_extern) 2386 << Var << Arg->getSourceRange(); 2387 Diag(Var->getLocation(), diag::note_template_arg_internal_object) 2388 << true; 2389 return true; 2390 } 2391 2392 // Okay: we've named an object with external linkage 2393 Entity = Var; 2394 return Invalid; 2395 } 2396 2397 // We found something else, but we don't know specifically what it is. 2398 Diag(Arg->getSourceRange().getBegin(), 2399 diag::err_template_arg_not_object_or_func) 2400 << Arg->getSourceRange(); 2401 Diag(DRE->getDecl()->getLocation(), 2402 diag::note_template_arg_refers_here); 2403 return true; 2404} 2405 2406/// \brief Checks whether the given template argument is a pointer to 2407/// member constant according to C++ [temp.arg.nontype]p1. 2408bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, 2409 TemplateArgument &Converted) { 2410 bool Invalid = false; 2411 2412 // See through any implicit casts we added to fix the type. 2413 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg)) 2414 Arg = Cast->getSubExpr(); 2415 2416 // C++0x allows nullptr, and there's no further checking to be done for that. 2417 if (Arg->getType()->isNullPtrType()) 2418 return false; 2419 2420 // C++ [temp.arg.nontype]p1: 2421 // 2422 // A template-argument for a non-type, non-template 2423 // template-parameter shall be one of: [...] 2424 // 2425 // -- a pointer to member expressed as described in 5.3.1. 2426 DeclRefExpr *DRE = 0; 2427 2428 // Ignore (and complain about) any excess parentheses. 2429 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) { 2430 if (!Invalid) { 2431 Diag(Arg->getSourceRange().getBegin(), 2432 diag::err_template_arg_extra_parens) 2433 << Arg->getSourceRange(); 2434 Invalid = true; 2435 } 2436 2437 Arg = Parens->getSubExpr(); 2438 } 2439 2440 // A pointer-to-member constant written &Class::member. 2441 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) { 2442 if (UnOp->getOpcode() == UnaryOperator::AddrOf) { 2443 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr()); 2444 if (DRE && !DRE->getQualifier()) 2445 DRE = 0; 2446 } 2447 } 2448 // A constant of pointer-to-member type. 2449 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) { 2450 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) { 2451 if (VD->getType()->isMemberPointerType()) { 2452 if (isa<NonTypeTemplateParmDecl>(VD) || 2453 (isa<VarDecl>(VD) && 2454 Context.getCanonicalType(VD->getType()).isConstQualified())) { 2455 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2456 Converted = TemplateArgument(Arg->Retain()); 2457 else 2458 Converted = TemplateArgument(VD->getCanonicalDecl()); 2459 return Invalid; 2460 } 2461 } 2462 } 2463 2464 DRE = 0; 2465 } 2466 2467 if (!DRE) 2468 return Diag(Arg->getSourceRange().getBegin(), 2469 diag::err_template_arg_not_pointer_to_member_form) 2470 << Arg->getSourceRange(); 2471 2472 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) { 2473 assert((isa<FieldDecl>(DRE->getDecl()) || 2474 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) && 2475 "Only non-static member pointers can make it here"); 2476 2477 // Okay: this is the address of a non-static member, and therefore 2478 // a member pointer constant. 2479 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2480 Converted = TemplateArgument(Arg->Retain()); 2481 else 2482 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl()); 2483 return Invalid; 2484 } 2485 2486 // We found something else, but we don't know specifically what it is. 2487 Diag(Arg->getSourceRange().getBegin(), 2488 diag::err_template_arg_not_pointer_to_member_form) 2489 << Arg->getSourceRange(); 2490 Diag(DRE->getDecl()->getLocation(), 2491 diag::note_template_arg_refers_here); 2492 return true; 2493} 2494 2495/// \brief Check a template argument against its corresponding 2496/// non-type template parameter. 2497/// 2498/// This routine implements the semantics of C++ [temp.arg.nontype]. 2499/// It returns true if an error occurred, and false otherwise. \p 2500/// InstantiatedParamType is the type of the non-type template 2501/// parameter after it has been instantiated. 2502/// 2503/// If no error was detected, Converted receives the converted template argument. 2504bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param, 2505 QualType InstantiatedParamType, Expr *&Arg, 2506 TemplateArgument &Converted) { 2507 SourceLocation StartLoc = Arg->getSourceRange().getBegin(); 2508 2509 // If either the parameter has a dependent type or the argument is 2510 // type-dependent, there's nothing we can check now. 2511 // FIXME: Add template argument to Converted! 2512 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) { 2513 // FIXME: Produce a cloned, canonical expression? 2514 Converted = TemplateArgument(Arg); 2515 return false; 2516 } 2517 2518 // C++ [temp.arg.nontype]p5: 2519 // The following conversions are performed on each expression used 2520 // as a non-type template-argument. If a non-type 2521 // template-argument cannot be converted to the type of the 2522 // corresponding template-parameter then the program is 2523 // ill-formed. 2524 // 2525 // -- for a non-type template-parameter of integral or 2526 // enumeration type, integral promotions (4.5) and integral 2527 // conversions (4.7) are applied. 2528 QualType ParamType = InstantiatedParamType; 2529 QualType ArgType = Arg->getType(); 2530 if (ParamType->isIntegralType() || ParamType->isEnumeralType()) { 2531 // C++ [temp.arg.nontype]p1: 2532 // A template-argument for a non-type, non-template 2533 // template-parameter shall be one of: 2534 // 2535 // -- an integral constant-expression of integral or enumeration 2536 // type; or 2537 // -- the name of a non-type template-parameter; or 2538 SourceLocation NonConstantLoc; 2539 llvm::APSInt Value; 2540 if (!ArgType->isIntegralType() && !ArgType->isEnumeralType()) { 2541 Diag(Arg->getSourceRange().getBegin(), 2542 diag::err_template_arg_not_integral_or_enumeral) 2543 << ArgType << Arg->getSourceRange(); 2544 Diag(Param->getLocation(), diag::note_template_param_here); 2545 return true; 2546 } else if (!Arg->isValueDependent() && 2547 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) { 2548 Diag(NonConstantLoc, diag::err_template_arg_not_ice) 2549 << ArgType << Arg->getSourceRange(); 2550 return true; 2551 } 2552 2553 // FIXME: We need some way to more easily get the unqualified form 2554 // of the types without going all the way to the 2555 // canonical type. 2556 if (Context.getCanonicalType(ParamType).getCVRQualifiers()) 2557 ParamType = Context.getCanonicalType(ParamType).getUnqualifiedType(); 2558 if (Context.getCanonicalType(ArgType).getCVRQualifiers()) 2559 ArgType = Context.getCanonicalType(ArgType).getUnqualifiedType(); 2560 2561 // Try to convert the argument to the parameter's type. 2562 if (Context.hasSameType(ParamType, ArgType)) { 2563 // Okay: no conversion necessary 2564 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) || 2565 !ParamType->isEnumeralType()) { 2566 // This is an integral promotion or conversion. 2567 ImpCastExprToType(Arg, ParamType, CastExpr::CK_IntegralCast); 2568 } else { 2569 // We can't perform this conversion. 2570 Diag(Arg->getSourceRange().getBegin(), 2571 diag::err_template_arg_not_convertible) 2572 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange(); 2573 Diag(Param->getLocation(), diag::note_template_param_here); 2574 return true; 2575 } 2576 2577 QualType IntegerType = Context.getCanonicalType(ParamType); 2578 if (const EnumType *Enum = IntegerType->getAs<EnumType>()) 2579 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType()); 2580 2581 if (!Arg->isValueDependent()) { 2582 // Check that an unsigned parameter does not receive a negative 2583 // value. 2584 if (IntegerType->isUnsignedIntegerType() 2585 && (Value.isSigned() && Value.isNegative())) { 2586 Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_negative) 2587 << Value.toString(10) << Param->getType() 2588 << Arg->getSourceRange(); 2589 Diag(Param->getLocation(), diag::note_template_param_here); 2590 return true; 2591 } 2592 2593 // Check that we don't overflow the template parameter type. 2594 unsigned AllowedBits = Context.getTypeSize(IntegerType); 2595 if (Value.getActiveBits() > AllowedBits) { 2596 Diag(Arg->getSourceRange().getBegin(), 2597 diag::err_template_arg_too_large) 2598 << Value.toString(10) << Param->getType() 2599 << Arg->getSourceRange(); 2600 Diag(Param->getLocation(), diag::note_template_param_here); 2601 return true; 2602 } 2603 2604 if (Value.getBitWidth() != AllowedBits) 2605 Value.extOrTrunc(AllowedBits); 2606 Value.setIsSigned(IntegerType->isSignedIntegerType()); 2607 } 2608 2609 // Add the value of this argument to the list of converted 2610 // arguments. We use the bitwidth and signedness of the template 2611 // parameter. 2612 if (Arg->isValueDependent()) { 2613 // The argument is value-dependent. Create a new 2614 // TemplateArgument with the converted expression. 2615 Converted = TemplateArgument(Arg); 2616 return false; 2617 } 2618 2619 Converted = TemplateArgument(Value, 2620 ParamType->isEnumeralType() ? ParamType 2621 : IntegerType); 2622 return false; 2623 } 2624 2625 // Handle pointer-to-function, reference-to-function, and 2626 // pointer-to-member-function all in (roughly) the same way. 2627 if (// -- For a non-type template-parameter of type pointer to 2628 // function, only the function-to-pointer conversion (4.3) is 2629 // applied. If the template-argument represents a set of 2630 // overloaded functions (or a pointer to such), the matching 2631 // function is selected from the set (13.4). 2632 // In C++0x, any std::nullptr_t value can be converted. 2633 (ParamType->isPointerType() && 2634 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) || 2635 // -- For a non-type template-parameter of type reference to 2636 // function, no conversions apply. If the template-argument 2637 // represents a set of overloaded functions, the matching 2638 // function is selected from the set (13.4). 2639 (ParamType->isReferenceType() && 2640 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) || 2641 // -- For a non-type template-parameter of type pointer to 2642 // member function, no conversions apply. If the 2643 // template-argument represents a set of overloaded member 2644 // functions, the matching member function is selected from 2645 // the set (13.4). 2646 // Again, C++0x allows a std::nullptr_t value. 2647 (ParamType->isMemberPointerType() && 2648 ParamType->getAs<MemberPointerType>()->getPointeeType() 2649 ->isFunctionType())) { 2650 if (Context.hasSameUnqualifiedType(ArgType, 2651 ParamType.getNonReferenceType())) { 2652 // We don't have to do anything: the types already match. 2653 } else if (ArgType->isNullPtrType() && (ParamType->isPointerType() || 2654 ParamType->isMemberPointerType())) { 2655 ArgType = ParamType; 2656 if (ParamType->isMemberPointerType()) 2657 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer); 2658 else 2659 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast); 2660 } else if (ArgType->isFunctionType() && ParamType->isPointerType()) { 2661 ArgType = Context.getPointerType(ArgType); 2662 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay); 2663 } else if (FunctionDecl *Fn 2664 = ResolveAddressOfOverloadedFunction(Arg, ParamType, true)) { 2665 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin())) 2666 return true; 2667 2668 Arg = FixOverloadedFunctionReference(Arg, Fn); 2669 ArgType = Arg->getType(); 2670 if (ArgType->isFunctionType() && ParamType->isPointerType()) { 2671 ArgType = Context.getPointerType(Arg->getType()); 2672 ImpCastExprToType(Arg, ArgType, CastExpr::CK_FunctionToPointerDecay); 2673 } 2674 } 2675 2676 if (!Context.hasSameUnqualifiedType(ArgType, 2677 ParamType.getNonReferenceType())) { 2678 // We can't perform this conversion. 2679 Diag(Arg->getSourceRange().getBegin(), 2680 diag::err_template_arg_not_convertible) 2681 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange(); 2682 Diag(Param->getLocation(), diag::note_template_param_here); 2683 return true; 2684 } 2685 2686 if (ParamType->isMemberPointerType()) 2687 return CheckTemplateArgumentPointerToMember(Arg, Converted); 2688 2689 NamedDecl *Entity = 0; 2690 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity)) 2691 return true; 2692 2693 if (Entity) 2694 Entity = cast<NamedDecl>(Entity->getCanonicalDecl()); 2695 Converted = TemplateArgument(Entity); 2696 return false; 2697 } 2698 2699 if (ParamType->isPointerType()) { 2700 // -- for a non-type template-parameter of type pointer to 2701 // object, qualification conversions (4.4) and the 2702 // array-to-pointer conversion (4.2) are applied. 2703 // C++0x also allows a value of std::nullptr_t. 2704 assert(ParamType->getAs<PointerType>()->getPointeeType()->isObjectType() && 2705 "Only object pointers allowed here"); 2706 2707 if (ArgType->isNullPtrType()) { 2708 ArgType = ParamType; 2709 ImpCastExprToType(Arg, ParamType, CastExpr::CK_BitCast); 2710 } else if (ArgType->isArrayType()) { 2711 ArgType = Context.getArrayDecayedType(ArgType); 2712 ImpCastExprToType(Arg, ArgType, CastExpr::CK_ArrayToPointerDecay); 2713 } 2714 2715 if (IsQualificationConversion(ArgType, ParamType)) { 2716 ArgType = ParamType; 2717 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp); 2718 } 2719 2720 if (!Context.hasSameUnqualifiedType(ArgType, ParamType)) { 2721 // We can't perform this conversion. 2722 Diag(Arg->getSourceRange().getBegin(), 2723 diag::err_template_arg_not_convertible) 2724 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange(); 2725 Diag(Param->getLocation(), diag::note_template_param_here); 2726 return true; 2727 } 2728 2729 NamedDecl *Entity = 0; 2730 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity)) 2731 return true; 2732 2733 if (Entity) 2734 Entity = cast<NamedDecl>(Entity->getCanonicalDecl()); 2735 Converted = TemplateArgument(Entity); 2736 return false; 2737 } 2738 2739 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) { 2740 // -- For a non-type template-parameter of type reference to 2741 // object, no conversions apply. The type referred to by the 2742 // reference may be more cv-qualified than the (otherwise 2743 // identical) type of the template-argument. The 2744 // template-parameter is bound directly to the 2745 // template-argument, which must be an lvalue. 2746 assert(ParamRefType->getPointeeType()->isObjectType() && 2747 "Only object references allowed here"); 2748 2749 if (!Context.hasSameUnqualifiedType(ParamRefType->getPointeeType(), ArgType)) { 2750 Diag(Arg->getSourceRange().getBegin(), 2751 diag::err_template_arg_no_ref_bind) 2752 << InstantiatedParamType << Arg->getType() 2753 << Arg->getSourceRange(); 2754 Diag(Param->getLocation(), diag::note_template_param_here); 2755 return true; 2756 } 2757 2758 unsigned ParamQuals 2759 = Context.getCanonicalType(ParamType).getCVRQualifiers(); 2760 unsigned ArgQuals = Context.getCanonicalType(ArgType).getCVRQualifiers(); 2761 2762 if ((ParamQuals | ArgQuals) != ParamQuals) { 2763 Diag(Arg->getSourceRange().getBegin(), 2764 diag::err_template_arg_ref_bind_ignores_quals) 2765 << InstantiatedParamType << Arg->getType() 2766 << Arg->getSourceRange(); 2767 Diag(Param->getLocation(), diag::note_template_param_here); 2768 return true; 2769 } 2770 2771 NamedDecl *Entity = 0; 2772 if (CheckTemplateArgumentAddressOfObjectOrFunction(Arg, Entity)) 2773 return true; 2774 2775 Entity = cast<NamedDecl>(Entity->getCanonicalDecl()); 2776 Converted = TemplateArgument(Entity); 2777 return false; 2778 } 2779 2780 // -- For a non-type template-parameter of type pointer to data 2781 // member, qualification conversions (4.4) are applied. 2782 // C++0x allows std::nullptr_t values. 2783 assert(ParamType->isMemberPointerType() && "Only pointers to members remain"); 2784 2785 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) { 2786 // Types match exactly: nothing more to do here. 2787 } else if (ArgType->isNullPtrType()) { 2788 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NullToMemberPointer); 2789 } else if (IsQualificationConversion(ArgType, ParamType)) { 2790 ImpCastExprToType(Arg, ParamType, CastExpr::CK_NoOp); 2791 } else { 2792 // We can't perform this conversion. 2793 Diag(Arg->getSourceRange().getBegin(), 2794 diag::err_template_arg_not_convertible) 2795 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange(); 2796 Diag(Param->getLocation(), diag::note_template_param_here); 2797 return true; 2798 } 2799 2800 return CheckTemplateArgumentPointerToMember(Arg, Converted); 2801} 2802 2803/// \brief Check a template argument against its corresponding 2804/// template template parameter. 2805/// 2806/// This routine implements the semantics of C++ [temp.arg.template]. 2807/// It returns true if an error occurred, and false otherwise. 2808bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param, 2809 const TemplateArgumentLoc &Arg) { 2810 TemplateName Name = Arg.getArgument().getAsTemplate(); 2811 TemplateDecl *Template = Name.getAsTemplateDecl(); 2812 if (!Template) { 2813 // Any dependent template name is fine. 2814 assert(Name.isDependent() && "Non-dependent template isn't a declaration?"); 2815 return false; 2816 } 2817 2818 // C++ [temp.arg.template]p1: 2819 // A template-argument for a template template-parameter shall be 2820 // the name of a class template, expressed as id-expression. Only 2821 // primary class templates are considered when matching the 2822 // template template argument with the corresponding parameter; 2823 // partial specializations are not considered even if their 2824 // parameter lists match that of the template template parameter. 2825 // 2826 // Note that we also allow template template parameters here, which 2827 // will happen when we are dealing with, e.g., class template 2828 // partial specializations. 2829 if (!isa<ClassTemplateDecl>(Template) && 2830 !isa<TemplateTemplateParmDecl>(Template)) { 2831 assert(isa<FunctionTemplateDecl>(Template) && 2832 "Only function templates are possible here"); 2833 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template); 2834 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func) 2835 << Template; 2836 } 2837 2838 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(), 2839 Param->getTemplateParameters(), 2840 true, 2841 TPL_TemplateTemplateArgumentMatch, 2842 Arg.getLocation()); 2843} 2844 2845/// \brief Determine whether the given template parameter lists are 2846/// equivalent. 2847/// 2848/// \param New The new template parameter list, typically written in the 2849/// source code as part of a new template declaration. 2850/// 2851/// \param Old The old template parameter list, typically found via 2852/// name lookup of the template declared with this template parameter 2853/// list. 2854/// 2855/// \param Complain If true, this routine will produce a diagnostic if 2856/// the template parameter lists are not equivalent. 2857/// 2858/// \param Kind describes how we are to match the template parameter lists. 2859/// 2860/// \param TemplateArgLoc If this source location is valid, then we 2861/// are actually checking the template parameter list of a template 2862/// argument (New) against the template parameter list of its 2863/// corresponding template template parameter (Old). We produce 2864/// slightly different diagnostics in this scenario. 2865/// 2866/// \returns True if the template parameter lists are equal, false 2867/// otherwise. 2868bool 2869Sema::TemplateParameterListsAreEqual(TemplateParameterList *New, 2870 TemplateParameterList *Old, 2871 bool Complain, 2872 TemplateParameterListEqualKind Kind, 2873 SourceLocation TemplateArgLoc) { 2874 if (Old->size() != New->size()) { 2875 if (Complain) { 2876 unsigned NextDiag = diag::err_template_param_list_different_arity; 2877 if (TemplateArgLoc.isValid()) { 2878 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch); 2879 NextDiag = diag::note_template_param_list_different_arity; 2880 } 2881 Diag(New->getTemplateLoc(), NextDiag) 2882 << (New->size() > Old->size()) 2883 << (Kind != TPL_TemplateMatch) 2884 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc()); 2885 Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration) 2886 << (Kind != TPL_TemplateMatch) 2887 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc()); 2888 } 2889 2890 return false; 2891 } 2892 2893 for (TemplateParameterList::iterator OldParm = Old->begin(), 2894 OldParmEnd = Old->end(), NewParm = New->begin(); 2895 OldParm != OldParmEnd; ++OldParm, ++NewParm) { 2896 if ((*OldParm)->getKind() != (*NewParm)->getKind()) { 2897 if (Complain) { 2898 unsigned NextDiag = diag::err_template_param_different_kind; 2899 if (TemplateArgLoc.isValid()) { 2900 Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch); 2901 NextDiag = diag::note_template_param_different_kind; 2902 } 2903 Diag((*NewParm)->getLocation(), NextDiag) 2904 << (Kind != TPL_TemplateMatch); 2905 Diag((*OldParm)->getLocation(), diag::note_template_prev_declaration) 2906 << (Kind != TPL_TemplateMatch); 2907 } 2908 return false; 2909 } 2910 2911 if (isa<TemplateTypeParmDecl>(*OldParm)) { 2912 // Okay; all template type parameters are equivalent (since we 2913 // know we're at the same index). 2914 } else if (NonTypeTemplateParmDecl *OldNTTP 2915 = dyn_cast<NonTypeTemplateParmDecl>(*OldParm)) { 2916 // The types of non-type template parameters must agree. 2917 NonTypeTemplateParmDecl *NewNTTP 2918 = cast<NonTypeTemplateParmDecl>(*NewParm); 2919 2920 // If we are matching a template template argument to a template 2921 // template parameter and one of the non-type template parameter types 2922 // is dependent, then we must wait until template instantiation time 2923 // to actually compare the arguments. 2924 if (Kind == TPL_TemplateTemplateArgumentMatch && 2925 (OldNTTP->getType()->isDependentType() || 2926 NewNTTP->getType()->isDependentType())) 2927 continue; 2928 2929 if (Context.getCanonicalType(OldNTTP->getType()) != 2930 Context.getCanonicalType(NewNTTP->getType())) { 2931 if (Complain) { 2932 unsigned NextDiag = diag::err_template_nontype_parm_different_type; 2933 if (TemplateArgLoc.isValid()) { 2934 Diag(TemplateArgLoc, 2935 diag::err_template_arg_template_params_mismatch); 2936 NextDiag = diag::note_template_nontype_parm_different_type; 2937 } 2938 Diag(NewNTTP->getLocation(), NextDiag) 2939 << NewNTTP->getType() 2940 << (Kind != TPL_TemplateMatch); 2941 Diag(OldNTTP->getLocation(), 2942 diag::note_template_nontype_parm_prev_declaration) 2943 << OldNTTP->getType(); 2944 } 2945 return false; 2946 } 2947 } else { 2948 // The template parameter lists of template template 2949 // parameters must agree. 2950 assert(isa<TemplateTemplateParmDecl>(*OldParm) && 2951 "Only template template parameters handled here"); 2952 TemplateTemplateParmDecl *OldTTP 2953 = cast<TemplateTemplateParmDecl>(*OldParm); 2954 TemplateTemplateParmDecl *NewTTP 2955 = cast<TemplateTemplateParmDecl>(*NewParm); 2956 if (!TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(), 2957 OldTTP->getTemplateParameters(), 2958 Complain, 2959 (Kind == TPL_TemplateMatch? TPL_TemplateTemplateParmMatch : Kind), 2960 TemplateArgLoc)) 2961 return false; 2962 } 2963 } 2964 2965 return true; 2966} 2967 2968/// \brief Check whether a template can be declared within this scope. 2969/// 2970/// If the template declaration is valid in this scope, returns 2971/// false. Otherwise, issues a diagnostic and returns true. 2972bool 2973Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) { 2974 // Find the nearest enclosing declaration scope. 2975 while ((S->getFlags() & Scope::DeclScope) == 0 || 2976 (S->getFlags() & Scope::TemplateParamScope) != 0) 2977 S = S->getParent(); 2978 2979 // C++ [temp]p2: 2980 // A template-declaration can appear only as a namespace scope or 2981 // class scope declaration. 2982 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity()); 2983 if (Ctx && isa<LinkageSpecDecl>(Ctx) && 2984 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx) 2985 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage) 2986 << TemplateParams->getSourceRange(); 2987 2988 while (Ctx && isa<LinkageSpecDecl>(Ctx)) 2989 Ctx = Ctx->getParent(); 2990 2991 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord())) 2992 return false; 2993 2994 return Diag(TemplateParams->getTemplateLoc(), 2995 diag::err_template_outside_namespace_or_class_scope) 2996 << TemplateParams->getSourceRange(); 2997} 2998 2999/// \brief Determine what kind of template specialization the given declaration 3000/// is. 3001static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) { 3002 if (!D) 3003 return TSK_Undeclared; 3004 3005 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) 3006 return Record->getTemplateSpecializationKind(); 3007 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) 3008 return Function->getTemplateSpecializationKind(); 3009 if (VarDecl *Var = dyn_cast<VarDecl>(D)) 3010 return Var->getTemplateSpecializationKind(); 3011 3012 return TSK_Undeclared; 3013} 3014 3015/// \brief Check whether a specialization is well-formed in the current 3016/// context. 3017/// 3018/// This routine determines whether a template specialization can be declared 3019/// in the current context (C++ [temp.expl.spec]p2). 3020/// 3021/// \param S the semantic analysis object for which this check is being 3022/// performed. 3023/// 3024/// \param Specialized the entity being specialized or instantiated, which 3025/// may be a kind of template (class template, function template, etc.) or 3026/// a member of a class template (member function, static data member, 3027/// member class). 3028/// 3029/// \param PrevDecl the previous declaration of this entity, if any. 3030/// 3031/// \param Loc the location of the explicit specialization or instantiation of 3032/// this entity. 3033/// 3034/// \param IsPartialSpecialization whether this is a partial specialization of 3035/// a class template. 3036/// 3037/// \returns true if there was an error that we cannot recover from, false 3038/// otherwise. 3039static bool CheckTemplateSpecializationScope(Sema &S, 3040 NamedDecl *Specialized, 3041 NamedDecl *PrevDecl, 3042 SourceLocation Loc, 3043 bool IsPartialSpecialization) { 3044 // Keep these "kind" numbers in sync with the %select statements in the 3045 // various diagnostics emitted by this routine. 3046 int EntityKind = 0; 3047 bool isTemplateSpecialization = false; 3048 if (isa<ClassTemplateDecl>(Specialized)) { 3049 EntityKind = IsPartialSpecialization? 1 : 0; 3050 isTemplateSpecialization = true; 3051 } else if (isa<FunctionTemplateDecl>(Specialized)) { 3052 EntityKind = 2; 3053 isTemplateSpecialization = true; 3054 } else if (isa<CXXMethodDecl>(Specialized)) 3055 EntityKind = 3; 3056 else if (isa<VarDecl>(Specialized)) 3057 EntityKind = 4; 3058 else if (isa<RecordDecl>(Specialized)) 3059 EntityKind = 5; 3060 else { 3061 S.Diag(Loc, diag::err_template_spec_unknown_kind); 3062 S.Diag(Specialized->getLocation(), diag::note_specialized_entity); 3063 return true; 3064 } 3065 3066 // C++ [temp.expl.spec]p2: 3067 // An explicit specialization shall be declared in the namespace 3068 // of which the template is a member, or, for member templates, in 3069 // the namespace of which the enclosing class or enclosing class 3070 // template is a member. An explicit specialization of a member 3071 // function, member class or static data member of a class 3072 // template shall be declared in the namespace of which the class 3073 // template is a member. Such a declaration may also be a 3074 // definition. If the declaration is not a definition, the 3075 // specialization may be defined later in the name- space in which 3076 // the explicit specialization was declared, or in a namespace 3077 // that encloses the one in which the explicit specialization was 3078 // declared. 3079 if (S.CurContext->getLookupContext()->isFunctionOrMethod()) { 3080 S.Diag(Loc, diag::err_template_spec_decl_function_scope) 3081 << Specialized; 3082 return true; 3083 } 3084 3085 if (S.CurContext->isRecord() && !IsPartialSpecialization) { 3086 S.Diag(Loc, diag::err_template_spec_decl_class_scope) 3087 << Specialized; 3088 return true; 3089 } 3090 3091 // C++ [temp.class.spec]p6: 3092 // A class template partial specialization may be declared or redeclared 3093 // in any namespace scope in which its definition may be defined (14.5.1 3094 // and 14.5.2). 3095 bool ComplainedAboutScope = false; 3096 DeclContext *SpecializedContext 3097 = Specialized->getDeclContext()->getEnclosingNamespaceContext(); 3098 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext(); 3099 if ((!PrevDecl || 3100 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared || 3101 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){ 3102 // There is no prior declaration of this entity, so this 3103 // specialization must be in the same context as the template 3104 // itself. 3105 if (!DC->Equals(SpecializedContext)) { 3106 if (isa<TranslationUnitDecl>(SpecializedContext)) 3107 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global) 3108 << EntityKind << Specialized; 3109 else if (isa<NamespaceDecl>(SpecializedContext)) 3110 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope) 3111 << EntityKind << Specialized 3112 << cast<NamedDecl>(SpecializedContext); 3113 3114 S.Diag(Specialized->getLocation(), diag::note_specialized_entity); 3115 ComplainedAboutScope = true; 3116 } 3117 } 3118 3119 // Make sure that this redeclaration (or definition) occurs in an enclosing 3120 // namespace. 3121 // Note that HandleDeclarator() performs this check for explicit 3122 // specializations of function templates, static data members, and member 3123 // functions, so we skip the check here for those kinds of entities. 3124 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though. 3125 // Should we refactor that check, so that it occurs later? 3126 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) && 3127 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) || 3128 isa<FunctionDecl>(Specialized))) { 3129 if (isa<TranslationUnitDecl>(SpecializedContext)) 3130 S.Diag(Loc, diag::err_template_spec_redecl_global_scope) 3131 << EntityKind << Specialized; 3132 else if (isa<NamespaceDecl>(SpecializedContext)) 3133 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope) 3134 << EntityKind << Specialized 3135 << cast<NamedDecl>(SpecializedContext); 3136 3137 S.Diag(Specialized->getLocation(), diag::note_specialized_entity); 3138 } 3139 3140 // FIXME: check for specialization-after-instantiation errors and such. 3141 3142 return false; 3143} 3144 3145/// \brief Check the non-type template arguments of a class template 3146/// partial specialization according to C++ [temp.class.spec]p9. 3147/// 3148/// \param TemplateParams the template parameters of the primary class 3149/// template. 3150/// 3151/// \param TemplateArg the template arguments of the class template 3152/// partial specialization. 3153/// 3154/// \param MirrorsPrimaryTemplate will be set true if the class 3155/// template partial specialization arguments are identical to the 3156/// implicit template arguments of the primary template. This is not 3157/// necessarily an error (C++0x), and it is left to the caller to diagnose 3158/// this condition when it is an error. 3159/// 3160/// \returns true if there was an error, false otherwise. 3161bool Sema::CheckClassTemplatePartialSpecializationArgs( 3162 TemplateParameterList *TemplateParams, 3163 const TemplateArgumentListBuilder &TemplateArgs, 3164 bool &MirrorsPrimaryTemplate) { 3165 // FIXME: the interface to this function will have to change to 3166 // accommodate variadic templates. 3167 MirrorsPrimaryTemplate = true; 3168 3169 const TemplateArgument *ArgList = TemplateArgs.getFlatArguments(); 3170 3171 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) { 3172 // Determine whether the template argument list of the partial 3173 // specialization is identical to the implicit argument list of 3174 // the primary template. The caller may need to diagnostic this as 3175 // an error per C++ [temp.class.spec]p9b3. 3176 if (MirrorsPrimaryTemplate) { 3177 if (TemplateTypeParmDecl *TTP 3178 = dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(I))) { 3179 if (Context.getCanonicalType(Context.getTypeDeclType(TTP)) != 3180 Context.getCanonicalType(ArgList[I].getAsType())) 3181 MirrorsPrimaryTemplate = false; 3182 } else if (TemplateTemplateParmDecl *TTP 3183 = dyn_cast<TemplateTemplateParmDecl>( 3184 TemplateParams->getParam(I))) { 3185 TemplateName Name = ArgList[I].getAsTemplate(); 3186 TemplateTemplateParmDecl *ArgDecl 3187 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()); 3188 if (!ArgDecl || 3189 ArgDecl->getIndex() != TTP->getIndex() || 3190 ArgDecl->getDepth() != TTP->getDepth()) 3191 MirrorsPrimaryTemplate = false; 3192 } 3193 } 3194 3195 NonTypeTemplateParmDecl *Param 3196 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I)); 3197 if (!Param) { 3198 continue; 3199 } 3200 3201 Expr *ArgExpr = ArgList[I].getAsExpr(); 3202 if (!ArgExpr) { 3203 MirrorsPrimaryTemplate = false; 3204 continue; 3205 } 3206 3207 // C++ [temp.class.spec]p8: 3208 // A non-type argument is non-specialized if it is the name of a 3209 // non-type parameter. All other non-type arguments are 3210 // specialized. 3211 // 3212 // Below, we check the two conditions that only apply to 3213 // specialized non-type arguments, so skip any non-specialized 3214 // arguments. 3215 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr)) 3216 if (NonTypeTemplateParmDecl *NTTP 3217 = dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl())) { 3218 if (MirrorsPrimaryTemplate && 3219 (Param->getIndex() != NTTP->getIndex() || 3220 Param->getDepth() != NTTP->getDepth())) 3221 MirrorsPrimaryTemplate = false; 3222 3223 continue; 3224 } 3225 3226 // C++ [temp.class.spec]p9: 3227 // Within the argument list of a class template partial 3228 // specialization, the following restrictions apply: 3229 // -- A partially specialized non-type argument expression 3230 // shall not involve a template parameter of the partial 3231 // specialization except when the argument expression is a 3232 // simple identifier. 3233 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) { 3234 Diag(ArgExpr->getLocStart(), 3235 diag::err_dependent_non_type_arg_in_partial_spec) 3236 << ArgExpr->getSourceRange(); 3237 return true; 3238 } 3239 3240 // -- The type of a template parameter corresponding to a 3241 // specialized non-type argument shall not be dependent on a 3242 // parameter of the specialization. 3243 if (Param->getType()->isDependentType()) { 3244 Diag(ArgExpr->getLocStart(), 3245 diag::err_dependent_typed_non_type_arg_in_partial_spec) 3246 << Param->getType() 3247 << ArgExpr->getSourceRange(); 3248 Diag(Param->getLocation(), diag::note_template_param_here); 3249 return true; 3250 } 3251 3252 MirrorsPrimaryTemplate = false; 3253 } 3254 3255 return false; 3256} 3257 3258Sema::DeclResult 3259Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, 3260 TagUseKind TUK, 3261 SourceLocation KWLoc, 3262 const CXXScopeSpec &SS, 3263 TemplateTy TemplateD, 3264 SourceLocation TemplateNameLoc, 3265 SourceLocation LAngleLoc, 3266 ASTTemplateArgsPtr TemplateArgsIn, 3267 SourceLocation RAngleLoc, 3268 AttributeList *Attr, 3269 MultiTemplateParamsArg TemplateParameterLists) { 3270 assert(TUK != TUK_Reference && "References are not specializations"); 3271 3272 // Find the class template we're specializing 3273 TemplateName Name = TemplateD.getAsVal<TemplateName>(); 3274 ClassTemplateDecl *ClassTemplate 3275 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl()); 3276 3277 if (!ClassTemplate) { 3278 Diag(TemplateNameLoc, diag::err_not_class_template_specialization) 3279 << (Name.getAsTemplateDecl() && 3280 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())); 3281 return true; 3282 } 3283 3284 bool isExplicitSpecialization = false; 3285 bool isPartialSpecialization = false; 3286 3287 // Check the validity of the template headers that introduce this 3288 // template. 3289 // FIXME: We probably shouldn't complain about these headers for 3290 // friend declarations. 3291 TemplateParameterList *TemplateParams 3292 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS, 3293 (TemplateParameterList**)TemplateParameterLists.get(), 3294 TemplateParameterLists.size(), 3295 isExplicitSpecialization); 3296 if (TemplateParams && TemplateParams->size() > 0) { 3297 isPartialSpecialization = true; 3298 3299 // C++ [temp.class.spec]p10: 3300 // The template parameter list of a specialization shall not 3301 // contain default template argument values. 3302 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) { 3303 Decl *Param = TemplateParams->getParam(I); 3304 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) { 3305 if (TTP->hasDefaultArgument()) { 3306 Diag(TTP->getDefaultArgumentLoc(), 3307 diag::err_default_arg_in_partial_spec); 3308 TTP->removeDefaultArgument(); 3309 } 3310 } else if (NonTypeTemplateParmDecl *NTTP 3311 = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 3312 if (Expr *DefArg = NTTP->getDefaultArgument()) { 3313 Diag(NTTP->getDefaultArgumentLoc(), 3314 diag::err_default_arg_in_partial_spec) 3315 << DefArg->getSourceRange(); 3316 NTTP->setDefaultArgument(0); 3317 DefArg->Destroy(Context); 3318 } 3319 } else { 3320 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param); 3321 if (TTP->hasDefaultArgument()) { 3322 Diag(TTP->getDefaultArgument().getLocation(), 3323 diag::err_default_arg_in_partial_spec) 3324 << TTP->getDefaultArgument().getSourceRange(); 3325 TTP->setDefaultArgument(TemplateArgumentLoc()); 3326 } 3327 } 3328 } 3329 } else if (TemplateParams) { 3330 if (TUK == TUK_Friend) 3331 Diag(KWLoc, diag::err_template_spec_friend) 3332 << CodeModificationHint::CreateRemoval( 3333 SourceRange(TemplateParams->getTemplateLoc(), 3334 TemplateParams->getRAngleLoc())) 3335 << SourceRange(LAngleLoc, RAngleLoc); 3336 else 3337 isExplicitSpecialization = true; 3338 } else if (TUK != TUK_Friend) { 3339 Diag(KWLoc, diag::err_template_spec_needs_header) 3340 << CodeModificationHint::CreateInsertion(KWLoc, "template<> "); 3341 isExplicitSpecialization = true; 3342 } 3343 3344 // Check that the specialization uses the same tag kind as the 3345 // original template. 3346 TagDecl::TagKind Kind; 3347 switch (TagSpec) { 3348 default: assert(0 && "Unknown tag type!"); 3349 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break; 3350 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break; 3351 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break; 3352 } 3353 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), 3354 Kind, KWLoc, 3355 *ClassTemplate->getIdentifier())) { 3356 Diag(KWLoc, diag::err_use_with_wrong_tag) 3357 << ClassTemplate 3358 << CodeModificationHint::CreateReplacement(KWLoc, 3359 ClassTemplate->getTemplatedDecl()->getKindName()); 3360 Diag(ClassTemplate->getTemplatedDecl()->getLocation(), 3361 diag::note_previous_use); 3362 Kind = ClassTemplate->getTemplatedDecl()->getTagKind(); 3363 } 3364 3365 // Translate the parser's template argument list in our AST format. 3366 TemplateArgumentListInfo TemplateArgs; 3367 TemplateArgs.setLAngleLoc(LAngleLoc); 3368 TemplateArgs.setRAngleLoc(RAngleLoc); 3369 translateTemplateArguments(TemplateArgsIn, TemplateArgs); 3370 3371 // Check that the template argument list is well-formed for this 3372 // template. 3373 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(), 3374 TemplateArgs.size()); 3375 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, 3376 TemplateArgs, false, Converted)) 3377 return true; 3378 3379 assert((Converted.structuredSize() == 3380 ClassTemplate->getTemplateParameters()->size()) && 3381 "Converted template argument list is too short!"); 3382 3383 // Find the class template (partial) specialization declaration that 3384 // corresponds to these arguments. 3385 llvm::FoldingSetNodeID ID; 3386 if (isPartialSpecialization) { 3387 bool MirrorsPrimaryTemplate; 3388 if (CheckClassTemplatePartialSpecializationArgs( 3389 ClassTemplate->getTemplateParameters(), 3390 Converted, MirrorsPrimaryTemplate)) 3391 return true; 3392 3393 if (MirrorsPrimaryTemplate) { 3394 // C++ [temp.class.spec]p9b3: 3395 // 3396 // -- The argument list of the specialization shall not be identical 3397 // to the implicit argument list of the primary template. 3398 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template) 3399 << (TUK == TUK_Definition) 3400 << CodeModificationHint::CreateRemoval(SourceRange(LAngleLoc, 3401 RAngleLoc)); 3402 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS, 3403 ClassTemplate->getIdentifier(), 3404 TemplateNameLoc, 3405 Attr, 3406 TemplateParams, 3407 AS_none); 3408 } 3409 3410 // FIXME: Diagnose friend partial specializations 3411 3412 // FIXME: Template parameter list matters, too 3413 ClassTemplatePartialSpecializationDecl::Profile(ID, 3414 Converted.getFlatArguments(), 3415 Converted.flatSize(), 3416 Context); 3417 } else 3418 ClassTemplateSpecializationDecl::Profile(ID, 3419 Converted.getFlatArguments(), 3420 Converted.flatSize(), 3421 Context); 3422 void *InsertPos = 0; 3423 ClassTemplateSpecializationDecl *PrevDecl = 0; 3424 3425 if (isPartialSpecialization) 3426 PrevDecl 3427 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID, 3428 InsertPos); 3429 else 3430 PrevDecl 3431 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos); 3432 3433 ClassTemplateSpecializationDecl *Specialization = 0; 3434 3435 // Check whether we can declare a class template specialization in 3436 // the current scope. 3437 if (TUK != TUK_Friend && 3438 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl, 3439 TemplateNameLoc, 3440 isPartialSpecialization)) 3441 return true; 3442 3443 // The canonical type 3444 QualType CanonType; 3445 if (PrevDecl && 3446 (PrevDecl->getSpecializationKind() == TSK_Undeclared || 3447 TUK == TUK_Friend)) { 3448 // Since the only prior class template specialization with these 3449 // arguments was referenced but not declared, or we're only 3450 // referencing this specialization as a friend, reuse that 3451 // declaration node as our own, updating its source location to 3452 // reflect our new declaration. 3453 Specialization = PrevDecl; 3454 Specialization->setLocation(TemplateNameLoc); 3455 PrevDecl = 0; 3456 CanonType = Context.getTypeDeclType(Specialization); 3457 } else if (isPartialSpecialization) { 3458 // Build the canonical type that describes the converted template 3459 // arguments of the class template partial specialization. 3460 CanonType = Context.getTemplateSpecializationType( 3461 TemplateName(ClassTemplate), 3462 Converted.getFlatArguments(), 3463 Converted.flatSize()); 3464 3465 // Create a new class template partial specialization declaration node. 3466 ClassTemplatePartialSpecializationDecl *PrevPartial 3467 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl); 3468 ClassTemplatePartialSpecializationDecl *Partial 3469 = ClassTemplatePartialSpecializationDecl::Create(Context, 3470 ClassTemplate->getDeclContext(), 3471 TemplateNameLoc, 3472 TemplateParams, 3473 ClassTemplate, 3474 Converted, 3475 TemplateArgs, 3476 PrevPartial); 3477 3478 if (PrevPartial) { 3479 ClassTemplate->getPartialSpecializations().RemoveNode(PrevPartial); 3480 ClassTemplate->getPartialSpecializations().GetOrInsertNode(Partial); 3481 } else { 3482 ClassTemplate->getPartialSpecializations().InsertNode(Partial, InsertPos); 3483 } 3484 Specialization = Partial; 3485 3486 // If we are providing an explicit specialization of a member class 3487 // template specialization, make a note of that. 3488 if (PrevPartial && PrevPartial->getInstantiatedFromMember()) 3489 PrevPartial->setMemberSpecialization(); 3490 3491 // Check that all of the template parameters of the class template 3492 // partial specialization are deducible from the template 3493 // arguments. If not, this class template partial specialization 3494 // will never be used. 3495 llvm::SmallVector<bool, 8> DeducibleParams; 3496 DeducibleParams.resize(TemplateParams->size()); 3497 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true, 3498 TemplateParams->getDepth(), 3499 DeducibleParams); 3500 unsigned NumNonDeducible = 0; 3501 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) 3502 if (!DeducibleParams[I]) 3503 ++NumNonDeducible; 3504 3505 if (NumNonDeducible) { 3506 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible) 3507 << (NumNonDeducible > 1) 3508 << SourceRange(TemplateNameLoc, RAngleLoc); 3509 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) { 3510 if (!DeducibleParams[I]) { 3511 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I)); 3512 if (Param->getDeclName()) 3513 Diag(Param->getLocation(), 3514 diag::note_partial_spec_unused_parameter) 3515 << Param->getDeclName(); 3516 else 3517 Diag(Param->getLocation(), 3518 diag::note_partial_spec_unused_parameter) 3519 << std::string("<anonymous>"); 3520 } 3521 } 3522 } 3523 } else { 3524 // Create a new class template specialization declaration node for 3525 // this explicit specialization or friend declaration. 3526 Specialization 3527 = ClassTemplateSpecializationDecl::Create(Context, 3528 ClassTemplate->getDeclContext(), 3529 TemplateNameLoc, 3530 ClassTemplate, 3531 Converted, 3532 PrevDecl); 3533 3534 if (PrevDecl) { 3535 ClassTemplate->getSpecializations().RemoveNode(PrevDecl); 3536 ClassTemplate->getSpecializations().GetOrInsertNode(Specialization); 3537 } else { 3538 ClassTemplate->getSpecializations().InsertNode(Specialization, 3539 InsertPos); 3540 } 3541 3542 CanonType = Context.getTypeDeclType(Specialization); 3543 } 3544 3545 // C++ [temp.expl.spec]p6: 3546 // If a template, a member template or the member of a class template is 3547 // explicitly specialized then that specialization shall be declared 3548 // before the first use of that specialization that would cause an implicit 3549 // instantiation to take place, in every translation unit in which such a 3550 // use occurs; no diagnostic is required. 3551 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) { 3552 SourceRange Range(TemplateNameLoc, RAngleLoc); 3553 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation) 3554 << Context.getTypeDeclType(Specialization) << Range; 3555 3556 Diag(PrevDecl->getPointOfInstantiation(), 3557 diag::note_instantiation_required_here) 3558 << (PrevDecl->getTemplateSpecializationKind() 3559 != TSK_ImplicitInstantiation); 3560 return true; 3561 } 3562 3563 // If this is not a friend, note that this is an explicit specialization. 3564 if (TUK != TUK_Friend) 3565 Specialization->setSpecializationKind(TSK_ExplicitSpecialization); 3566 3567 // Check that this isn't a redefinition of this specialization. 3568 if (TUK == TUK_Definition) { 3569 if (RecordDecl *Def = Specialization->getDefinition(Context)) { 3570 SourceRange Range(TemplateNameLoc, RAngleLoc); 3571 Diag(TemplateNameLoc, diag::err_redefinition) 3572 << Context.getTypeDeclType(Specialization) << Range; 3573 Diag(Def->getLocation(), diag::note_previous_definition); 3574 Specialization->setInvalidDecl(); 3575 return true; 3576 } 3577 } 3578 3579 // Build the fully-sugared type for this class template 3580 // specialization as the user wrote in the specialization 3581 // itself. This means that we'll pretty-print the type retrieved 3582 // from the specialization's declaration the way that the user 3583 // actually wrote the specialization, rather than formatting the 3584 // name based on the "canonical" representation used to store the 3585 // template arguments in the specialization. 3586 QualType WrittenTy 3587 = Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType); 3588 if (TUK != TUK_Friend) 3589 Specialization->setTypeAsWritten(WrittenTy); 3590 TemplateArgsIn.release(); 3591 3592 // C++ [temp.expl.spec]p9: 3593 // A template explicit specialization is in the scope of the 3594 // namespace in which the template was defined. 3595 // 3596 // We actually implement this paragraph where we set the semantic 3597 // context (in the creation of the ClassTemplateSpecializationDecl), 3598 // but we also maintain the lexical context where the actual 3599 // definition occurs. 3600 Specialization->setLexicalDeclContext(CurContext); 3601 3602 // We may be starting the definition of this specialization. 3603 if (TUK == TUK_Definition) 3604 Specialization->startDefinition(); 3605 3606 if (TUK == TUK_Friend) { 3607 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, 3608 TemplateNameLoc, 3609 WrittenTy.getTypePtr(), 3610 /*FIXME:*/KWLoc); 3611 Friend->setAccess(AS_public); 3612 CurContext->addDecl(Friend); 3613 } else { 3614 // Add the specialization into its lexical context, so that it can 3615 // be seen when iterating through the list of declarations in that 3616 // context. However, specializations are not found by name lookup. 3617 CurContext->addDecl(Specialization); 3618 } 3619 return DeclPtrTy::make(Specialization); 3620} 3621 3622Sema::DeclPtrTy 3623Sema::ActOnTemplateDeclarator(Scope *S, 3624 MultiTemplateParamsArg TemplateParameterLists, 3625 Declarator &D) { 3626 return HandleDeclarator(S, D, move(TemplateParameterLists), false); 3627} 3628 3629Sema::DeclPtrTy 3630Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope, 3631 MultiTemplateParamsArg TemplateParameterLists, 3632 Declarator &D) { 3633 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 3634 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function && 3635 "Not a function declarator!"); 3636 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 3637 3638 if (FTI.hasPrototype) { 3639 // FIXME: Diagnose arguments without names in C. 3640 } 3641 3642 Scope *ParentScope = FnBodyScope->getParent(); 3643 3644 DeclPtrTy DP = HandleDeclarator(ParentScope, D, 3645 move(TemplateParameterLists), 3646 /*IsFunctionDefinition=*/true); 3647 if (FunctionTemplateDecl *FunctionTemplate 3648 = dyn_cast_or_null<FunctionTemplateDecl>(DP.getAs<Decl>())) 3649 return ActOnStartOfFunctionDef(FnBodyScope, 3650 DeclPtrTy::make(FunctionTemplate->getTemplatedDecl())); 3651 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP.getAs<Decl>())) 3652 return ActOnStartOfFunctionDef(FnBodyScope, DeclPtrTy::make(Function)); 3653 return DeclPtrTy(); 3654} 3655 3656/// \brief Diagnose cases where we have an explicit template specialization 3657/// before/after an explicit template instantiation, producing diagnostics 3658/// for those cases where they are required and determining whether the 3659/// new specialization/instantiation will have any effect. 3660/// 3661/// \param NewLoc the location of the new explicit specialization or 3662/// instantiation. 3663/// 3664/// \param NewTSK the kind of the new explicit specialization or instantiation. 3665/// 3666/// \param PrevDecl the previous declaration of the entity. 3667/// 3668/// \param PrevTSK the kind of the old explicit specialization or instantiatin. 3669/// 3670/// \param PrevPointOfInstantiation if valid, indicates where the previus 3671/// declaration was instantiated (either implicitly or explicitly). 3672/// 3673/// \param SuppressNew will be set to true to indicate that the new 3674/// specialization or instantiation has no effect and should be ignored. 3675/// 3676/// \returns true if there was an error that should prevent the introduction of 3677/// the new declaration into the AST, false otherwise. 3678bool 3679Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, 3680 TemplateSpecializationKind NewTSK, 3681 NamedDecl *PrevDecl, 3682 TemplateSpecializationKind PrevTSK, 3683 SourceLocation PrevPointOfInstantiation, 3684 bool &SuppressNew) { 3685 SuppressNew = false; 3686 3687 switch (NewTSK) { 3688 case TSK_Undeclared: 3689 case TSK_ImplicitInstantiation: 3690 assert(false && "Don't check implicit instantiations here"); 3691 return false; 3692 3693 case TSK_ExplicitSpecialization: 3694 switch (PrevTSK) { 3695 case TSK_Undeclared: 3696 case TSK_ExplicitSpecialization: 3697 // Okay, we're just specializing something that is either already 3698 // explicitly specialized or has merely been mentioned without any 3699 // instantiation. 3700 return false; 3701 3702 case TSK_ImplicitInstantiation: 3703 if (PrevPointOfInstantiation.isInvalid()) { 3704 // The declaration itself has not actually been instantiated, so it is 3705 // still okay to specialize it. 3706 return false; 3707 } 3708 // Fall through 3709 3710 case TSK_ExplicitInstantiationDeclaration: 3711 case TSK_ExplicitInstantiationDefinition: 3712 assert((PrevTSK == TSK_ImplicitInstantiation || 3713 PrevPointOfInstantiation.isValid()) && 3714 "Explicit instantiation without point of instantiation?"); 3715 3716 // C++ [temp.expl.spec]p6: 3717 // If a template, a member template or the member of a class template 3718 // is explicitly specialized then that specialization shall be declared 3719 // before the first use of that specialization that would cause an 3720 // implicit instantiation to take place, in every translation unit in 3721 // which such a use occurs; no diagnostic is required. 3722 Diag(NewLoc, diag::err_specialization_after_instantiation) 3723 << PrevDecl; 3724 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here) 3725 << (PrevTSK != TSK_ImplicitInstantiation); 3726 3727 return true; 3728 } 3729 break; 3730 3731 case TSK_ExplicitInstantiationDeclaration: 3732 switch (PrevTSK) { 3733 case TSK_ExplicitInstantiationDeclaration: 3734 // This explicit instantiation declaration is redundant (that's okay). 3735 SuppressNew = true; 3736 return false; 3737 3738 case TSK_Undeclared: 3739 case TSK_ImplicitInstantiation: 3740 // We're explicitly instantiating something that may have already been 3741 // implicitly instantiated; that's fine. 3742 return false; 3743 3744 case TSK_ExplicitSpecialization: 3745 // C++0x [temp.explicit]p4: 3746 // For a given set of template parameters, if an explicit instantiation 3747 // of a template appears after a declaration of an explicit 3748 // specialization for that template, the explicit instantiation has no 3749 // effect. 3750 return false; 3751 3752 case TSK_ExplicitInstantiationDefinition: 3753 // C++0x [temp.explicit]p10: 3754 // If an entity is the subject of both an explicit instantiation 3755 // declaration and an explicit instantiation definition in the same 3756 // translation unit, the definition shall follow the declaration. 3757 Diag(NewLoc, 3758 diag::err_explicit_instantiation_declaration_after_definition); 3759 Diag(PrevPointOfInstantiation, 3760 diag::note_explicit_instantiation_definition_here); 3761 assert(PrevPointOfInstantiation.isValid() && 3762 "Explicit instantiation without point of instantiation?"); 3763 SuppressNew = true; 3764 return false; 3765 } 3766 break; 3767 3768 case TSK_ExplicitInstantiationDefinition: 3769 switch (PrevTSK) { 3770 case TSK_Undeclared: 3771 case TSK_ImplicitInstantiation: 3772 // We're explicitly instantiating something that may have already been 3773 // implicitly instantiated; that's fine. 3774 return false; 3775 3776 case TSK_ExplicitSpecialization: 3777 // C++ DR 259, C++0x [temp.explicit]p4: 3778 // For a given set of template parameters, if an explicit 3779 // instantiation of a template appears after a declaration of 3780 // an explicit specialization for that template, the explicit 3781 // instantiation has no effect. 3782 // 3783 // In C++98/03 mode, we only give an extension warning here, because it 3784 // is not not harmful to try to explicitly instantiate something that 3785 // has been explicitly specialized. 3786 if (!getLangOptions().CPlusPlus0x) { 3787 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization) 3788 << PrevDecl; 3789 Diag(PrevDecl->getLocation(), 3790 diag::note_previous_template_specialization); 3791 } 3792 SuppressNew = true; 3793 return false; 3794 3795 case TSK_ExplicitInstantiationDeclaration: 3796 // We're explicity instantiating a definition for something for which we 3797 // were previously asked to suppress instantiations. That's fine. 3798 return false; 3799 3800 case TSK_ExplicitInstantiationDefinition: 3801 // C++0x [temp.spec]p5: 3802 // For a given template and a given set of template-arguments, 3803 // - an explicit instantiation definition shall appear at most once 3804 // in a program, 3805 Diag(NewLoc, diag::err_explicit_instantiation_duplicate) 3806 << PrevDecl; 3807 Diag(PrevPointOfInstantiation, 3808 diag::note_previous_explicit_instantiation); 3809 SuppressNew = true; 3810 return false; 3811 } 3812 break; 3813 } 3814 3815 assert(false && "Missing specialization/instantiation case?"); 3816 3817 return false; 3818} 3819 3820/// \brief Perform semantic analysis for the given function template 3821/// specialization. 3822/// 3823/// This routine performs all of the semantic analysis required for an 3824/// explicit function template specialization. On successful completion, 3825/// the function declaration \p FD will become a function template 3826/// specialization. 3827/// 3828/// \param FD the function declaration, which will be updated to become a 3829/// function template specialization. 3830/// 3831/// \param HasExplicitTemplateArgs whether any template arguments were 3832/// explicitly provided. 3833/// 3834/// \param LAngleLoc the location of the left angle bracket ('<'), if 3835/// template arguments were explicitly provided. 3836/// 3837/// \param ExplicitTemplateArgs the explicitly-provided template arguments, 3838/// if any. 3839/// 3840/// \param NumExplicitTemplateArgs the number of explicitly-provided template 3841/// arguments. This number may be zero even when HasExplicitTemplateArgs is 3842/// true as in, e.g., \c void sort<>(char*, char*); 3843/// 3844/// \param RAngleLoc the location of the right angle bracket ('>'), if 3845/// template arguments were explicitly provided. 3846/// 3847/// \param PrevDecl the set of declarations that 3848bool 3849Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD, 3850 const TemplateArgumentListInfo *ExplicitTemplateArgs, 3851 LookupResult &Previous) { 3852 // The set of function template specializations that could match this 3853 // explicit function template specialization. 3854 typedef llvm::SmallVector<FunctionDecl *, 8> CandidateSet; 3855 CandidateSet Candidates; 3856 3857 DeclContext *FDLookupContext = FD->getDeclContext()->getLookupContext(); 3858 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 3859 I != E; ++I) { 3860 NamedDecl *Ovl = (*I)->getUnderlyingDecl(); 3861 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) { 3862 // Only consider templates found within the same semantic lookup scope as 3863 // FD. 3864 if (!FDLookupContext->Equals(Ovl->getDeclContext()->getLookupContext())) 3865 continue; 3866 3867 // C++ [temp.expl.spec]p11: 3868 // A trailing template-argument can be left unspecified in the 3869 // template-id naming an explicit function template specialization 3870 // provided it can be deduced from the function argument type. 3871 // Perform template argument deduction to determine whether we may be 3872 // specializing this template. 3873 // FIXME: It is somewhat wasteful to build 3874 TemplateDeductionInfo Info(Context); 3875 FunctionDecl *Specialization = 0; 3876 if (TemplateDeductionResult TDK 3877 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs, 3878 FD->getType(), 3879 Specialization, 3880 Info)) { 3881 // FIXME: Template argument deduction failed; record why it failed, so 3882 // that we can provide nifty diagnostics. 3883 (void)TDK; 3884 continue; 3885 } 3886 3887 // Record this candidate. 3888 Candidates.push_back(Specialization); 3889 } 3890 } 3891 3892 // Find the most specialized function template. 3893 FunctionDecl *Specialization = getMostSpecialized(Candidates.data(), 3894 Candidates.size(), 3895 TPOC_Other, 3896 FD->getLocation(), 3897 PartialDiagnostic(diag::err_function_template_spec_no_match) 3898 << FD->getDeclName(), 3899 PartialDiagnostic(diag::err_function_template_spec_ambiguous) 3900 << FD->getDeclName() << (ExplicitTemplateArgs != 0), 3901 PartialDiagnostic(diag::note_function_template_spec_matched)); 3902 if (!Specialization) 3903 return true; 3904 3905 // FIXME: Check if the prior specialization has a point of instantiation. 3906 // If so, we have run afoul of . 3907 3908 // Check the scope of this explicit specialization. 3909 if (CheckTemplateSpecializationScope(*this, 3910 Specialization->getPrimaryTemplate(), 3911 Specialization, FD->getLocation(), 3912 false)) 3913 return true; 3914 3915 // C++ [temp.expl.spec]p6: 3916 // If a template, a member template or the member of a class template is 3917 // explicitly specialized then that specialization shall be declared 3918 // before the first use of that specialization that would cause an implicit 3919 // instantiation to take place, in every translation unit in which such a 3920 // use occurs; no diagnostic is required. 3921 FunctionTemplateSpecializationInfo *SpecInfo 3922 = Specialization->getTemplateSpecializationInfo(); 3923 assert(SpecInfo && "Function template specialization info missing?"); 3924 if (SpecInfo->getPointOfInstantiation().isValid()) { 3925 Diag(FD->getLocation(), diag::err_specialization_after_instantiation) 3926 << FD; 3927 Diag(SpecInfo->getPointOfInstantiation(), 3928 diag::note_instantiation_required_here) 3929 << (Specialization->getTemplateSpecializationKind() 3930 != TSK_ImplicitInstantiation); 3931 return true; 3932 } 3933 3934 // Mark the prior declaration as an explicit specialization, so that later 3935 // clients know that this is an explicit specialization. 3936 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization); 3937 3938 // Turn the given function declaration into a function template 3939 // specialization, with the template arguments from the previous 3940 // specialization. 3941 FD->setFunctionTemplateSpecialization(Context, 3942 Specialization->getPrimaryTemplate(), 3943 new (Context) TemplateArgumentList( 3944 *Specialization->getTemplateSpecializationArgs()), 3945 /*InsertPos=*/0, 3946 TSK_ExplicitSpecialization); 3947 3948 // The "previous declaration" for this function template specialization is 3949 // the prior function template specialization. 3950 Previous.clear(); 3951 Previous.addDecl(Specialization); 3952 return false; 3953} 3954 3955/// \brief Perform semantic analysis for the given non-template member 3956/// specialization. 3957/// 3958/// This routine performs all of the semantic analysis required for an 3959/// explicit member function specialization. On successful completion, 3960/// the function declaration \p FD will become a member function 3961/// specialization. 3962/// 3963/// \param Member the member declaration, which will be updated to become a 3964/// specialization. 3965/// 3966/// \param Previous the set of declarations, one of which may be specialized 3967/// by this function specialization; the set will be modified to contain the 3968/// redeclared member. 3969bool 3970Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) { 3971 assert(!isa<TemplateDecl>(Member) && "Only for non-template members"); 3972 3973 // Try to find the member we are instantiating. 3974 NamedDecl *Instantiation = 0; 3975 NamedDecl *InstantiatedFrom = 0; 3976 MemberSpecializationInfo *MSInfo = 0; 3977 3978 if (Previous.empty()) { 3979 // Nowhere to look anyway. 3980 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) { 3981 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 3982 I != E; ++I) { 3983 NamedDecl *D = (*I)->getUnderlyingDecl(); 3984 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 3985 if (Context.hasSameType(Function->getType(), Method->getType())) { 3986 Instantiation = Method; 3987 InstantiatedFrom = Method->getInstantiatedFromMemberFunction(); 3988 MSInfo = Method->getMemberSpecializationInfo(); 3989 break; 3990 } 3991 } 3992 } 3993 } else if (isa<VarDecl>(Member)) { 3994 VarDecl *PrevVar; 3995 if (Previous.isSingleResult() && 3996 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl()))) 3997 if (PrevVar->isStaticDataMember()) { 3998 Instantiation = PrevVar; 3999 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember(); 4000 MSInfo = PrevVar->getMemberSpecializationInfo(); 4001 } 4002 } else if (isa<RecordDecl>(Member)) { 4003 CXXRecordDecl *PrevRecord; 4004 if (Previous.isSingleResult() && 4005 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) { 4006 Instantiation = PrevRecord; 4007 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass(); 4008 MSInfo = PrevRecord->getMemberSpecializationInfo(); 4009 } 4010 } 4011 4012 if (!Instantiation) { 4013 // There is no previous declaration that matches. Since member 4014 // specializations are always out-of-line, the caller will complain about 4015 // this mismatch later. 4016 return false; 4017 } 4018 4019 // Make sure that this is a specialization of a member. 4020 if (!InstantiatedFrom) { 4021 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated) 4022 << Member; 4023 Diag(Instantiation->getLocation(), diag::note_specialized_decl); 4024 return true; 4025 } 4026 4027 // C++ [temp.expl.spec]p6: 4028 // If a template, a member template or the member of a class template is 4029 // explicitly specialized then that spe- cialization shall be declared 4030 // before the first use of that specialization that would cause an implicit 4031 // instantiation to take place, in every translation unit in which such a 4032 // use occurs; no diagnostic is required. 4033 assert(MSInfo && "Member specialization info missing?"); 4034 if (MSInfo->getPointOfInstantiation().isValid()) { 4035 Diag(Member->getLocation(), diag::err_specialization_after_instantiation) 4036 << Member; 4037 Diag(MSInfo->getPointOfInstantiation(), 4038 diag::note_instantiation_required_here) 4039 << (MSInfo->getTemplateSpecializationKind() != TSK_ImplicitInstantiation); 4040 return true; 4041 } 4042 4043 // Check the scope of this explicit specialization. 4044 if (CheckTemplateSpecializationScope(*this, 4045 InstantiatedFrom, 4046 Instantiation, Member->getLocation(), 4047 false)) 4048 return true; 4049 4050 // Note that this is an explicit instantiation of a member. 4051 // the original declaration to note that it is an explicit specialization 4052 // (if it was previously an implicit instantiation). This latter step 4053 // makes bookkeeping easier. 4054 if (isa<FunctionDecl>(Member)) { 4055 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation); 4056 if (InstantiationFunction->getTemplateSpecializationKind() == 4057 TSK_ImplicitInstantiation) { 4058 InstantiationFunction->setTemplateSpecializationKind( 4059 TSK_ExplicitSpecialization); 4060 InstantiationFunction->setLocation(Member->getLocation()); 4061 } 4062 4063 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction( 4064 cast<CXXMethodDecl>(InstantiatedFrom), 4065 TSK_ExplicitSpecialization); 4066 } else if (isa<VarDecl>(Member)) { 4067 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation); 4068 if (InstantiationVar->getTemplateSpecializationKind() == 4069 TSK_ImplicitInstantiation) { 4070 InstantiationVar->setTemplateSpecializationKind( 4071 TSK_ExplicitSpecialization); 4072 InstantiationVar->setLocation(Member->getLocation()); 4073 } 4074 4075 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member), 4076 cast<VarDecl>(InstantiatedFrom), 4077 TSK_ExplicitSpecialization); 4078 } else { 4079 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain"); 4080 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation); 4081 if (InstantiationClass->getTemplateSpecializationKind() == 4082 TSK_ImplicitInstantiation) { 4083 InstantiationClass->setTemplateSpecializationKind( 4084 TSK_ExplicitSpecialization); 4085 InstantiationClass->setLocation(Member->getLocation()); 4086 } 4087 4088 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass( 4089 cast<CXXRecordDecl>(InstantiatedFrom), 4090 TSK_ExplicitSpecialization); 4091 } 4092 4093 // Save the caller the trouble of having to figure out which declaration 4094 // this specialization matches. 4095 Previous.clear(); 4096 Previous.addDecl(Instantiation); 4097 return false; 4098} 4099 4100/// \brief Check the scope of an explicit instantiation. 4101static void CheckExplicitInstantiationScope(Sema &S, NamedDecl *D, 4102 SourceLocation InstLoc, 4103 bool WasQualifiedName) { 4104 DeclContext *ExpectedContext 4105 = D->getDeclContext()->getEnclosingNamespaceContext()->getLookupContext(); 4106 DeclContext *CurContext = S.CurContext->getLookupContext(); 4107 4108 // C++0x [temp.explicit]p2: 4109 // An explicit instantiation shall appear in an enclosing namespace of its 4110 // template. 4111 // 4112 // This is DR275, which we do not retroactively apply to C++98/03. 4113 if (S.getLangOptions().CPlusPlus0x && 4114 !CurContext->Encloses(ExpectedContext)) { 4115 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ExpectedContext)) 4116 S.Diag(InstLoc, diag::err_explicit_instantiation_out_of_scope) 4117 << D << NS; 4118 else 4119 S.Diag(InstLoc, diag::err_explicit_instantiation_must_be_global) 4120 << D; 4121 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here); 4122 return; 4123 } 4124 4125 // C++0x [temp.explicit]p2: 4126 // If the name declared in the explicit instantiation is an unqualified 4127 // name, the explicit instantiation shall appear in the namespace where 4128 // its template is declared or, if that namespace is inline (7.3.1), any 4129 // namespace from its enclosing namespace set. 4130 if (WasQualifiedName) 4131 return; 4132 4133 if (CurContext->Equals(ExpectedContext)) 4134 return; 4135 4136 S.Diag(InstLoc, diag::err_explicit_instantiation_unqualified_wrong_namespace) 4137 << D << ExpectedContext; 4138 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here); 4139} 4140 4141/// \brief Determine whether the given scope specifier has a template-id in it. 4142static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) { 4143 if (!SS.isSet()) 4144 return false; 4145 4146 // C++0x [temp.explicit]p2: 4147 // If the explicit instantiation is for a member function, a member class 4148 // or a static data member of a class template specialization, the name of 4149 // the class template specialization in the qualified-id for the member 4150 // name shall be a simple-template-id. 4151 // 4152 // C++98 has the same restriction, just worded differently. 4153 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep(); 4154 NNS; NNS = NNS->getPrefix()) 4155 if (Type *T = NNS->getAsType()) 4156 if (isa<TemplateSpecializationType>(T)) 4157 return true; 4158 4159 return false; 4160} 4161 4162// Explicit instantiation of a class template specialization 4163// FIXME: Implement extern template semantics 4164Sema::DeclResult 4165Sema::ActOnExplicitInstantiation(Scope *S, 4166 SourceLocation ExternLoc, 4167 SourceLocation TemplateLoc, 4168 unsigned TagSpec, 4169 SourceLocation KWLoc, 4170 const CXXScopeSpec &SS, 4171 TemplateTy TemplateD, 4172 SourceLocation TemplateNameLoc, 4173 SourceLocation LAngleLoc, 4174 ASTTemplateArgsPtr TemplateArgsIn, 4175 SourceLocation RAngleLoc, 4176 AttributeList *Attr) { 4177 // Find the class template we're specializing 4178 TemplateName Name = TemplateD.getAsVal<TemplateName>(); 4179 ClassTemplateDecl *ClassTemplate 4180 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl()); 4181 4182 // Check that the specialization uses the same tag kind as the 4183 // original template. 4184 TagDecl::TagKind Kind; 4185 switch (TagSpec) { 4186 default: assert(0 && "Unknown tag type!"); 4187 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break; 4188 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break; 4189 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break; 4190 } 4191 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), 4192 Kind, KWLoc, 4193 *ClassTemplate->getIdentifier())) { 4194 Diag(KWLoc, diag::err_use_with_wrong_tag) 4195 << ClassTemplate 4196 << CodeModificationHint::CreateReplacement(KWLoc, 4197 ClassTemplate->getTemplatedDecl()->getKindName()); 4198 Diag(ClassTemplate->getTemplatedDecl()->getLocation(), 4199 diag::note_previous_use); 4200 Kind = ClassTemplate->getTemplatedDecl()->getTagKind(); 4201 } 4202 4203 // C++0x [temp.explicit]p2: 4204 // There are two forms of explicit instantiation: an explicit instantiation 4205 // definition and an explicit instantiation declaration. An explicit 4206 // instantiation declaration begins with the extern keyword. [...] 4207 TemplateSpecializationKind TSK 4208 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition 4209 : TSK_ExplicitInstantiationDeclaration; 4210 4211 // Translate the parser's template argument list in our AST format. 4212 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); 4213 translateTemplateArguments(TemplateArgsIn, TemplateArgs); 4214 4215 // Check that the template argument list is well-formed for this 4216 // template. 4217 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(), 4218 TemplateArgs.size()); 4219 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, 4220 TemplateArgs, false, Converted)) 4221 return true; 4222 4223 assert((Converted.structuredSize() == 4224 ClassTemplate->getTemplateParameters()->size()) && 4225 "Converted template argument list is too short!"); 4226 4227 // Find the class template specialization declaration that 4228 // corresponds to these arguments. 4229 llvm::FoldingSetNodeID ID; 4230 ClassTemplateSpecializationDecl::Profile(ID, 4231 Converted.getFlatArguments(), 4232 Converted.flatSize(), 4233 Context); 4234 void *InsertPos = 0; 4235 ClassTemplateSpecializationDecl *PrevDecl 4236 = ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos); 4237 4238 // C++0x [temp.explicit]p2: 4239 // [...] An explicit instantiation shall appear in an enclosing 4240 // namespace of its template. [...] 4241 // 4242 // This is C++ DR 275. 4243 CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc, 4244 SS.isSet()); 4245 4246 ClassTemplateSpecializationDecl *Specialization = 0; 4247 4248 bool ReusedDecl = false; 4249 if (PrevDecl) { 4250 bool SuppressNew = false; 4251 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK, 4252 PrevDecl, 4253 PrevDecl->getSpecializationKind(), 4254 PrevDecl->getPointOfInstantiation(), 4255 SuppressNew)) 4256 return DeclPtrTy::make(PrevDecl); 4257 4258 if (SuppressNew) 4259 return DeclPtrTy::make(PrevDecl); 4260 4261 if (PrevDecl->getSpecializationKind() == TSK_ImplicitInstantiation || 4262 PrevDecl->getSpecializationKind() == TSK_Undeclared) { 4263 // Since the only prior class template specialization with these 4264 // arguments was referenced but not declared, reuse that 4265 // declaration node as our own, updating its source location to 4266 // reflect our new declaration. 4267 Specialization = PrevDecl; 4268 Specialization->setLocation(TemplateNameLoc); 4269 PrevDecl = 0; 4270 ReusedDecl = true; 4271 } 4272 } 4273 4274 if (!Specialization) { 4275 // Create a new class template specialization declaration node for 4276 // this explicit specialization. 4277 Specialization 4278 = ClassTemplateSpecializationDecl::Create(Context, 4279 ClassTemplate->getDeclContext(), 4280 TemplateNameLoc, 4281 ClassTemplate, 4282 Converted, PrevDecl); 4283 4284 if (PrevDecl) { 4285 // Remove the previous declaration from the folding set, since we want 4286 // to introduce a new declaration. 4287 ClassTemplate->getSpecializations().RemoveNode(PrevDecl); 4288 ClassTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos); 4289 } 4290 4291 // Insert the new specialization. 4292 ClassTemplate->getSpecializations().InsertNode(Specialization, InsertPos); 4293 } 4294 4295 // Build the fully-sugared type for this explicit instantiation as 4296 // the user wrote in the explicit instantiation itself. This means 4297 // that we'll pretty-print the type retrieved from the 4298 // specialization's declaration the way that the user actually wrote 4299 // the explicit instantiation, rather than formatting the name based 4300 // on the "canonical" representation used to store the template 4301 // arguments in the specialization. 4302 QualType WrittenTy 4303 = Context.getTemplateSpecializationType(Name, TemplateArgs, 4304 Context.getTypeDeclType(Specialization)); 4305 Specialization->setTypeAsWritten(WrittenTy); 4306 TemplateArgsIn.release(); 4307 4308 if (!ReusedDecl) { 4309 // Add the explicit instantiation into its lexical context. However, 4310 // since explicit instantiations are never found by name lookup, we 4311 // just put it into the declaration context directly. 4312 Specialization->setLexicalDeclContext(CurContext); 4313 CurContext->addDecl(Specialization); 4314 } 4315 4316 // C++ [temp.explicit]p3: 4317 // A definition of a class template or class member template 4318 // shall be in scope at the point of the explicit instantiation of 4319 // the class template or class member template. 4320 // 4321 // This check comes when we actually try to perform the 4322 // instantiation. 4323 ClassTemplateSpecializationDecl *Def 4324 = cast_or_null<ClassTemplateSpecializationDecl>( 4325 Specialization->getDefinition(Context)); 4326 if (!Def) 4327 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK); 4328 4329 // Instantiate the members of this class template specialization. 4330 Def = cast_or_null<ClassTemplateSpecializationDecl>( 4331 Specialization->getDefinition(Context)); 4332 if (Def) 4333 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK); 4334 4335 return DeclPtrTy::make(Specialization); 4336} 4337 4338// Explicit instantiation of a member class of a class template. 4339Sema::DeclResult 4340Sema::ActOnExplicitInstantiation(Scope *S, 4341 SourceLocation ExternLoc, 4342 SourceLocation TemplateLoc, 4343 unsigned TagSpec, 4344 SourceLocation KWLoc, 4345 const CXXScopeSpec &SS, 4346 IdentifierInfo *Name, 4347 SourceLocation NameLoc, 4348 AttributeList *Attr) { 4349 4350 bool Owned = false; 4351 bool IsDependent = false; 4352 DeclPtrTy TagD = ActOnTag(S, TagSpec, Action::TUK_Reference, 4353 KWLoc, SS, Name, NameLoc, Attr, AS_none, 4354 MultiTemplateParamsArg(*this, 0, 0), 4355 Owned, IsDependent); 4356 assert(!IsDependent && "explicit instantiation of dependent name not yet handled"); 4357 4358 if (!TagD) 4359 return true; 4360 4361 TagDecl *Tag = cast<TagDecl>(TagD.getAs<Decl>()); 4362 if (Tag->isEnum()) { 4363 Diag(TemplateLoc, diag::err_explicit_instantiation_enum) 4364 << Context.getTypeDeclType(Tag); 4365 return true; 4366 } 4367 4368 if (Tag->isInvalidDecl()) 4369 return true; 4370 4371 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag); 4372 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass(); 4373 if (!Pattern) { 4374 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type) 4375 << Context.getTypeDeclType(Record); 4376 Diag(Record->getLocation(), diag::note_nontemplate_decl_here); 4377 return true; 4378 } 4379 4380 // C++0x [temp.explicit]p2: 4381 // If the explicit instantiation is for a class or member class, the 4382 // elaborated-type-specifier in the declaration shall include a 4383 // simple-template-id. 4384 // 4385 // C++98 has the same restriction, just worded differently. 4386 if (!ScopeSpecifierHasTemplateId(SS)) 4387 Diag(TemplateLoc, diag::err_explicit_instantiation_without_qualified_id) 4388 << Record << SS.getRange(); 4389 4390 // C++0x [temp.explicit]p2: 4391 // There are two forms of explicit instantiation: an explicit instantiation 4392 // definition and an explicit instantiation declaration. An explicit 4393 // instantiation declaration begins with the extern keyword. [...] 4394 TemplateSpecializationKind TSK 4395 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition 4396 : TSK_ExplicitInstantiationDeclaration; 4397 4398 // C++0x [temp.explicit]p2: 4399 // [...] An explicit instantiation shall appear in an enclosing 4400 // namespace of its template. [...] 4401 // 4402 // This is C++ DR 275. 4403 CheckExplicitInstantiationScope(*this, Record, NameLoc, true); 4404 4405 // Verify that it is okay to explicitly instantiate here. 4406 CXXRecordDecl *PrevDecl 4407 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration()); 4408 if (!PrevDecl && Record->getDefinition(Context)) 4409 PrevDecl = Record; 4410 if (PrevDecl) { 4411 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo(); 4412 bool SuppressNew = false; 4413 assert(MSInfo && "No member specialization information?"); 4414 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK, 4415 PrevDecl, 4416 MSInfo->getTemplateSpecializationKind(), 4417 MSInfo->getPointOfInstantiation(), 4418 SuppressNew)) 4419 return true; 4420 if (SuppressNew) 4421 return TagD; 4422 } 4423 4424 CXXRecordDecl *RecordDef 4425 = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context)); 4426 if (!RecordDef) { 4427 // C++ [temp.explicit]p3: 4428 // A definition of a member class of a class template shall be in scope 4429 // at the point of an explicit instantiation of the member class. 4430 CXXRecordDecl *Def 4431 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition(Context)); 4432 if (!Def) { 4433 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member) 4434 << 0 << Record->getDeclName() << Record->getDeclContext(); 4435 Diag(Pattern->getLocation(), diag::note_forward_declaration) 4436 << Pattern; 4437 return true; 4438 } else { 4439 if (InstantiateClass(NameLoc, Record, Def, 4440 getTemplateInstantiationArgs(Record), 4441 TSK)) 4442 return true; 4443 4444 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition(Context)); 4445 if (!RecordDef) 4446 return true; 4447 } 4448 } 4449 4450 // Instantiate all of the members of the class. 4451 InstantiateClassMembers(NameLoc, RecordDef, 4452 getTemplateInstantiationArgs(Record), TSK); 4453 4454 // FIXME: We don't have any representation for explicit instantiations of 4455 // member classes. Such a representation is not needed for compilation, but it 4456 // should be available for clients that want to see all of the declarations in 4457 // the source code. 4458 return TagD; 4459} 4460 4461Sema::DeclResult Sema::ActOnExplicitInstantiation(Scope *S, 4462 SourceLocation ExternLoc, 4463 SourceLocation TemplateLoc, 4464 Declarator &D) { 4465 // Explicit instantiations always require a name. 4466 DeclarationName Name = GetNameForDeclarator(D); 4467 if (!Name) { 4468 if (!D.isInvalidType()) 4469 Diag(D.getDeclSpec().getSourceRange().getBegin(), 4470 diag::err_explicit_instantiation_requires_name) 4471 << D.getDeclSpec().getSourceRange() 4472 << D.getSourceRange(); 4473 4474 return true; 4475 } 4476 4477 // The scope passed in may not be a decl scope. Zip up the scope tree until 4478 // we find one that is. 4479 while ((S->getFlags() & Scope::DeclScope) == 0 || 4480 (S->getFlags() & Scope::TemplateParamScope) != 0) 4481 S = S->getParent(); 4482 4483 // Determine the type of the declaration. 4484 QualType R = GetTypeForDeclarator(D, S, 0); 4485 if (R.isNull()) 4486 return true; 4487 4488 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 4489 // Cannot explicitly instantiate a typedef. 4490 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef) 4491 << Name; 4492 return true; 4493 } 4494 4495 // C++0x [temp.explicit]p1: 4496 // [...] An explicit instantiation of a function template shall not use the 4497 // inline or constexpr specifiers. 4498 // Presumably, this also applies to member functions of class templates as 4499 // well. 4500 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x) 4501 Diag(D.getDeclSpec().getInlineSpecLoc(), 4502 diag::err_explicit_instantiation_inline) 4503 << CodeModificationHint::CreateRemoval( 4504 SourceRange(D.getDeclSpec().getInlineSpecLoc())); 4505 4506 // FIXME: check for constexpr specifier. 4507 4508 // C++0x [temp.explicit]p2: 4509 // There are two forms of explicit instantiation: an explicit instantiation 4510 // definition and an explicit instantiation declaration. An explicit 4511 // instantiation declaration begins with the extern keyword. [...] 4512 TemplateSpecializationKind TSK 4513 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition 4514 : TSK_ExplicitInstantiationDeclaration; 4515 4516 LookupResult Previous(*this, Name, D.getIdentifierLoc(), LookupOrdinaryName); 4517 LookupParsedName(Previous, S, &D.getCXXScopeSpec()); 4518 4519 if (!R->isFunctionType()) { 4520 // C++ [temp.explicit]p1: 4521 // A [...] static data member of a class template can be explicitly 4522 // instantiated from the member definition associated with its class 4523 // template. 4524 if (Previous.isAmbiguous()) 4525 return true; 4526 4527 VarDecl *Prev = dyn_cast_or_null<VarDecl>( 4528 Previous.getAsSingleDecl(Context)); 4529 if (!Prev || !Prev->isStaticDataMember()) { 4530 // We expect to see a data data member here. 4531 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known) 4532 << Name; 4533 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end(); 4534 P != PEnd; ++P) 4535 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here); 4536 return true; 4537 } 4538 4539 if (!Prev->getInstantiatedFromStaticDataMember()) { 4540 // FIXME: Check for explicit specialization? 4541 Diag(D.getIdentifierLoc(), 4542 diag::err_explicit_instantiation_data_member_not_instantiated) 4543 << Prev; 4544 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here); 4545 // FIXME: Can we provide a note showing where this was declared? 4546 return true; 4547 } 4548 4549 // C++0x [temp.explicit]p2: 4550 // If the explicit instantiation is for a member function, a member class 4551 // or a static data member of a class template specialization, the name of 4552 // the class template specialization in the qualified-id for the member 4553 // name shall be a simple-template-id. 4554 // 4555 // C++98 has the same restriction, just worded differently. 4556 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec())) 4557 Diag(D.getIdentifierLoc(), 4558 diag::err_explicit_instantiation_without_qualified_id) 4559 << Prev << D.getCXXScopeSpec().getRange(); 4560 4561 // Check the scope of this explicit instantiation. 4562 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true); 4563 4564 // Verify that it is okay to explicitly instantiate here. 4565 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo(); 4566 assert(MSInfo && "Missing static data member specialization info?"); 4567 bool SuppressNew = false; 4568 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev, 4569 MSInfo->getTemplateSpecializationKind(), 4570 MSInfo->getPointOfInstantiation(), 4571 SuppressNew)) 4572 return true; 4573 if (SuppressNew) 4574 return DeclPtrTy(); 4575 4576 // Instantiate static data member. 4577 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc()); 4578 if (TSK == TSK_ExplicitInstantiationDefinition) 4579 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev, false, 4580 /*DefinitionRequired=*/true); 4581 4582 // FIXME: Create an ExplicitInstantiation node? 4583 return DeclPtrTy(); 4584 } 4585 4586 // If the declarator is a template-id, translate the parser's template 4587 // argument list into our AST format. 4588 bool HasExplicitTemplateArgs = false; 4589 TemplateArgumentListInfo TemplateArgs; 4590 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 4591 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 4592 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 4593 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 4594 ASTTemplateArgsPtr TemplateArgsPtr(*this, 4595 TemplateId->getTemplateArgs(), 4596 TemplateId->NumArgs); 4597 translateTemplateArguments(TemplateArgsPtr, TemplateArgs); 4598 HasExplicitTemplateArgs = true; 4599 TemplateArgsPtr.release(); 4600 } 4601 4602 // C++ [temp.explicit]p1: 4603 // A [...] function [...] can be explicitly instantiated from its template. 4604 // A member function [...] of a class template can be explicitly 4605 // instantiated from the member definition associated with its class 4606 // template. 4607 llvm::SmallVector<FunctionDecl *, 8> Matches; 4608 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end(); 4609 P != PEnd; ++P) { 4610 NamedDecl *Prev = *P; 4611 if (!HasExplicitTemplateArgs) { 4612 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) { 4613 if (Context.hasSameUnqualifiedType(Method->getType(), R)) { 4614 Matches.clear(); 4615 Matches.push_back(Method); 4616 break; 4617 } 4618 } 4619 } 4620 4621 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev); 4622 if (!FunTmpl) 4623 continue; 4624 4625 TemplateDeductionInfo Info(Context); 4626 FunctionDecl *Specialization = 0; 4627 if (TemplateDeductionResult TDK 4628 = DeduceTemplateArguments(FunTmpl, 4629 (HasExplicitTemplateArgs ? &TemplateArgs : 0), 4630 R, Specialization, Info)) { 4631 // FIXME: Keep track of almost-matches? 4632 (void)TDK; 4633 continue; 4634 } 4635 4636 Matches.push_back(Specialization); 4637 } 4638 4639 // Find the most specialized function template specialization. 4640 FunctionDecl *Specialization 4641 = getMostSpecialized(Matches.data(), Matches.size(), TPOC_Other, 4642 D.getIdentifierLoc(), 4643 PartialDiagnostic(diag::err_explicit_instantiation_not_known) << Name, 4644 PartialDiagnostic(diag::err_explicit_instantiation_ambiguous) << Name, 4645 PartialDiagnostic(diag::note_explicit_instantiation_candidate)); 4646 4647 if (!Specialization) 4648 return true; 4649 4650 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) { 4651 Diag(D.getIdentifierLoc(), 4652 diag::err_explicit_instantiation_member_function_not_instantiated) 4653 << Specialization 4654 << (Specialization->getTemplateSpecializationKind() == 4655 TSK_ExplicitSpecialization); 4656 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here); 4657 return true; 4658 } 4659 4660 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration(); 4661 if (!PrevDecl && Specialization->isThisDeclarationADefinition()) 4662 PrevDecl = Specialization; 4663 4664 if (PrevDecl) { 4665 bool SuppressNew = false; 4666 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, 4667 PrevDecl, 4668 PrevDecl->getTemplateSpecializationKind(), 4669 PrevDecl->getPointOfInstantiation(), 4670 SuppressNew)) 4671 return true; 4672 4673 // FIXME: We may still want to build some representation of this 4674 // explicit specialization. 4675 if (SuppressNew) 4676 return DeclPtrTy(); 4677 } 4678 4679 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc()); 4680 4681 if (TSK == TSK_ExplicitInstantiationDefinition) 4682 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization, 4683 false, /*DefinitionRequired=*/true); 4684 4685 // C++0x [temp.explicit]p2: 4686 // If the explicit instantiation is for a member function, a member class 4687 // or a static data member of a class template specialization, the name of 4688 // the class template specialization in the qualified-id for the member 4689 // name shall be a simple-template-id. 4690 // 4691 // C++98 has the same restriction, just worded differently. 4692 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate(); 4693 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl && 4694 D.getCXXScopeSpec().isSet() && 4695 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec())) 4696 Diag(D.getIdentifierLoc(), 4697 diag::err_explicit_instantiation_without_qualified_id) 4698 << Specialization << D.getCXXScopeSpec().getRange(); 4699 4700 CheckExplicitInstantiationScope(*this, 4701 FunTmpl? (NamedDecl *)FunTmpl 4702 : Specialization->getInstantiatedFromMemberFunction(), 4703 D.getIdentifierLoc(), 4704 D.getCXXScopeSpec().isSet()); 4705 4706 // FIXME: Create some kind of ExplicitInstantiationDecl here. 4707 return DeclPtrTy(); 4708} 4709 4710Sema::TypeResult 4711Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 4712 const CXXScopeSpec &SS, IdentifierInfo *Name, 4713 SourceLocation TagLoc, SourceLocation NameLoc) { 4714 // This has to hold, because SS is expected to be defined. 4715 assert(Name && "Expected a name in a dependent tag"); 4716 4717 NestedNameSpecifier *NNS 4718 = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 4719 if (!NNS) 4720 return true; 4721 4722 QualType T = CheckTypenameType(NNS, *Name, SourceRange(TagLoc, NameLoc)); 4723 if (T.isNull()) 4724 return true; 4725 4726 TagDecl::TagKind TagKind = TagDecl::getTagKindForTypeSpec(TagSpec); 4727 QualType ElabType = Context.getElaboratedType(T, TagKind); 4728 4729 return ElabType.getAsOpaquePtr(); 4730} 4731 4732Sema::TypeResult 4733Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS, 4734 const IdentifierInfo &II, SourceLocation IdLoc) { 4735 NestedNameSpecifier *NNS 4736 = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 4737 if (!NNS) 4738 return true; 4739 4740 QualType T = CheckTypenameType(NNS, II, SourceRange(TypenameLoc, IdLoc)); 4741 if (T.isNull()) 4742 return true; 4743 return T.getAsOpaquePtr(); 4744} 4745 4746Sema::TypeResult 4747Sema::ActOnTypenameType(SourceLocation TypenameLoc, const CXXScopeSpec &SS, 4748 SourceLocation TemplateLoc, TypeTy *Ty) { 4749 QualType T = GetTypeFromParser(Ty); 4750 NestedNameSpecifier *NNS 4751 = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 4752 const TemplateSpecializationType *TemplateId 4753 = T->getAs<TemplateSpecializationType>(); 4754 assert(TemplateId && "Expected a template specialization type"); 4755 4756 if (computeDeclContext(SS, false)) { 4757 // If we can compute a declaration context, then the "typename" 4758 // keyword was superfluous. Just build a QualifiedNameType to keep 4759 // track of the nested-name-specifier. 4760 4761 // FIXME: Note that the QualifiedNameType had the "typename" keyword! 4762 return Context.getQualifiedNameType(NNS, T).getAsOpaquePtr(); 4763 } 4764 4765 return Context.getTypenameType(NNS, TemplateId).getAsOpaquePtr(); 4766} 4767 4768/// \brief Build the type that describes a C++ typename specifier, 4769/// e.g., "typename T::type". 4770QualType 4771Sema::CheckTypenameType(NestedNameSpecifier *NNS, const IdentifierInfo &II, 4772 SourceRange Range) { 4773 CXXRecordDecl *CurrentInstantiation = 0; 4774 if (NNS->isDependent()) { 4775 CurrentInstantiation = getCurrentInstantiationOf(NNS); 4776 4777 // If the nested-name-specifier does not refer to the current 4778 // instantiation, then build a typename type. 4779 if (!CurrentInstantiation) 4780 return Context.getTypenameType(NNS, &II); 4781 4782 // The nested-name-specifier refers to the current instantiation, so the 4783 // "typename" keyword itself is superfluous. In C++03, the program is 4784 // actually ill-formed. However, DR 382 (in C++0x CD1) allows such 4785 // extraneous "typename" keywords, and we retroactively apply this DR to 4786 // C++03 code. 4787 } 4788 4789 DeclContext *Ctx = 0; 4790 4791 if (CurrentInstantiation) 4792 Ctx = CurrentInstantiation; 4793 else { 4794 CXXScopeSpec SS; 4795 SS.setScopeRep(NNS); 4796 SS.setRange(Range); 4797 if (RequireCompleteDeclContext(SS)) 4798 return QualType(); 4799 4800 Ctx = computeDeclContext(SS); 4801 } 4802 assert(Ctx && "No declaration context?"); 4803 4804 DeclarationName Name(&II); 4805 LookupResult Result(*this, Name, Range.getEnd(), LookupOrdinaryName); 4806 LookupQualifiedName(Result, Ctx); 4807 unsigned DiagID = 0; 4808 Decl *Referenced = 0; 4809 switch (Result.getResultKind()) { 4810 case LookupResult::NotFound: 4811 DiagID = diag::err_typename_nested_not_found; 4812 break; 4813 4814 case LookupResult::Found: 4815 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) { 4816 // We found a type. Build a QualifiedNameType, since the 4817 // typename-specifier was just sugar. FIXME: Tell 4818 // QualifiedNameType that it has a "typename" prefix. 4819 return Context.getQualifiedNameType(NNS, Context.getTypeDeclType(Type)); 4820 } 4821 4822 DiagID = diag::err_typename_nested_not_type; 4823 Referenced = Result.getFoundDecl(); 4824 break; 4825 4826 case LookupResult::FoundUnresolvedValue: 4827 llvm::llvm_unreachable("unresolved using decl in non-dependent context"); 4828 return QualType(); 4829 4830 case LookupResult::FoundOverloaded: 4831 DiagID = diag::err_typename_nested_not_type; 4832 Referenced = *Result.begin(); 4833 break; 4834 4835 case LookupResult::Ambiguous: 4836 return QualType(); 4837 } 4838 4839 // If we get here, it's because name lookup did not find a 4840 // type. Emit an appropriate diagnostic and return an error. 4841 Diag(Range.getEnd(), DiagID) << Range << Name << Ctx; 4842 if (Referenced) 4843 Diag(Referenced->getLocation(), diag::note_typename_refers_here) 4844 << Name; 4845 return QualType(); 4846} 4847 4848namespace { 4849 // See Sema::RebuildTypeInCurrentInstantiation 4850 class VISIBILITY_HIDDEN CurrentInstantiationRebuilder 4851 : public TreeTransform<CurrentInstantiationRebuilder> { 4852 SourceLocation Loc; 4853 DeclarationName Entity; 4854 4855 public: 4856 CurrentInstantiationRebuilder(Sema &SemaRef, 4857 SourceLocation Loc, 4858 DeclarationName Entity) 4859 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef), 4860 Loc(Loc), Entity(Entity) { } 4861 4862 /// \brief Determine whether the given type \p T has already been 4863 /// transformed. 4864 /// 4865 /// For the purposes of type reconstruction, a type has already been 4866 /// transformed if it is NULL or if it is not dependent. 4867 bool AlreadyTransformed(QualType T) { 4868 return T.isNull() || !T->isDependentType(); 4869 } 4870 4871 /// \brief Returns the location of the entity whose type is being 4872 /// rebuilt. 4873 SourceLocation getBaseLocation() { return Loc; } 4874 4875 /// \brief Returns the name of the entity whose type is being rebuilt. 4876 DeclarationName getBaseEntity() { return Entity; } 4877 4878 /// \brief Sets the "base" location and entity when that 4879 /// information is known based on another transformation. 4880 void setBase(SourceLocation Loc, DeclarationName Entity) { 4881 this->Loc = Loc; 4882 this->Entity = Entity; 4883 } 4884 4885 /// \brief Transforms an expression by returning the expression itself 4886 /// (an identity function). 4887 /// 4888 /// FIXME: This is completely unsafe; we will need to actually clone the 4889 /// expressions. 4890 Sema::OwningExprResult TransformExpr(Expr *E) { 4891 return getSema().Owned(E); 4892 } 4893 4894 /// \brief Transforms a typename type by determining whether the type now 4895 /// refers to a member of the current instantiation, and then 4896 /// type-checking and building a QualifiedNameType (when possible). 4897 QualType TransformTypenameType(TypeLocBuilder &TLB, TypenameTypeLoc TL); 4898 }; 4899} 4900 4901QualType 4902CurrentInstantiationRebuilder::TransformTypenameType(TypeLocBuilder &TLB, 4903 TypenameTypeLoc TL) { 4904 TypenameType *T = TL.getTypePtr(); 4905 4906 NestedNameSpecifier *NNS 4907 = TransformNestedNameSpecifier(T->getQualifier(), 4908 /*FIXME:*/SourceRange(getBaseLocation())); 4909 if (!NNS) 4910 return QualType(); 4911 4912 // If the nested-name-specifier did not change, and we cannot compute the 4913 // context corresponding to the nested-name-specifier, then this 4914 // typename type will not change; exit early. 4915 CXXScopeSpec SS; 4916 SS.setRange(SourceRange(getBaseLocation())); 4917 SS.setScopeRep(NNS); 4918 4919 QualType Result; 4920 if (NNS == T->getQualifier() && getSema().computeDeclContext(SS) == 0) 4921 Result = QualType(T, 0); 4922 4923 // Rebuild the typename type, which will probably turn into a 4924 // QualifiedNameType. 4925 else if (const TemplateSpecializationType *TemplateId = T->getTemplateId()) { 4926 QualType NewTemplateId 4927 = TransformType(QualType(TemplateId, 0)); 4928 if (NewTemplateId.isNull()) 4929 return QualType(); 4930 4931 if (NNS == T->getQualifier() && 4932 NewTemplateId == QualType(TemplateId, 0)) 4933 Result = QualType(T, 0); 4934 else 4935 Result = getDerived().RebuildTypenameType(NNS, NewTemplateId); 4936 } else 4937 Result = getDerived().RebuildTypenameType(NNS, T->getIdentifier(), 4938 SourceRange(TL.getNameLoc())); 4939 4940 TypenameTypeLoc NewTL = TLB.push<TypenameTypeLoc>(Result); 4941 NewTL.setNameLoc(TL.getNameLoc()); 4942 return Result; 4943} 4944 4945/// \brief Rebuilds a type within the context of the current instantiation. 4946/// 4947/// The type \p T is part of the type of an out-of-line member definition of 4948/// a class template (or class template partial specialization) that was parsed 4949/// and constructed before we entered the scope of the class template (or 4950/// partial specialization thereof). This routine will rebuild that type now 4951/// that we have entered the declarator's scope, which may produce different 4952/// canonical types, e.g., 4953/// 4954/// \code 4955/// template<typename T> 4956/// struct X { 4957/// typedef T* pointer; 4958/// pointer data(); 4959/// }; 4960/// 4961/// template<typename T> 4962/// typename X<T>::pointer X<T>::data() { ... } 4963/// \endcode 4964/// 4965/// Here, the type "typename X<T>::pointer" will be created as a TypenameType, 4966/// since we do not know that we can look into X<T> when we parsed the type. 4967/// This function will rebuild the type, performing the lookup of "pointer" 4968/// in X<T> and returning a QualifiedNameType whose canonical type is the same 4969/// as the canonical type of T*, allowing the return types of the out-of-line 4970/// definition and the declaration to match. 4971QualType Sema::RebuildTypeInCurrentInstantiation(QualType T, SourceLocation Loc, 4972 DeclarationName Name) { 4973 if (T.isNull() || !T->isDependentType()) 4974 return T; 4975 4976 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name); 4977 return Rebuilder.TransformType(T); 4978} 4979 4980/// \brief Produces a formatted string that describes the binding of 4981/// template parameters to template arguments. 4982std::string 4983Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params, 4984 const TemplateArgumentList &Args) { 4985 // FIXME: For variadic templates, we'll need to get the structured list. 4986 return getTemplateArgumentBindingsText(Params, Args.getFlatArgumentList(), 4987 Args.flat_size()); 4988} 4989 4990std::string 4991Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params, 4992 const TemplateArgument *Args, 4993 unsigned NumArgs) { 4994 std::string Result; 4995 4996 if (!Params || Params->size() == 0 || NumArgs == 0) 4997 return Result; 4998 4999 for (unsigned I = 0, N = Params->size(); I != N; ++I) { 5000 if (I >= NumArgs) 5001 break; 5002 5003 if (I == 0) 5004 Result += "[with "; 5005 else 5006 Result += ", "; 5007 5008 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) { 5009 Result += Id->getName(); 5010 } else { 5011 Result += '$'; 5012 Result += llvm::utostr(I); 5013 } 5014 5015 Result += " = "; 5016 5017 switch (Args[I].getKind()) { 5018 case TemplateArgument::Null: 5019 Result += "<no value>"; 5020 break; 5021 5022 case TemplateArgument::Type: { 5023 std::string TypeStr; 5024 Args[I].getAsType().getAsStringInternal(TypeStr, 5025 Context.PrintingPolicy); 5026 Result += TypeStr; 5027 break; 5028 } 5029 5030 case TemplateArgument::Declaration: { 5031 bool Unnamed = true; 5032 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(Args[I].getAsDecl())) { 5033 if (ND->getDeclName()) { 5034 Unnamed = false; 5035 Result += ND->getNameAsString(); 5036 } 5037 } 5038 5039 if (Unnamed) { 5040 Result += "<anonymous>"; 5041 } 5042 break; 5043 } 5044 5045 case TemplateArgument::Template: { 5046 std::string Str; 5047 llvm::raw_string_ostream OS(Str); 5048 Args[I].getAsTemplate().print(OS, Context.PrintingPolicy); 5049 Result += OS.str(); 5050 break; 5051 } 5052 5053 case TemplateArgument::Integral: { 5054 Result += Args[I].getAsIntegral()->toString(10); 5055 break; 5056 } 5057 5058 case TemplateArgument::Expression: { 5059 assert(false && "No expressions in deduced template arguments!"); 5060 Result += "<expression>"; 5061 break; 5062 } 5063 5064 case TemplateArgument::Pack: 5065 // FIXME: Format template argument packs 5066 Result += "<template argument pack>"; 5067 break; 5068 } 5069 } 5070 5071 Result += ']'; 5072 return Result; 5073} 5074