SemaTemplate.cpp revision e559ca1672ecef59345a928af0a6809b09282d2c
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 "clang/Sema/SemaInternal.h" 13#include "clang/Sema/Lookup.h" 14#include "clang/Sema/Scope.h" 15#include "clang/Sema/Template.h" 16#include "clang/Sema/TemplateDeduction.h" 17#include "TreeTransform.h" 18#include "clang/AST/ASTContext.h" 19#include "clang/AST/Expr.h" 20#include "clang/AST/ExprCXX.h" 21#include "clang/AST/DeclFriend.h" 22#include "clang/AST/DeclTemplate.h" 23#include "clang/AST/RecursiveASTVisitor.h" 24#include "clang/AST/TypeVisitor.h" 25#include "clang/Sema/DeclSpec.h" 26#include "clang/Sema/ParsedTemplate.h" 27#include "clang/Basic/LangOptions.h" 28#include "clang/Basic/PartialDiagnostic.h" 29#include "llvm/ADT/StringExtras.h" 30using namespace clang; 31using namespace sema; 32 33// Exported for use by Parser. 34SourceRange 35clang::getTemplateParamsRange(TemplateParameterList const * const *Ps, 36 unsigned N) { 37 if (!N) return SourceRange(); 38 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc()); 39} 40 41/// \brief Determine whether the declaration found is acceptable as the name 42/// of a template and, if so, return that template declaration. Otherwise, 43/// returns NULL. 44static NamedDecl *isAcceptableTemplateName(ASTContext &Context, 45 NamedDecl *Orig) { 46 NamedDecl *D = Orig->getUnderlyingDecl(); 47 48 if (isa<TemplateDecl>(D)) 49 return Orig; 50 51 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) { 52 // C++ [temp.local]p1: 53 // Like normal (non-template) classes, class templates have an 54 // injected-class-name (Clause 9). The injected-class-name 55 // can be used with or without a template-argument-list. When 56 // it is used without a template-argument-list, it is 57 // equivalent to the injected-class-name followed by the 58 // template-parameters of the class template enclosed in 59 // <>. When it is used with a template-argument-list, it 60 // refers to the specified class template specialization, 61 // which could be the current specialization or another 62 // specialization. 63 if (Record->isInjectedClassName()) { 64 Record = cast<CXXRecordDecl>(Record->getDeclContext()); 65 if (Record->getDescribedClassTemplate()) 66 return Record->getDescribedClassTemplate(); 67 68 if (ClassTemplateSpecializationDecl *Spec 69 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) 70 return Spec->getSpecializedTemplate(); 71 } 72 73 return 0; 74 } 75 76 return 0; 77} 78 79void Sema::FilterAcceptableTemplateNames(LookupResult &R) { 80 // The set of class templates we've already seen. 81 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates; 82 LookupResult::Filter filter = R.makeFilter(); 83 while (filter.hasNext()) { 84 NamedDecl *Orig = filter.next(); 85 NamedDecl *Repl = isAcceptableTemplateName(Context, Orig); 86 if (!Repl) 87 filter.erase(); 88 else if (Repl != Orig) { 89 90 // C++ [temp.local]p3: 91 // A lookup that finds an injected-class-name (10.2) can result in an 92 // ambiguity in certain cases (for example, if it is found in more than 93 // one base class). If all of the injected-class-names that are found 94 // refer to specializations of the same class template, and if the name 95 // is used as a template-name, the reference refers to the class 96 // template itself and not a specialization thereof, and is not 97 // ambiguous. 98 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl)) 99 if (!ClassTemplates.insert(ClassTmpl)) { 100 filter.erase(); 101 continue; 102 } 103 104 // FIXME: we promote access to public here as a workaround to 105 // the fact that LookupResult doesn't let us remember that we 106 // found this template through a particular injected class name, 107 // which means we end up doing nasty things to the invariants. 108 // Pretending that access is public is *much* safer. 109 filter.replace(Repl, AS_public); 110 } 111 } 112 filter.done(); 113} 114 115bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R) { 116 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) 117 if (isAcceptableTemplateName(Context, *I)) 118 return true; 119 120 return false; 121} 122 123TemplateNameKind Sema::isTemplateName(Scope *S, 124 CXXScopeSpec &SS, 125 bool hasTemplateKeyword, 126 UnqualifiedId &Name, 127 ParsedType ObjectTypePtr, 128 bool EnteringContext, 129 TemplateTy &TemplateResult, 130 bool &MemberOfUnknownSpecialization) { 131 assert(getLangOptions().CPlusPlus && "No template names in C!"); 132 133 DeclarationName TName; 134 MemberOfUnknownSpecialization = false; 135 136 switch (Name.getKind()) { 137 case UnqualifiedId::IK_Identifier: 138 TName = DeclarationName(Name.Identifier); 139 break; 140 141 case UnqualifiedId::IK_OperatorFunctionId: 142 TName = Context.DeclarationNames.getCXXOperatorName( 143 Name.OperatorFunctionId.Operator); 144 break; 145 146 case UnqualifiedId::IK_LiteralOperatorId: 147 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier); 148 break; 149 150 default: 151 return TNK_Non_template; 152 } 153 154 QualType ObjectType = ObjectTypePtr.get(); 155 156 LookupResult R(*this, TName, Name.getSourceRange().getBegin(), 157 LookupOrdinaryName); 158 LookupTemplateName(R, S, SS, ObjectType, EnteringContext, 159 MemberOfUnknownSpecialization); 160 if (R.empty()) return TNK_Non_template; 161 if (R.isAmbiguous()) { 162 // Suppress diagnostics; we'll redo this lookup later. 163 R.suppressDiagnostics(); 164 165 // FIXME: we might have ambiguous templates, in which case we 166 // should at least parse them properly! 167 return TNK_Non_template; 168 } 169 170 TemplateName Template; 171 TemplateNameKind TemplateKind; 172 173 unsigned ResultCount = R.end() - R.begin(); 174 if (ResultCount > 1) { 175 // We assume that we'll preserve the qualifier from a function 176 // template name in other ways. 177 Template = Context.getOverloadedTemplateName(R.begin(), R.end()); 178 TemplateKind = TNK_Function_template; 179 180 // We'll do this lookup again later. 181 R.suppressDiagnostics(); 182 } else { 183 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl()); 184 185 if (SS.isSet() && !SS.isInvalid()) { 186 NestedNameSpecifier *Qualifier 187 = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 188 Template = Context.getQualifiedTemplateName(Qualifier, 189 hasTemplateKeyword, TD); 190 } else { 191 Template = TemplateName(TD); 192 } 193 194 if (isa<FunctionTemplateDecl>(TD)) { 195 TemplateKind = TNK_Function_template; 196 197 // We'll do this lookup again later. 198 R.suppressDiagnostics(); 199 } else { 200 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) || 201 isa<TypeAliasTemplateDecl>(TD)); 202 TemplateKind = TNK_Type_template; 203 } 204 } 205 206 TemplateResult = TemplateTy::make(Template); 207 return TemplateKind; 208} 209 210bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II, 211 SourceLocation IILoc, 212 Scope *S, 213 const CXXScopeSpec *SS, 214 TemplateTy &SuggestedTemplate, 215 TemplateNameKind &SuggestedKind) { 216 // We can't recover unless there's a dependent scope specifier preceding the 217 // template name. 218 // FIXME: Typo correction? 219 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) || 220 computeDeclContext(*SS)) 221 return false; 222 223 // The code is missing a 'template' keyword prior to the dependent template 224 // name. 225 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep(); 226 Diag(IILoc, diag::err_template_kw_missing) 227 << Qualifier << II.getName() 228 << FixItHint::CreateInsertion(IILoc, "template "); 229 SuggestedTemplate 230 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II)); 231 SuggestedKind = TNK_Dependent_template_name; 232 return true; 233} 234 235void Sema::LookupTemplateName(LookupResult &Found, 236 Scope *S, CXXScopeSpec &SS, 237 QualType ObjectType, 238 bool EnteringContext, 239 bool &MemberOfUnknownSpecialization) { 240 // Determine where to perform name lookup 241 MemberOfUnknownSpecialization = false; 242 DeclContext *LookupCtx = 0; 243 bool isDependent = false; 244 if (!ObjectType.isNull()) { 245 // This nested-name-specifier occurs in a member access expression, e.g., 246 // x->B::f, and we are looking into the type of the object. 247 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist"); 248 LookupCtx = computeDeclContext(ObjectType); 249 isDependent = ObjectType->isDependentType(); 250 assert((isDependent || !ObjectType->isIncompleteType()) && 251 "Caller should have completed object type"); 252 } else if (SS.isSet()) { 253 // This nested-name-specifier occurs after another nested-name-specifier, 254 // so long into the context associated with the prior nested-name-specifier. 255 LookupCtx = computeDeclContext(SS, EnteringContext); 256 isDependent = isDependentScopeSpecifier(SS); 257 258 // The declaration context must be complete. 259 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx)) 260 return; 261 } 262 263 bool ObjectTypeSearchedInScope = false; 264 if (LookupCtx) { 265 // Perform "qualified" name lookup into the declaration context we 266 // computed, which is either the type of the base of a member access 267 // expression or the declaration context associated with a prior 268 // nested-name-specifier. 269 LookupQualifiedName(Found, LookupCtx); 270 271 if (!ObjectType.isNull() && Found.empty()) { 272 // C++ [basic.lookup.classref]p1: 273 // In a class member access expression (5.2.5), if the . or -> token is 274 // immediately followed by an identifier followed by a <, the 275 // identifier must be looked up to determine whether the < is the 276 // beginning of a template argument list (14.2) or a less-than operator. 277 // The identifier is first looked up in the class of the object 278 // expression. If the identifier is not found, it is then looked up in 279 // the context of the entire postfix-expression and shall name a class 280 // or function template. 281 if (S) LookupName(Found, S); 282 ObjectTypeSearchedInScope = true; 283 } 284 } else if (isDependent && (!S || ObjectType.isNull())) { 285 // We cannot look into a dependent object type or nested nme 286 // specifier. 287 MemberOfUnknownSpecialization = true; 288 return; 289 } else { 290 // Perform unqualified name lookup in the current scope. 291 LookupName(Found, S); 292 } 293 294 if (Found.empty() && !isDependent) { 295 // If we did not find any names, attempt to correct any typos. 296 DeclarationName Name = Found.getLookupName(); 297 if (DeclarationName Corrected = CorrectTypo(Found, S, &SS, LookupCtx, 298 false, CTC_CXXCasts)) { 299 FilterAcceptableTemplateNames(Found); 300 if (!Found.empty()) { 301 if (LookupCtx) 302 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest) 303 << Name << LookupCtx << Found.getLookupName() << SS.getRange() 304 << FixItHint::CreateReplacement(Found.getNameLoc(), 305 Found.getLookupName().getAsString()); 306 else 307 Diag(Found.getNameLoc(), diag::err_no_template_suggest) 308 << Name << Found.getLookupName() 309 << FixItHint::CreateReplacement(Found.getNameLoc(), 310 Found.getLookupName().getAsString()); 311 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>()) 312 Diag(Template->getLocation(), diag::note_previous_decl) 313 << Template->getDeclName(); 314 } 315 } else { 316 Found.clear(); 317 Found.setLookupName(Name); 318 } 319 } 320 321 FilterAcceptableTemplateNames(Found); 322 if (Found.empty()) { 323 if (isDependent) 324 MemberOfUnknownSpecialization = true; 325 return; 326 } 327 328 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) { 329 // C++ [basic.lookup.classref]p1: 330 // [...] If the lookup in the class of the object expression finds a 331 // template, the name is also looked up in the context of the entire 332 // postfix-expression and [...] 333 // 334 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(), 335 LookupOrdinaryName); 336 LookupName(FoundOuter, S); 337 FilterAcceptableTemplateNames(FoundOuter); 338 339 if (FoundOuter.empty()) { 340 // - if the name is not found, the name found in the class of the 341 // object expression is used, otherwise 342 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) { 343 // - if the name is found in the context of the entire 344 // postfix-expression and does not name a class template, the name 345 // found in the class of the object expression is used, otherwise 346 } else if (!Found.isSuppressingDiagnostics()) { 347 // - if the name found is a class template, it must refer to the same 348 // entity as the one found in the class of the object expression, 349 // otherwise the program is ill-formed. 350 if (!Found.isSingleResult() || 351 Found.getFoundDecl()->getCanonicalDecl() 352 != FoundOuter.getFoundDecl()->getCanonicalDecl()) { 353 Diag(Found.getNameLoc(), 354 diag::ext_nested_name_member_ref_lookup_ambiguous) 355 << Found.getLookupName() 356 << ObjectType; 357 Diag(Found.getRepresentativeDecl()->getLocation(), 358 diag::note_ambig_member_ref_object_type) 359 << ObjectType; 360 Diag(FoundOuter.getFoundDecl()->getLocation(), 361 diag::note_ambig_member_ref_scope); 362 363 // Recover by taking the template that we found in the object 364 // expression's type. 365 } 366 } 367 } 368} 369 370/// ActOnDependentIdExpression - Handle a dependent id-expression that 371/// was just parsed. This is only possible with an explicit scope 372/// specifier naming a dependent type. 373ExprResult 374Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS, 375 const DeclarationNameInfo &NameInfo, 376 bool isAddressOfOperand, 377 const TemplateArgumentListInfo *TemplateArgs) { 378 DeclContext *DC = getFunctionLevelDeclContext(); 379 380 if (!isAddressOfOperand && 381 isa<CXXMethodDecl>(DC) && 382 cast<CXXMethodDecl>(DC)->isInstance()) { 383 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context); 384 385 // Since the 'this' expression is synthesized, we don't need to 386 // perform the double-lookup check. 387 NamedDecl *FirstQualifierInScope = 0; 388 389 return Owned(CXXDependentScopeMemberExpr::Create(Context, 390 /*This*/ 0, ThisType, 391 /*IsArrow*/ true, 392 /*Op*/ SourceLocation(), 393 SS.getWithLocInContext(Context), 394 FirstQualifierInScope, 395 NameInfo, 396 TemplateArgs)); 397 } 398 399 return BuildDependentDeclRefExpr(SS, NameInfo, TemplateArgs); 400} 401 402ExprResult 403Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS, 404 const DeclarationNameInfo &NameInfo, 405 const TemplateArgumentListInfo *TemplateArgs) { 406 return Owned(DependentScopeDeclRefExpr::Create(Context, 407 SS.getWithLocInContext(Context), 408 NameInfo, 409 TemplateArgs)); 410} 411 412/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining 413/// that the template parameter 'PrevDecl' is being shadowed by a new 414/// declaration at location Loc. Returns true to indicate that this is 415/// an error, and false otherwise. 416bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) { 417 assert(PrevDecl->isTemplateParameter() && "Not a template parameter"); 418 419 // Microsoft Visual C++ permits template parameters to be shadowed. 420 if (getLangOptions().Microsoft) 421 return false; 422 423 // C++ [temp.local]p4: 424 // A template-parameter shall not be redeclared within its 425 // scope (including nested scopes). 426 Diag(Loc, diag::err_template_param_shadow) 427 << cast<NamedDecl>(PrevDecl)->getDeclName(); 428 Diag(PrevDecl->getLocation(), diag::note_template_param_here); 429 return true; 430} 431 432/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset 433/// the parameter D to reference the templated declaration and return a pointer 434/// to the template declaration. Otherwise, do nothing to D and return null. 435TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) { 436 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) { 437 D = Temp->getTemplatedDecl(); 438 return Temp; 439 } 440 return 0; 441} 442 443ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion( 444 SourceLocation EllipsisLoc) const { 445 assert(Kind == Template && 446 "Only template template arguments can be pack expansions here"); 447 assert(getAsTemplate().get().containsUnexpandedParameterPack() && 448 "Template template argument pack expansion without packs"); 449 ParsedTemplateArgument Result(*this); 450 Result.EllipsisLoc = EllipsisLoc; 451 return Result; 452} 453 454static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef, 455 const ParsedTemplateArgument &Arg) { 456 457 switch (Arg.getKind()) { 458 case ParsedTemplateArgument::Type: { 459 TypeSourceInfo *DI; 460 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI); 461 if (!DI) 462 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation()); 463 return TemplateArgumentLoc(TemplateArgument(T), DI); 464 } 465 466 case ParsedTemplateArgument::NonType: { 467 Expr *E = static_cast<Expr *>(Arg.getAsExpr()); 468 return TemplateArgumentLoc(TemplateArgument(E), E); 469 } 470 471 case ParsedTemplateArgument::Template: { 472 TemplateName Template = Arg.getAsTemplate().get(); 473 TemplateArgument TArg; 474 if (Arg.getEllipsisLoc().isValid()) 475 TArg = TemplateArgument(Template, llvm::Optional<unsigned int>()); 476 else 477 TArg = Template; 478 return TemplateArgumentLoc(TArg, 479 Arg.getScopeSpec().getWithLocInContext( 480 SemaRef.Context), 481 Arg.getLocation(), 482 Arg.getEllipsisLoc()); 483 } 484 } 485 486 llvm_unreachable("Unhandled parsed template argument"); 487 return TemplateArgumentLoc(); 488} 489 490/// \brief Translates template arguments as provided by the parser 491/// into template arguments used by semantic analysis. 492void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn, 493 TemplateArgumentListInfo &TemplateArgs) { 494 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I) 495 TemplateArgs.addArgument(translateTemplateArgument(*this, 496 TemplateArgsIn[I])); 497} 498 499/// ActOnTypeParameter - Called when a C++ template type parameter 500/// (e.g., "typename T") has been parsed. Typename specifies whether 501/// the keyword "typename" was used to declare the type parameter 502/// (otherwise, "class" was used), and KeyLoc is the location of the 503/// "class" or "typename" keyword. ParamName is the name of the 504/// parameter (NULL indicates an unnamed template parameter) and 505/// ParamNameLoc is the location of the parameter name (if any). 506/// If the type parameter has a default argument, it will be added 507/// later via ActOnTypeParameterDefault. 508Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis, 509 SourceLocation EllipsisLoc, 510 SourceLocation KeyLoc, 511 IdentifierInfo *ParamName, 512 SourceLocation ParamNameLoc, 513 unsigned Depth, unsigned Position, 514 SourceLocation EqualLoc, 515 ParsedType DefaultArg) { 516 assert(S->isTemplateParamScope() && 517 "Template type parameter not in template parameter scope!"); 518 bool Invalid = false; 519 520 if (ParamName) { 521 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc, 522 LookupOrdinaryName, 523 ForRedeclaration); 524 if (PrevDecl && PrevDecl->isTemplateParameter()) 525 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc, 526 PrevDecl); 527 } 528 529 SourceLocation Loc = ParamNameLoc; 530 if (!ParamName) 531 Loc = KeyLoc; 532 533 TemplateTypeParmDecl *Param 534 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(), 535 KeyLoc, Loc, Depth, Position, ParamName, 536 Typename, Ellipsis); 537 Param->setAccess(AS_public); 538 if (Invalid) 539 Param->setInvalidDecl(); 540 541 if (ParamName) { 542 // Add the template parameter into the current scope. 543 S->AddDecl(Param); 544 IdResolver.AddDecl(Param); 545 } 546 547 // C++0x [temp.param]p9: 548 // A default template-argument may be specified for any kind of 549 // template-parameter that is not a template parameter pack. 550 if (DefaultArg && Ellipsis) { 551 Diag(EqualLoc, diag::err_template_param_pack_default_arg); 552 DefaultArg = ParsedType(); 553 } 554 555 // Handle the default argument, if provided. 556 if (DefaultArg) { 557 TypeSourceInfo *DefaultTInfo; 558 GetTypeFromParser(DefaultArg, &DefaultTInfo); 559 560 assert(DefaultTInfo && "expected source information for type"); 561 562 // Check for unexpanded parameter packs. 563 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo, 564 UPPC_DefaultArgument)) 565 return Param; 566 567 // Check the template argument itself. 568 if (CheckTemplateArgument(Param, DefaultTInfo)) { 569 Param->setInvalidDecl(); 570 return Param; 571 } 572 573 Param->setDefaultArgument(DefaultTInfo, false); 574 } 575 576 return Param; 577} 578 579/// \brief Check that the type of a non-type template parameter is 580/// well-formed. 581/// 582/// \returns the (possibly-promoted) parameter type if valid; 583/// otherwise, produces a diagnostic and returns a NULL type. 584QualType 585Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) { 586 // We don't allow variably-modified types as the type of non-type template 587 // parameters. 588 if (T->isVariablyModifiedType()) { 589 Diag(Loc, diag::err_variably_modified_nontype_template_param) 590 << T; 591 return QualType(); 592 } 593 594 // C++ [temp.param]p4: 595 // 596 // A non-type template-parameter shall have one of the following 597 // (optionally cv-qualified) types: 598 // 599 // -- integral or enumeration type, 600 if (T->isIntegralOrEnumerationType() || 601 // -- pointer to object or pointer to function, 602 T->isPointerType() || 603 // -- reference to object or reference to function, 604 T->isReferenceType() || 605 // -- pointer to member, 606 T->isMemberPointerType() || 607 // -- std::nullptr_t. 608 T->isNullPtrType() || 609 // If T is a dependent type, we can't do the check now, so we 610 // assume that it is well-formed. 611 T->isDependentType()) 612 return T; 613 // C++ [temp.param]p8: 614 // 615 // A non-type template-parameter of type "array of T" or 616 // "function returning T" is adjusted to be of type "pointer to 617 // T" or "pointer to function returning T", respectively. 618 else if (T->isArrayType()) 619 // FIXME: Keep the type prior to promotion? 620 return Context.getArrayDecayedType(T); 621 else if (T->isFunctionType()) 622 // FIXME: Keep the type prior to promotion? 623 return Context.getPointerType(T); 624 625 Diag(Loc, diag::err_template_nontype_parm_bad_type) 626 << T; 627 628 return QualType(); 629} 630 631Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, 632 unsigned Depth, 633 unsigned Position, 634 SourceLocation EqualLoc, 635 Expr *Default) { 636 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 637 QualType T = TInfo->getType(); 638 639 assert(S->isTemplateParamScope() && 640 "Non-type template parameter not in template parameter scope!"); 641 bool Invalid = false; 642 643 IdentifierInfo *ParamName = D.getIdentifier(); 644 if (ParamName) { 645 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(), 646 LookupOrdinaryName, 647 ForRedeclaration); 648 if (PrevDecl && PrevDecl->isTemplateParameter()) 649 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 650 PrevDecl); 651 } 652 653 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc()); 654 if (T.isNull()) { 655 T = Context.IntTy; // Recover with an 'int' type. 656 Invalid = true; 657 } 658 659 bool IsParameterPack = D.hasEllipsis(); 660 NonTypeTemplateParmDecl *Param 661 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(), 662 D.getSourceRange().getBegin(), 663 D.getIdentifierLoc(), 664 Depth, Position, ParamName, T, 665 IsParameterPack, TInfo); 666 Param->setAccess(AS_public); 667 668 if (Invalid) 669 Param->setInvalidDecl(); 670 671 if (D.getIdentifier()) { 672 // Add the template parameter into the current scope. 673 S->AddDecl(Param); 674 IdResolver.AddDecl(Param); 675 } 676 677 // C++0x [temp.param]p9: 678 // A default template-argument may be specified for any kind of 679 // template-parameter that is not a template parameter pack. 680 if (Default && IsParameterPack) { 681 Diag(EqualLoc, diag::err_template_param_pack_default_arg); 682 Default = 0; 683 } 684 685 // Check the well-formedness of the default template argument, if provided. 686 if (Default) { 687 // Check for unexpanded parameter packs. 688 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument)) 689 return Param; 690 691 TemplateArgument Converted; 692 ExprResult DefaultRes = CheckTemplateArgument(Param, Param->getType(), Default, Converted); 693 if (DefaultRes.isInvalid()) { 694 Param->setInvalidDecl(); 695 return Param; 696 } 697 Default = DefaultRes.take(); 698 699 Param->setDefaultArgument(Default, false); 700 } 701 702 return Param; 703} 704 705/// ActOnTemplateTemplateParameter - Called when a C++ template template 706/// parameter (e.g. T in template <template <typename> class T> class array) 707/// has been parsed. S is the current scope. 708Decl *Sema::ActOnTemplateTemplateParameter(Scope* S, 709 SourceLocation TmpLoc, 710 TemplateParamsTy *Params, 711 SourceLocation EllipsisLoc, 712 IdentifierInfo *Name, 713 SourceLocation NameLoc, 714 unsigned Depth, 715 unsigned Position, 716 SourceLocation EqualLoc, 717 ParsedTemplateArgument Default) { 718 assert(S->isTemplateParamScope() && 719 "Template template parameter not in template parameter scope!"); 720 721 // Construct the parameter object. 722 bool IsParameterPack = EllipsisLoc.isValid(); 723 TemplateTemplateParmDecl *Param = 724 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(), 725 NameLoc.isInvalid()? TmpLoc : NameLoc, 726 Depth, Position, IsParameterPack, 727 Name, Params); 728 Param->setAccess(AS_public); 729 730 // If the template template parameter has a name, then link the identifier 731 // into the scope and lookup mechanisms. 732 if (Name) { 733 S->AddDecl(Param); 734 IdResolver.AddDecl(Param); 735 } 736 737 if (Params->size() == 0) { 738 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms) 739 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc()); 740 Param->setInvalidDecl(); 741 } 742 743 // C++0x [temp.param]p9: 744 // A default template-argument may be specified for any kind of 745 // template-parameter that is not a template parameter pack. 746 if (IsParameterPack && !Default.isInvalid()) { 747 Diag(EqualLoc, diag::err_template_param_pack_default_arg); 748 Default = ParsedTemplateArgument(); 749 } 750 751 if (!Default.isInvalid()) { 752 // Check only that we have a template template argument. We don't want to 753 // try to check well-formedness now, because our template template parameter 754 // might have dependent types in its template parameters, which we wouldn't 755 // be able to match now. 756 // 757 // If none of the template template parameter's template arguments mention 758 // other template parameters, we could actually perform more checking here. 759 // However, it isn't worth doing. 760 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default); 761 if (DefaultArg.getArgument().getAsTemplate().isNull()) { 762 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template) 763 << DefaultArg.getSourceRange(); 764 return Param; 765 } 766 767 // Check for unexpanded parameter packs. 768 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(), 769 DefaultArg.getArgument().getAsTemplate(), 770 UPPC_DefaultArgument)) 771 return Param; 772 773 Param->setDefaultArgument(DefaultArg, false); 774 } 775 776 return Param; 777} 778 779/// ActOnTemplateParameterList - Builds a TemplateParameterList that 780/// contains the template parameters in Params/NumParams. 781Sema::TemplateParamsTy * 782Sema::ActOnTemplateParameterList(unsigned Depth, 783 SourceLocation ExportLoc, 784 SourceLocation TemplateLoc, 785 SourceLocation LAngleLoc, 786 Decl **Params, unsigned NumParams, 787 SourceLocation RAngleLoc) { 788 if (ExportLoc.isValid()) 789 Diag(ExportLoc, diag::warn_template_export_unsupported); 790 791 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc, 792 (NamedDecl**)Params, NumParams, 793 RAngleLoc); 794} 795 796static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) { 797 if (SS.isSet()) 798 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext())); 799} 800 801DeclResult 802Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, 803 SourceLocation KWLoc, CXXScopeSpec &SS, 804 IdentifierInfo *Name, SourceLocation NameLoc, 805 AttributeList *Attr, 806 TemplateParameterList *TemplateParams, 807 AccessSpecifier AS, 808 unsigned NumOuterTemplateParamLists, 809 TemplateParameterList** OuterTemplateParamLists) { 810 assert(TemplateParams && TemplateParams->size() > 0 && 811 "No template parameters"); 812 assert(TUK != TUK_Reference && "Can only declare or define class templates"); 813 bool Invalid = false; 814 815 // Check that we can declare a template here. 816 if (CheckTemplateDeclScope(S, TemplateParams)) 817 return true; 818 819 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 820 assert(Kind != TTK_Enum && "can't build template of enumerated type"); 821 822 // There is no such thing as an unnamed class template. 823 if (!Name) { 824 Diag(KWLoc, diag::err_template_unnamed_class); 825 return true; 826 } 827 828 // Find any previous declaration with this name. 829 DeclContext *SemanticContext; 830 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName, 831 ForRedeclaration); 832 if (SS.isNotEmpty() && !SS.isInvalid()) { 833 SemanticContext = computeDeclContext(SS, true); 834 if (!SemanticContext) { 835 // FIXME: Produce a reasonable diagnostic here 836 return true; 837 } 838 839 if (RequireCompleteDeclContext(SS, SemanticContext)) 840 return true; 841 842 LookupQualifiedName(Previous, SemanticContext); 843 } else { 844 SemanticContext = CurContext; 845 LookupName(Previous, S); 846 } 847 848 if (Previous.isAmbiguous()) 849 return true; 850 851 NamedDecl *PrevDecl = 0; 852 if (Previous.begin() != Previous.end()) 853 PrevDecl = (*Previous.begin())->getUnderlyingDecl(); 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 (TUK == TUK_Friend) { 876 // C++ [namespace.memdef]p3: 877 // [...] When looking for a prior declaration of a class or a function 878 // declared as a friend, and when the name of the friend class or 879 // function is neither a qualified name nor a template-id, scopes outside 880 // the innermost enclosing namespace scope are not considered. 881 if (!SS.isSet()) { 882 DeclContext *OutermostContext = CurContext; 883 while (!OutermostContext->isFileContext()) 884 OutermostContext = OutermostContext->getLookupParent(); 885 886 if (PrevDecl && 887 (OutermostContext->Equals(PrevDecl->getDeclContext()) || 888 OutermostContext->Encloses(PrevDecl->getDeclContext()))) { 889 SemanticContext = PrevDecl->getDeclContext(); 890 } else { 891 // Declarations in outer scopes don't matter. However, the outermost 892 // context we computed is the semantic context for our new 893 // declaration. 894 PrevDecl = PrevClassTemplate = 0; 895 SemanticContext = OutermostContext; 896 } 897 } 898 899 if (CurContext->isDependentContext()) { 900 // If this is a dependent context, we don't want to link the friend 901 // class template to the template in scope, because that would perform 902 // checking of the template parameter lists that can't be performed 903 // until the outer context is instantiated. 904 PrevDecl = PrevClassTemplate = 0; 905 } 906 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S)) 907 PrevDecl = PrevClassTemplate = 0; 908 909 if (PrevClassTemplate) { 910 // Ensure that the template parameter lists are compatible. 911 if (!TemplateParameterListsAreEqual(TemplateParams, 912 PrevClassTemplate->getTemplateParameters(), 913 /*Complain=*/true, 914 TPL_TemplateMatch)) 915 return true; 916 917 // C++ [temp.class]p4: 918 // In a redeclaration, partial specialization, explicit 919 // specialization or explicit instantiation of a class template, 920 // the class-key shall agree in kind with the original class 921 // template declaration (7.1.5.3). 922 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl(); 923 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, 924 TUK == TUK_Definition, KWLoc, *Name)) { 925 Diag(KWLoc, diag::err_use_with_wrong_tag) 926 << Name 927 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName()); 928 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use); 929 Kind = PrevRecordDecl->getTagKind(); 930 } 931 932 // Check for redefinition of this class template. 933 if (TUK == TUK_Definition) { 934 if (TagDecl *Def = PrevRecordDecl->getDefinition()) { 935 Diag(NameLoc, diag::err_redefinition) << Name; 936 Diag(Def->getLocation(), diag::note_previous_definition); 937 // FIXME: Would it make sense to try to "forget" the previous 938 // definition, as part of error recovery? 939 return true; 940 } 941 } 942 } else if (PrevDecl && PrevDecl->isTemplateParameter()) { 943 // Maybe we will complain about the shadowed template parameter. 944 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl); 945 // Just pretend that we didn't see the previous declaration. 946 PrevDecl = 0; 947 } else if (PrevDecl) { 948 // C++ [temp]p5: 949 // A class template shall not have the same name as any other 950 // template, class, function, object, enumeration, enumerator, 951 // namespace, or type in the same scope (3.3), except as specified 952 // in (14.5.4). 953 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 954 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 955 return true; 956 } 957 958 // Check the template parameter list of this declaration, possibly 959 // merging in the template parameter list from the previous class 960 // template declaration. 961 if (CheckTemplateParameterList(TemplateParams, 962 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0, 963 (SS.isSet() && SemanticContext && 964 SemanticContext->isRecord() && 965 SemanticContext->isDependentContext()) 966 ? TPC_ClassTemplateMember 967 : TPC_ClassTemplate)) 968 Invalid = true; 969 970 if (SS.isSet()) { 971 // If the name of the template was qualified, we must be defining the 972 // template out-of-line. 973 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate && 974 !(TUK == TUK_Friend && CurContext->isDependentContext())) 975 Diag(NameLoc, diag::err_member_def_does_not_match) 976 << Name << SemanticContext << SS.getRange(); 977 } 978 979 CXXRecordDecl *NewClass = 980 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name, 981 PrevClassTemplate? 982 PrevClassTemplate->getTemplatedDecl() : 0, 983 /*DelayTypeCreation=*/true); 984 SetNestedNameSpecifier(NewClass, SS); 985 if (NumOuterTemplateParamLists > 0) 986 NewClass->setTemplateParameterListsInfo(Context, 987 NumOuterTemplateParamLists, 988 OuterTemplateParamLists); 989 990 ClassTemplateDecl *NewTemplate 991 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc, 992 DeclarationName(Name), TemplateParams, 993 NewClass, PrevClassTemplate); 994 NewClass->setDescribedClassTemplate(NewTemplate); 995 996 // Build the type for the class template declaration now. 997 QualType T = NewTemplate->getInjectedClassNameSpecialization(); 998 T = Context.getInjectedClassNameType(NewClass, T); 999 assert(T->isDependentType() && "Class template type is not dependent?"); 1000 (void)T; 1001 1002 // If we are providing an explicit specialization of a member that is a 1003 // class template, make a note of that. 1004 if (PrevClassTemplate && 1005 PrevClassTemplate->getInstantiatedFromMemberTemplate()) 1006 PrevClassTemplate->setMemberSpecialization(); 1007 1008 // Set the access specifier. 1009 if (!Invalid && TUK != TUK_Friend) 1010 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS); 1011 1012 // Set the lexical context of these templates 1013 NewClass->setLexicalDeclContext(CurContext); 1014 NewTemplate->setLexicalDeclContext(CurContext); 1015 1016 if (TUK == TUK_Definition) 1017 NewClass->startDefinition(); 1018 1019 if (Attr) 1020 ProcessDeclAttributeList(S, NewClass, Attr); 1021 1022 if (TUK != TUK_Friend) 1023 PushOnScopeChains(NewTemplate, S); 1024 else { 1025 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) { 1026 NewTemplate->setAccess(PrevClassTemplate->getAccess()); 1027 NewClass->setAccess(PrevClassTemplate->getAccess()); 1028 } 1029 1030 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */ 1031 PrevClassTemplate != NULL); 1032 1033 // Friend templates are visible in fairly strange ways. 1034 if (!CurContext->isDependentContext()) { 1035 DeclContext *DC = SemanticContext->getRedeclContext(); 1036 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false); 1037 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 1038 PushOnScopeChains(NewTemplate, EnclosingScope, 1039 /* AddToContext = */ false); 1040 } 1041 1042 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, 1043 NewClass->getLocation(), 1044 NewTemplate, 1045 /*FIXME:*/NewClass->getLocation()); 1046 Friend->setAccess(AS_public); 1047 CurContext->addDecl(Friend); 1048 } 1049 1050 if (Invalid) { 1051 NewTemplate->setInvalidDecl(); 1052 NewClass->setInvalidDecl(); 1053 } 1054 return NewTemplate; 1055} 1056 1057/// \brief Diagnose the presence of a default template argument on a 1058/// template parameter, which is ill-formed in certain contexts. 1059/// 1060/// \returns true if the default template argument should be dropped. 1061static bool DiagnoseDefaultTemplateArgument(Sema &S, 1062 Sema::TemplateParamListContext TPC, 1063 SourceLocation ParamLoc, 1064 SourceRange DefArgRange) { 1065 switch (TPC) { 1066 case Sema::TPC_ClassTemplate: 1067 case Sema::TPC_TypeAliasTemplate: 1068 return false; 1069 1070 case Sema::TPC_FunctionTemplate: 1071 case Sema::TPC_FriendFunctionTemplateDefinition: 1072 // C++ [temp.param]p9: 1073 // A default template-argument shall not be specified in a 1074 // function template declaration or a function template 1075 // definition [...] 1076 // If a friend function template declaration specifies a default 1077 // template-argument, that declaration shall be a definition and shall be 1078 // the only declaration of the function template in the translation unit. 1079 // (C++98/03 doesn't have this wording; see DR226). 1080 if (!S.getLangOptions().CPlusPlus0x) 1081 S.Diag(ParamLoc, 1082 diag::ext_template_parameter_default_in_function_template) 1083 << DefArgRange; 1084 return false; 1085 1086 case Sema::TPC_ClassTemplateMember: 1087 // C++0x [temp.param]p9: 1088 // A default template-argument shall not be specified in the 1089 // template-parameter-lists of the definition of a member of a 1090 // class template that appears outside of the member's class. 1091 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member) 1092 << DefArgRange; 1093 return true; 1094 1095 case Sema::TPC_FriendFunctionTemplate: 1096 // C++ [temp.param]p9: 1097 // A default template-argument shall not be specified in a 1098 // friend template declaration. 1099 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template) 1100 << DefArgRange; 1101 return true; 1102 1103 // FIXME: C++0x [temp.param]p9 allows default template-arguments 1104 // for friend function templates if there is only a single 1105 // declaration (and it is a definition). Strange! 1106 } 1107 1108 return false; 1109} 1110 1111/// \brief Check for unexpanded parameter packs within the template parameters 1112/// of a template template parameter, recursively. 1113static bool DiagnoseUnexpandedParameterPacks(Sema &S, 1114 TemplateTemplateParmDecl *TTP) { 1115 TemplateParameterList *Params = TTP->getTemplateParameters(); 1116 for (unsigned I = 0, N = Params->size(); I != N; ++I) { 1117 NamedDecl *P = Params->getParam(I); 1118 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) { 1119 if (S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(), 1120 NTTP->getTypeSourceInfo(), 1121 Sema::UPPC_NonTypeTemplateParameterType)) 1122 return true; 1123 1124 continue; 1125 } 1126 1127 if (TemplateTemplateParmDecl *InnerTTP 1128 = dyn_cast<TemplateTemplateParmDecl>(P)) 1129 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP)) 1130 return true; 1131 } 1132 1133 return false; 1134} 1135 1136/// \brief Checks the validity of a template parameter list, possibly 1137/// considering the template parameter list from a previous 1138/// declaration. 1139/// 1140/// If an "old" template parameter list is provided, it must be 1141/// equivalent (per TemplateParameterListsAreEqual) to the "new" 1142/// template parameter list. 1143/// 1144/// \param NewParams Template parameter list for a new template 1145/// declaration. This template parameter list will be updated with any 1146/// default arguments that are carried through from the previous 1147/// template parameter list. 1148/// 1149/// \param OldParams If provided, template parameter list from a 1150/// previous declaration of the same template. Default template 1151/// arguments will be merged from the old template parameter list to 1152/// the new template parameter list. 1153/// 1154/// \param TPC Describes the context in which we are checking the given 1155/// template parameter list. 1156/// 1157/// \returns true if an error occurred, false otherwise. 1158bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams, 1159 TemplateParameterList *OldParams, 1160 TemplateParamListContext TPC) { 1161 bool Invalid = false; 1162 1163 // C++ [temp.param]p10: 1164 // The set of default template-arguments available for use with a 1165 // template declaration or definition is obtained by merging the 1166 // default arguments from the definition (if in scope) and all 1167 // declarations in scope in the same way default function 1168 // arguments are (8.3.6). 1169 bool SawDefaultArgument = false; 1170 SourceLocation PreviousDefaultArgLoc; 1171 1172 bool SawParameterPack = false; 1173 SourceLocation ParameterPackLoc; 1174 1175 // Dummy initialization to avoid warnings. 1176 TemplateParameterList::iterator OldParam = NewParams->end(); 1177 if (OldParams) 1178 OldParam = OldParams->begin(); 1179 1180 bool RemoveDefaultArguments = false; 1181 for (TemplateParameterList::iterator NewParam = NewParams->begin(), 1182 NewParamEnd = NewParams->end(); 1183 NewParam != NewParamEnd; ++NewParam) { 1184 // Variables used to diagnose redundant default arguments 1185 bool RedundantDefaultArg = false; 1186 SourceLocation OldDefaultLoc; 1187 SourceLocation NewDefaultLoc; 1188 1189 // Variables used to diagnose missing default arguments 1190 bool MissingDefaultArg = false; 1191 1192 // C++0x [temp.param]p11: 1193 // If a template parameter of a primary class template or alias template 1194 // is a template parameter pack, it shall be the last template parameter. 1195 if (SawParameterPack && 1196 (TPC == TPC_ClassTemplate || TPC == TPC_TypeAliasTemplate)) { 1197 Diag(ParameterPackLoc, 1198 diag::err_template_param_pack_must_be_last_template_parameter); 1199 Invalid = true; 1200 } 1201 1202 if (TemplateTypeParmDecl *NewTypeParm 1203 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) { 1204 // Check the presence of a default argument here. 1205 if (NewTypeParm->hasDefaultArgument() && 1206 DiagnoseDefaultTemplateArgument(*this, TPC, 1207 NewTypeParm->getLocation(), 1208 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc() 1209 .getSourceRange())) 1210 NewTypeParm->removeDefaultArgument(); 1211 1212 // Merge default arguments for template type parameters. 1213 TemplateTypeParmDecl *OldTypeParm 1214 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0; 1215 1216 if (NewTypeParm->isParameterPack()) { 1217 assert(!NewTypeParm->hasDefaultArgument() && 1218 "Parameter packs can't have a default argument!"); 1219 SawParameterPack = true; 1220 ParameterPackLoc = NewTypeParm->getLocation(); 1221 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() && 1222 NewTypeParm->hasDefaultArgument()) { 1223 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc(); 1224 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc(); 1225 SawDefaultArgument = true; 1226 RedundantDefaultArg = true; 1227 PreviousDefaultArgLoc = NewDefaultLoc; 1228 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) { 1229 // Merge the default argument from the old declaration to the 1230 // new declaration. 1231 SawDefaultArgument = true; 1232 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(), 1233 true); 1234 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc(); 1235 } else if (NewTypeParm->hasDefaultArgument()) { 1236 SawDefaultArgument = true; 1237 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc(); 1238 } else if (SawDefaultArgument) 1239 MissingDefaultArg = true; 1240 } else if (NonTypeTemplateParmDecl *NewNonTypeParm 1241 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) { 1242 // Check for unexpanded parameter packs. 1243 if (DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(), 1244 NewNonTypeParm->getTypeSourceInfo(), 1245 UPPC_NonTypeTemplateParameterType)) { 1246 Invalid = true; 1247 continue; 1248 } 1249 1250 // Check the presence of a default argument here. 1251 if (NewNonTypeParm->hasDefaultArgument() && 1252 DiagnoseDefaultTemplateArgument(*this, TPC, 1253 NewNonTypeParm->getLocation(), 1254 NewNonTypeParm->getDefaultArgument()->getSourceRange())) { 1255 NewNonTypeParm->removeDefaultArgument(); 1256 } 1257 1258 // Merge default arguments for non-type template parameters 1259 NonTypeTemplateParmDecl *OldNonTypeParm 1260 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0; 1261 if (NewNonTypeParm->isParameterPack()) { 1262 assert(!NewNonTypeParm->hasDefaultArgument() && 1263 "Parameter packs can't have a default argument!"); 1264 SawParameterPack = true; 1265 ParameterPackLoc = NewNonTypeParm->getLocation(); 1266 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() && 1267 NewNonTypeParm->hasDefaultArgument()) { 1268 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc(); 1269 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc(); 1270 SawDefaultArgument = true; 1271 RedundantDefaultArg = true; 1272 PreviousDefaultArgLoc = NewDefaultLoc; 1273 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) { 1274 // Merge the default argument from the old declaration to the 1275 // new declaration. 1276 SawDefaultArgument = true; 1277 // FIXME: We need to create a new kind of "default argument" 1278 // expression that points to a previous non-type template 1279 // parameter. 1280 NewNonTypeParm->setDefaultArgument( 1281 OldNonTypeParm->getDefaultArgument(), 1282 /*Inherited=*/ true); 1283 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc(); 1284 } else if (NewNonTypeParm->hasDefaultArgument()) { 1285 SawDefaultArgument = true; 1286 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc(); 1287 } else if (SawDefaultArgument) 1288 MissingDefaultArg = true; 1289 } else { 1290 // Check the presence of a default argument here. 1291 TemplateTemplateParmDecl *NewTemplateParm 1292 = cast<TemplateTemplateParmDecl>(*NewParam); 1293 1294 // Check for unexpanded parameter packs, recursively. 1295 if (DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) { 1296 Invalid = true; 1297 continue; 1298 } 1299 1300 if (NewTemplateParm->hasDefaultArgument() && 1301 DiagnoseDefaultTemplateArgument(*this, TPC, 1302 NewTemplateParm->getLocation(), 1303 NewTemplateParm->getDefaultArgument().getSourceRange())) 1304 NewTemplateParm->removeDefaultArgument(); 1305 1306 // Merge default arguments for template template parameters 1307 TemplateTemplateParmDecl *OldTemplateParm 1308 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0; 1309 if (NewTemplateParm->isParameterPack()) { 1310 assert(!NewTemplateParm->hasDefaultArgument() && 1311 "Parameter packs can't have a default argument!"); 1312 SawParameterPack = true; 1313 ParameterPackLoc = NewTemplateParm->getLocation(); 1314 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() && 1315 NewTemplateParm->hasDefaultArgument()) { 1316 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation(); 1317 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation(); 1318 SawDefaultArgument = true; 1319 RedundantDefaultArg = true; 1320 PreviousDefaultArgLoc = NewDefaultLoc; 1321 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) { 1322 // Merge the default argument from the old declaration to the 1323 // new declaration. 1324 SawDefaultArgument = true; 1325 // FIXME: We need to create a new kind of "default argument" expression 1326 // that points to a previous template template parameter. 1327 NewTemplateParm->setDefaultArgument( 1328 OldTemplateParm->getDefaultArgument(), 1329 /*Inherited=*/ true); 1330 PreviousDefaultArgLoc 1331 = OldTemplateParm->getDefaultArgument().getLocation(); 1332 } else if (NewTemplateParm->hasDefaultArgument()) { 1333 SawDefaultArgument = true; 1334 PreviousDefaultArgLoc 1335 = NewTemplateParm->getDefaultArgument().getLocation(); 1336 } else if (SawDefaultArgument) 1337 MissingDefaultArg = true; 1338 } 1339 1340 if (RedundantDefaultArg) { 1341 // C++ [temp.param]p12: 1342 // A template-parameter shall not be given default arguments 1343 // by two different declarations in the same scope. 1344 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition); 1345 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg); 1346 Invalid = true; 1347 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) { 1348 // C++ [temp.param]p11: 1349 // If a template-parameter of a class template has a default 1350 // template-argument, each subsequent template-parameter shall either 1351 // have a default template-argument supplied or be a template parameter 1352 // pack. 1353 Diag((*NewParam)->getLocation(), 1354 diag::err_template_param_default_arg_missing); 1355 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg); 1356 Invalid = true; 1357 RemoveDefaultArguments = true; 1358 } 1359 1360 // If we have an old template parameter list that we're merging 1361 // in, move on to the next parameter. 1362 if (OldParams) 1363 ++OldParam; 1364 } 1365 1366 // We were missing some default arguments at the end of the list, so remove 1367 // all of the default arguments. 1368 if (RemoveDefaultArguments) { 1369 for (TemplateParameterList::iterator NewParam = NewParams->begin(), 1370 NewParamEnd = NewParams->end(); 1371 NewParam != NewParamEnd; ++NewParam) { 1372 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam)) 1373 TTP->removeDefaultArgument(); 1374 else if (NonTypeTemplateParmDecl *NTTP 1375 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) 1376 NTTP->removeDefaultArgument(); 1377 else 1378 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument(); 1379 } 1380 } 1381 1382 return Invalid; 1383} 1384 1385namespace { 1386 1387/// A class which looks for a use of a certain level of template 1388/// parameter. 1389struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> { 1390 typedef RecursiveASTVisitor<DependencyChecker> super; 1391 1392 unsigned Depth; 1393 bool Match; 1394 1395 DependencyChecker(TemplateParameterList *Params) : Match(false) { 1396 NamedDecl *ND = Params->getParam(0); 1397 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) { 1398 Depth = PD->getDepth(); 1399 } else if (NonTypeTemplateParmDecl *PD = 1400 dyn_cast<NonTypeTemplateParmDecl>(ND)) { 1401 Depth = PD->getDepth(); 1402 } else { 1403 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth(); 1404 } 1405 } 1406 1407 bool Matches(unsigned ParmDepth) { 1408 if (ParmDepth >= Depth) { 1409 Match = true; 1410 return true; 1411 } 1412 return false; 1413 } 1414 1415 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) { 1416 return !Matches(T->getDepth()); 1417 } 1418 1419 bool TraverseTemplateName(TemplateName N) { 1420 if (TemplateTemplateParmDecl *PD = 1421 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl())) 1422 if (Matches(PD->getDepth())) return false; 1423 return super::TraverseTemplateName(N); 1424 } 1425 1426 bool VisitDeclRefExpr(DeclRefExpr *E) { 1427 if (NonTypeTemplateParmDecl *PD = 1428 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl())) { 1429 if (PD->getDepth() == Depth) { 1430 Match = true; 1431 return false; 1432 } 1433 } 1434 return super::VisitDeclRefExpr(E); 1435 } 1436 1437 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) { 1438 return TraverseType(T->getInjectedSpecializationType()); 1439 } 1440}; 1441} 1442 1443/// Determines whether a given type depends on the given parameter 1444/// list. 1445static bool 1446DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) { 1447 DependencyChecker Checker(Params); 1448 Checker.TraverseType(T); 1449 return Checker.Match; 1450} 1451 1452// Find the source range corresponding to the named type in the given 1453// nested-name-specifier, if any. 1454static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context, 1455 QualType T, 1456 const CXXScopeSpec &SS) { 1457 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data()); 1458 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) { 1459 if (const Type *CurType = NNS->getAsType()) { 1460 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0))) 1461 return NNSLoc.getTypeLoc().getSourceRange(); 1462 } else 1463 break; 1464 1465 NNSLoc = NNSLoc.getPrefix(); 1466 } 1467 1468 return SourceRange(); 1469} 1470 1471/// \brief Match the given template parameter lists to the given scope 1472/// specifier, returning the template parameter list that applies to the 1473/// name. 1474/// 1475/// \param DeclStartLoc the start of the declaration that has a scope 1476/// specifier or a template parameter list. 1477/// 1478/// \param DeclLoc The location of the declaration itself. 1479/// 1480/// \param SS the scope specifier that will be matched to the given template 1481/// parameter lists. This scope specifier precedes a qualified name that is 1482/// being declared. 1483/// 1484/// \param ParamLists the template parameter lists, from the outermost to the 1485/// innermost template parameter lists. 1486/// 1487/// \param NumParamLists the number of template parameter lists in ParamLists. 1488/// 1489/// \param IsFriend Whether to apply the slightly different rules for 1490/// matching template parameters to scope specifiers in friend 1491/// declarations. 1492/// 1493/// \param IsExplicitSpecialization will be set true if the entity being 1494/// declared is an explicit specialization, false otherwise. 1495/// 1496/// \returns the template parameter list, if any, that corresponds to the 1497/// name that is preceded by the scope specifier @p SS. This template 1498/// parameter list may have template parameters (if we're declaring a 1499/// template) or may have no template parameters (if we're declaring a 1500/// template specialization), or may be NULL (if what we're declaring isn't 1501/// itself a template). 1502TemplateParameterList * 1503Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, 1504 SourceLocation DeclLoc, 1505 const CXXScopeSpec &SS, 1506 TemplateParameterList **ParamLists, 1507 unsigned NumParamLists, 1508 bool IsFriend, 1509 bool &IsExplicitSpecialization, 1510 bool &Invalid) { 1511 IsExplicitSpecialization = false; 1512 Invalid = false; 1513 1514 // The sequence of nested types to which we will match up the template 1515 // parameter lists. We first build this list by starting with the type named 1516 // by the nested-name-specifier and walking out until we run out of types. 1517 llvm::SmallVector<QualType, 4> NestedTypes; 1518 QualType T; 1519 if (SS.getScopeRep()) { 1520 if (CXXRecordDecl *Record 1521 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true))) 1522 T = Context.getTypeDeclType(Record); 1523 else 1524 T = QualType(SS.getScopeRep()->getAsType(), 0); 1525 } 1526 1527 // If we found an explicit specialization that prevents us from needing 1528 // 'template<>' headers, this will be set to the location of that 1529 // explicit specialization. 1530 SourceLocation ExplicitSpecLoc; 1531 1532 while (!T.isNull()) { 1533 NestedTypes.push_back(T); 1534 1535 // Retrieve the parent of a record type. 1536 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) { 1537 // If this type is an explicit specialization, we're done. 1538 if (ClassTemplateSpecializationDecl *Spec 1539 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) { 1540 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) && 1541 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) { 1542 ExplicitSpecLoc = Spec->getLocation(); 1543 break; 1544 } 1545 } else if (Record->getTemplateSpecializationKind() 1546 == TSK_ExplicitSpecialization) { 1547 ExplicitSpecLoc = Record->getLocation(); 1548 break; 1549 } 1550 1551 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent())) 1552 T = Context.getTypeDeclType(Parent); 1553 else 1554 T = QualType(); 1555 continue; 1556 } 1557 1558 if (const TemplateSpecializationType *TST 1559 = T->getAs<TemplateSpecializationType>()) { 1560 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) { 1561 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext())) 1562 T = Context.getTypeDeclType(Parent); 1563 else 1564 T = QualType(); 1565 continue; 1566 } 1567 } 1568 1569 // Look one step prior in a dependent template specialization type. 1570 if (const DependentTemplateSpecializationType *DependentTST 1571 = T->getAs<DependentTemplateSpecializationType>()) { 1572 if (NestedNameSpecifier *NNS = DependentTST->getQualifier()) 1573 T = QualType(NNS->getAsType(), 0); 1574 else 1575 T = QualType(); 1576 continue; 1577 } 1578 1579 // Look one step prior in a dependent name type. 1580 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){ 1581 if (NestedNameSpecifier *NNS = DependentName->getQualifier()) 1582 T = QualType(NNS->getAsType(), 0); 1583 else 1584 T = QualType(); 1585 continue; 1586 } 1587 1588 // Retrieve the parent of an enumeration type. 1589 if (const EnumType *EnumT = T->getAs<EnumType>()) { 1590 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization 1591 // check here. 1592 EnumDecl *Enum = EnumT->getDecl(); 1593 1594 // Get to the parent type. 1595 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent())) 1596 T = Context.getTypeDeclType(Parent); 1597 else 1598 T = QualType(); 1599 continue; 1600 } 1601 1602 T = QualType(); 1603 } 1604 // Reverse the nested types list, since we want to traverse from the outermost 1605 // to the innermost while checking template-parameter-lists. 1606 std::reverse(NestedTypes.begin(), NestedTypes.end()); 1607 1608 // C++0x [temp.expl.spec]p17: 1609 // A member or a member template may be nested within many 1610 // enclosing class templates. In an explicit specialization for 1611 // such a member, the member declaration shall be preceded by a 1612 // template<> for each enclosing class template that is 1613 // explicitly specialized. 1614 bool SawNonEmptyTemplateParameterList = false; 1615 unsigned ParamIdx = 0; 1616 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes; 1617 ++TypeIdx) { 1618 T = NestedTypes[TypeIdx]; 1619 1620 // Whether we expect a 'template<>' header. 1621 bool NeedEmptyTemplateHeader = false; 1622 1623 // Whether we expect a template header with parameters. 1624 bool NeedNonemptyTemplateHeader = false; 1625 1626 // For a dependent type, the set of template parameters that we 1627 // expect to see. 1628 TemplateParameterList *ExpectedTemplateParams = 0; 1629 1630 // C++0x [temp.expl.spec]p15: 1631 // A member or a member template may be nested within many enclosing 1632 // class templates. In an explicit specialization for such a member, the 1633 // member declaration shall be preceded by a template<> for each 1634 // enclosing class template that is explicitly specialized. 1635 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) { 1636 if (ClassTemplatePartialSpecializationDecl *Partial 1637 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) { 1638 ExpectedTemplateParams = Partial->getTemplateParameters(); 1639 NeedNonemptyTemplateHeader = true; 1640 } else if (Record->isDependentType()) { 1641 if (Record->getDescribedClassTemplate()) { 1642 ExpectedTemplateParams = Record->getDescribedClassTemplate() 1643 ->getTemplateParameters(); 1644 NeedNonemptyTemplateHeader = true; 1645 } 1646 } else if (ClassTemplateSpecializationDecl *Spec 1647 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) { 1648 // C++0x [temp.expl.spec]p4: 1649 // Members of an explicitly specialized class template are defined 1650 // in the same manner as members of normal classes, and not using 1651 // the template<> syntax. 1652 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization) 1653 NeedEmptyTemplateHeader = true; 1654 else 1655 continue; 1656 } else if (Record->getTemplateSpecializationKind()) { 1657 if (Record->getTemplateSpecializationKind() 1658 != TSK_ExplicitSpecialization && 1659 TypeIdx == NumTypes - 1) 1660 IsExplicitSpecialization = true; 1661 1662 continue; 1663 } 1664 } else if (const TemplateSpecializationType *TST 1665 = T->getAs<TemplateSpecializationType>()) { 1666 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) { 1667 ExpectedTemplateParams = Template->getTemplateParameters(); 1668 NeedNonemptyTemplateHeader = true; 1669 } 1670 } else if (T->getAs<DependentTemplateSpecializationType>()) { 1671 // FIXME: We actually could/should check the template arguments here 1672 // against the corresponding template parameter list. 1673 NeedNonemptyTemplateHeader = false; 1674 } 1675 1676 // C++ [temp.expl.spec]p16: 1677 // In an explicit specialization declaration for a member of a class 1678 // template or a member template that ap- pears in namespace scope, the 1679 // member template and some of its enclosing class templates may remain 1680 // unspecialized, except that the declaration shall not explicitly 1681 // specialize a class member template if its en- closing class templates 1682 // are not explicitly specialized as well. 1683 if (ParamIdx < NumParamLists) { 1684 if (ParamLists[ParamIdx]->size() == 0) { 1685 if (SawNonEmptyTemplateParameterList) { 1686 Diag(DeclLoc, diag::err_specialize_member_of_template) 1687 << ParamLists[ParamIdx]->getSourceRange(); 1688 Invalid = true; 1689 IsExplicitSpecialization = false; 1690 return 0; 1691 } 1692 } else 1693 SawNonEmptyTemplateParameterList = true; 1694 } 1695 1696 if (NeedEmptyTemplateHeader) { 1697 // If we're on the last of the types, and we need a 'template<>' header 1698 // here, then it's an explicit specialization. 1699 if (TypeIdx == NumTypes - 1) 1700 IsExplicitSpecialization = true; 1701 1702 if (ParamIdx < NumParamLists) { 1703 if (ParamLists[ParamIdx]->size() > 0) { 1704 // The header has template parameters when it shouldn't. Complain. 1705 Diag(ParamLists[ParamIdx]->getTemplateLoc(), 1706 diag::err_template_param_list_matches_nontemplate) 1707 << T 1708 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(), 1709 ParamLists[ParamIdx]->getRAngleLoc()) 1710 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS); 1711 Invalid = true; 1712 return 0; 1713 } 1714 1715 // Consume this template header. 1716 ++ParamIdx; 1717 continue; 1718 } 1719 1720 if (!IsFriend) { 1721 // We don't have a template header, but we should. 1722 SourceLocation ExpectedTemplateLoc; 1723 if (NumParamLists > 0) 1724 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc(); 1725 else 1726 ExpectedTemplateLoc = DeclStartLoc; 1727 1728 Diag(DeclLoc, diag::err_template_spec_needs_header) 1729 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS) 1730 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> "); 1731 } 1732 1733 continue; 1734 } 1735 1736 if (NeedNonemptyTemplateHeader) { 1737 // In friend declarations we can have template-ids which don't 1738 // depend on the corresponding template parameter lists. But 1739 // assume that empty parameter lists are supposed to match this 1740 // template-id. 1741 if (IsFriend && T->isDependentType()) { 1742 if (ParamIdx < NumParamLists && 1743 DependsOnTemplateParameters(T, ParamLists[ParamIdx])) 1744 ExpectedTemplateParams = 0; 1745 else 1746 continue; 1747 } 1748 1749 if (ParamIdx < NumParamLists) { 1750 // Check the template parameter list, if we can. 1751 if (ExpectedTemplateParams && 1752 !TemplateParameterListsAreEqual(ParamLists[ParamIdx], 1753 ExpectedTemplateParams, 1754 true, TPL_TemplateMatch)) 1755 Invalid = true; 1756 1757 if (!Invalid && 1758 CheckTemplateParameterList(ParamLists[ParamIdx], 0, 1759 TPC_ClassTemplateMember)) 1760 Invalid = true; 1761 1762 ++ParamIdx; 1763 continue; 1764 } 1765 1766 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters) 1767 << T 1768 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS); 1769 Invalid = true; 1770 continue; 1771 } 1772 } 1773 1774 // If there were at least as many template-ids as there were template 1775 // parameter lists, then there are no template parameter lists remaining for 1776 // the declaration itself. 1777 if (ParamIdx >= NumParamLists) 1778 return 0; 1779 1780 // If there were too many template parameter lists, complain about that now. 1781 if (ParamIdx < NumParamLists - 1) { 1782 bool HasAnyExplicitSpecHeader = false; 1783 bool AllExplicitSpecHeaders = true; 1784 for (unsigned I = ParamIdx; I != NumParamLists - 1; ++I) { 1785 if (ParamLists[I]->size() == 0) 1786 HasAnyExplicitSpecHeader = true; 1787 else 1788 AllExplicitSpecHeaders = false; 1789 } 1790 1791 Diag(ParamLists[ParamIdx]->getTemplateLoc(), 1792 AllExplicitSpecHeaders? diag::warn_template_spec_extra_headers 1793 : diag::err_template_spec_extra_headers) 1794 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(), 1795 ParamLists[NumParamLists - 2]->getRAngleLoc()); 1796 1797 // If there was a specialization somewhere, such that 'template<>' is 1798 // not required, and there were any 'template<>' headers, note where the 1799 // specialization occurred. 1800 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader) 1801 Diag(ExplicitSpecLoc, 1802 diag::note_explicit_template_spec_does_not_need_header) 1803 << NestedTypes.back(); 1804 1805 // We have a template parameter list with no corresponding scope, which 1806 // means that the resulting template declaration can't be instantiated 1807 // properly (we'll end up with dependent nodes when we shouldn't). 1808 if (!AllExplicitSpecHeaders) 1809 Invalid = true; 1810 } 1811 1812 // C++ [temp.expl.spec]p16: 1813 // In an explicit specialization declaration for a member of a class 1814 // template or a member template that ap- pears in namespace scope, the 1815 // member template and some of its enclosing class templates may remain 1816 // unspecialized, except that the declaration shall not explicitly 1817 // specialize a class member template if its en- closing class templates 1818 // are not explicitly specialized as well. 1819 if (ParamLists[NumParamLists - 1]->size() == 0 && 1820 SawNonEmptyTemplateParameterList) { 1821 Diag(DeclLoc, diag::err_specialize_member_of_template) 1822 << ParamLists[ParamIdx]->getSourceRange(); 1823 Invalid = true; 1824 IsExplicitSpecialization = false; 1825 return 0; 1826 } 1827 1828 // Return the last template parameter list, which corresponds to the 1829 // entity being declared. 1830 return ParamLists[NumParamLists - 1]; 1831} 1832 1833void Sema::NoteAllFoundTemplates(TemplateName Name) { 1834 if (TemplateDecl *Template = Name.getAsTemplateDecl()) { 1835 Diag(Template->getLocation(), diag::note_template_declared_here) 1836 << (isa<FunctionTemplateDecl>(Template)? 0 1837 : isa<ClassTemplateDecl>(Template)? 1 1838 : isa<TypeAliasTemplateDecl>(Template)? 2 1839 : 3) 1840 << Template->getDeclName(); 1841 return; 1842 } 1843 1844 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) { 1845 for (OverloadedTemplateStorage::iterator I = OST->begin(), 1846 IEnd = OST->end(); 1847 I != IEnd; ++I) 1848 Diag((*I)->getLocation(), diag::note_template_declared_here) 1849 << 0 << (*I)->getDeclName(); 1850 1851 return; 1852 } 1853} 1854 1855 1856QualType Sema::CheckTemplateIdType(TemplateName Name, 1857 SourceLocation TemplateLoc, 1858 TemplateArgumentListInfo &TemplateArgs) { 1859 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 1860 if (DTN && DTN->isIdentifier()) 1861 // When building a template-id where the template-name is dependent, 1862 // assume the template is a type template. Either our assumption is 1863 // correct, or the code is ill-formed and will be diagnosed when the 1864 // dependent name is substituted. 1865 return Context.getDependentTemplateSpecializationType(ETK_None, 1866 DTN->getQualifier(), 1867 DTN->getIdentifier(), 1868 TemplateArgs); 1869 1870 TemplateDecl *Template = Name.getAsTemplateDecl(); 1871 if (!Template || isa<FunctionTemplateDecl>(Template)) { 1872 // We might have a substituted template template parameter pack. If so, 1873 // build a template specialization type for it. 1874 if (Name.getAsSubstTemplateTemplateParmPack()) 1875 return Context.getTemplateSpecializationType(Name, TemplateArgs); 1876 1877 Diag(TemplateLoc, diag::err_template_id_not_a_type) 1878 << Name; 1879 NoteAllFoundTemplates(Name); 1880 return QualType(); 1881 } 1882 1883 // Check that the template argument list is well-formed for this 1884 // template. 1885 llvm::SmallVector<TemplateArgument, 4> Converted; 1886 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs, 1887 false, Converted)) 1888 return QualType(); 1889 1890 assert((Converted.size() == Template->getTemplateParameters()->size()) && 1891 "Converted template argument list is too short!"); 1892 1893 QualType CanonType; 1894 1895 if (TypeAliasTemplateDecl *AliasTemplate 1896 = dyn_cast<TypeAliasTemplateDecl>(Template)) { 1897 // Find the canonical type for this type alias template specialization. 1898 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl(); 1899 if (Pattern->isInvalidDecl()) 1900 return QualType(); 1901 1902 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, 1903 Converted.data(), Converted.size()); 1904 1905 // Only substitute for the innermost template argument list. 1906 MultiLevelTemplateArgumentList TemplateArgLists; 1907 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs); 1908 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth(); 1909 for (unsigned I = 0; I < Depth; ++I) 1910 TemplateArgLists.addOuterTemplateArguments(0, 0); 1911 1912 InstantiatingTemplate Inst(*this, TemplateLoc, Template); 1913 CanonType = SubstType(Pattern->getUnderlyingType(), 1914 TemplateArgLists, AliasTemplate->getLocation(), 1915 AliasTemplate->getDeclName()); 1916 if (CanonType.isNull()) 1917 return QualType(); 1918 } else if (Name.isDependent() || 1919 TemplateSpecializationType::anyDependentTemplateArguments( 1920 TemplateArgs)) { 1921 // This class template specialization is a dependent 1922 // type. Therefore, its canonical type is another class template 1923 // specialization type that contains all of the converted 1924 // arguments in canonical form. This ensures that, e.g., A<T> and 1925 // A<T, T> have identical types when A is declared as: 1926 // 1927 // template<typename T, typename U = T> struct A; 1928 TemplateName CanonName = Context.getCanonicalTemplateName(Name); 1929 CanonType = Context.getTemplateSpecializationType(CanonName, 1930 Converted.data(), 1931 Converted.size()); 1932 1933 // FIXME: CanonType is not actually the canonical type, and unfortunately 1934 // it is a TemplateSpecializationType that we will never use again. 1935 // In the future, we need to teach getTemplateSpecializationType to only 1936 // build the canonical type and return that to us. 1937 CanonType = Context.getCanonicalType(CanonType); 1938 1939 // This might work out to be a current instantiation, in which 1940 // case the canonical type needs to be the InjectedClassNameType. 1941 // 1942 // TODO: in theory this could be a simple hashtable lookup; most 1943 // changes to CurContext don't change the set of current 1944 // instantiations. 1945 if (isa<ClassTemplateDecl>(Template)) { 1946 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) { 1947 // If we get out to a namespace, we're done. 1948 if (Ctx->isFileContext()) break; 1949 1950 // If this isn't a record, keep looking. 1951 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx); 1952 if (!Record) continue; 1953 1954 // Look for one of the two cases with InjectedClassNameTypes 1955 // and check whether it's the same template. 1956 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) && 1957 !Record->getDescribedClassTemplate()) 1958 continue; 1959 1960 // Fetch the injected class name type and check whether its 1961 // injected type is equal to the type we just built. 1962 QualType ICNT = Context.getTypeDeclType(Record); 1963 QualType Injected = cast<InjectedClassNameType>(ICNT) 1964 ->getInjectedSpecializationType(); 1965 1966 if (CanonType != Injected->getCanonicalTypeInternal()) 1967 continue; 1968 1969 // If so, the canonical type of this TST is the injected 1970 // class name type of the record we just found. 1971 assert(ICNT.isCanonical()); 1972 CanonType = ICNT; 1973 break; 1974 } 1975 } 1976 } else if (ClassTemplateDecl *ClassTemplate 1977 = dyn_cast<ClassTemplateDecl>(Template)) { 1978 // Find the class template specialization declaration that 1979 // corresponds to these arguments. 1980 void *InsertPos = 0; 1981 ClassTemplateSpecializationDecl *Decl 1982 = ClassTemplate->findSpecialization(Converted.data(), Converted.size(), 1983 InsertPos); 1984 if (!Decl) { 1985 // This is the first time we have referenced this class template 1986 // specialization. Create the canonical declaration and add it to 1987 // the set of specializations. 1988 Decl = ClassTemplateSpecializationDecl::Create(Context, 1989 ClassTemplate->getTemplatedDecl()->getTagKind(), 1990 ClassTemplate->getDeclContext(), 1991 ClassTemplate->getLocation(), 1992 ClassTemplate->getLocation(), 1993 ClassTemplate, 1994 Converted.data(), 1995 Converted.size(), 0); 1996 ClassTemplate->AddSpecialization(Decl, InsertPos); 1997 Decl->setLexicalDeclContext(CurContext); 1998 } 1999 2000 CanonType = Context.getTypeDeclType(Decl); 2001 assert(isa<RecordType>(CanonType) && 2002 "type of non-dependent specialization is not a RecordType"); 2003 } 2004 2005 // Build the fully-sugared type for this class template 2006 // specialization, which refers back to the class template 2007 // specialization we created or found. 2008 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType); 2009} 2010 2011TypeResult 2012Sema::ActOnTemplateIdType(CXXScopeSpec &SS, 2013 TemplateTy TemplateD, SourceLocation TemplateLoc, 2014 SourceLocation LAngleLoc, 2015 ASTTemplateArgsPtr TemplateArgsIn, 2016 SourceLocation RAngleLoc) { 2017 if (SS.isInvalid()) 2018 return true; 2019 2020 TemplateName Template = TemplateD.getAsVal<TemplateName>(); 2021 2022 // Translate the parser's template argument list in our AST format. 2023 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); 2024 translateTemplateArguments(TemplateArgsIn, TemplateArgs); 2025 2026 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) { 2027 QualType T = Context.getDependentTemplateSpecializationType(ETK_None, 2028 DTN->getQualifier(), 2029 DTN->getIdentifier(), 2030 TemplateArgs); 2031 2032 // Build type-source information. 2033 TypeLocBuilder TLB; 2034 DependentTemplateSpecializationTypeLoc SpecTL 2035 = TLB.push<DependentTemplateSpecializationTypeLoc>(T); 2036 SpecTL.setKeywordLoc(SourceLocation()); 2037 SpecTL.setNameLoc(TemplateLoc); 2038 SpecTL.setLAngleLoc(LAngleLoc); 2039 SpecTL.setRAngleLoc(RAngleLoc); 2040 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2041 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I) 2042 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo()); 2043 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T)); 2044 } 2045 2046 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs); 2047 TemplateArgsIn.release(); 2048 2049 if (Result.isNull()) 2050 return true; 2051 2052 // Build type-source information. 2053 TypeLocBuilder TLB; 2054 TemplateSpecializationTypeLoc SpecTL 2055 = TLB.push<TemplateSpecializationTypeLoc>(Result); 2056 SpecTL.setTemplateNameLoc(TemplateLoc); 2057 SpecTL.setLAngleLoc(LAngleLoc); 2058 SpecTL.setRAngleLoc(RAngleLoc); 2059 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i) 2060 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo()); 2061 2062 if (SS.isNotEmpty()) { 2063 // Create an elaborated-type-specifier containing the nested-name-specifier. 2064 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result); 2065 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result); 2066 ElabTL.setKeywordLoc(SourceLocation()); 2067 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2068 } 2069 2070 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result)); 2071} 2072 2073TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK, 2074 TypeSpecifierType TagSpec, 2075 SourceLocation TagLoc, 2076 CXXScopeSpec &SS, 2077 TemplateTy TemplateD, 2078 SourceLocation TemplateLoc, 2079 SourceLocation LAngleLoc, 2080 ASTTemplateArgsPtr TemplateArgsIn, 2081 SourceLocation RAngleLoc) { 2082 TemplateName Template = TemplateD.getAsVal<TemplateName>(); 2083 2084 // Translate the parser's template argument list in our AST format. 2085 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); 2086 translateTemplateArguments(TemplateArgsIn, TemplateArgs); 2087 2088 // Determine the tag kind 2089 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 2090 ElaboratedTypeKeyword Keyword 2091 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind); 2092 2093 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) { 2094 QualType T = Context.getDependentTemplateSpecializationType(Keyword, 2095 DTN->getQualifier(), 2096 DTN->getIdentifier(), 2097 TemplateArgs); 2098 2099 // Build type-source information. 2100 TypeLocBuilder TLB; 2101 DependentTemplateSpecializationTypeLoc SpecTL 2102 = TLB.push<DependentTemplateSpecializationTypeLoc>(T); 2103 SpecTL.setKeywordLoc(TagLoc); 2104 SpecTL.setNameLoc(TemplateLoc); 2105 SpecTL.setLAngleLoc(LAngleLoc); 2106 SpecTL.setRAngleLoc(RAngleLoc); 2107 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2108 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I) 2109 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo()); 2110 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T)); 2111 } 2112 2113 if (TypeAliasTemplateDecl *TAT = 2114 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) { 2115 // C++0x [dcl.type.elab]p2: 2116 // If the identifier resolves to a typedef-name or the simple-template-id 2117 // resolves to an alias template specialization, the 2118 // elaborated-type-specifier is ill-formed. 2119 Diag(TemplateLoc, diag::err_tag_reference_non_tag) << 4; 2120 Diag(TAT->getLocation(), diag::note_declared_at); 2121 } 2122 2123 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs); 2124 if (Result.isNull()) 2125 return TypeResult(); 2126 2127 // Check the tag kind 2128 if (const RecordType *RT = Result->getAs<RecordType>()) { 2129 RecordDecl *D = RT->getDecl(); 2130 2131 IdentifierInfo *Id = D->getIdentifier(); 2132 assert(Id && "templated class must have an identifier"); 2133 2134 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition, 2135 TagLoc, *Id)) { 2136 Diag(TagLoc, diag::err_use_with_wrong_tag) 2137 << Result 2138 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName()); 2139 Diag(D->getLocation(), diag::note_previous_use); 2140 } 2141 } 2142 2143 // Provide source-location information for the template specialization. 2144 TypeLocBuilder TLB; 2145 TemplateSpecializationTypeLoc SpecTL 2146 = TLB.push<TemplateSpecializationTypeLoc>(Result); 2147 SpecTL.setTemplateNameLoc(TemplateLoc); 2148 SpecTL.setLAngleLoc(LAngleLoc); 2149 SpecTL.setRAngleLoc(RAngleLoc); 2150 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i) 2151 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo()); 2152 2153 // Construct an elaborated type containing the nested-name-specifier (if any) 2154 // and keyword. 2155 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result); 2156 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result); 2157 ElabTL.setKeywordLoc(TagLoc); 2158 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2159 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result)); 2160} 2161 2162ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS, 2163 LookupResult &R, 2164 bool RequiresADL, 2165 const TemplateArgumentListInfo &TemplateArgs) { 2166 // FIXME: Can we do any checking at this point? I guess we could check the 2167 // template arguments that we have against the template name, if the template 2168 // name refers to a single template. That's not a terribly common case, 2169 // though. 2170 // foo<int> could identify a single function unambiguously 2171 // This approach does NOT work, since f<int>(1); 2172 // gets resolved prior to resorting to overload resolution 2173 // i.e., template<class T> void f(double); 2174 // vs template<class T, class U> void f(U); 2175 2176 // These should be filtered out by our callers. 2177 assert(!R.empty() && "empty lookup results when building templateid"); 2178 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid"); 2179 2180 // We don't want lookup warnings at this point. 2181 R.suppressDiagnostics(); 2182 2183 UnresolvedLookupExpr *ULE 2184 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2185 SS.getWithLocInContext(Context), 2186 R.getLookupNameInfo(), 2187 RequiresADL, TemplateArgs, 2188 R.begin(), R.end()); 2189 2190 return Owned(ULE); 2191} 2192 2193// We actually only call this from template instantiation. 2194ExprResult 2195Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, 2196 const DeclarationNameInfo &NameInfo, 2197 const TemplateArgumentListInfo &TemplateArgs) { 2198 DeclContext *DC; 2199 if (!(DC = computeDeclContext(SS, false)) || 2200 DC->isDependentContext() || 2201 RequireCompleteDeclContext(SS, DC)) 2202 return BuildDependentDeclRefExpr(SS, NameInfo, &TemplateArgs); 2203 2204 bool MemberOfUnknownSpecialization; 2205 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2206 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false, 2207 MemberOfUnknownSpecialization); 2208 2209 if (R.isAmbiguous()) 2210 return ExprError(); 2211 2212 if (R.empty()) { 2213 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template) 2214 << NameInfo.getName() << SS.getRange(); 2215 return ExprError(); 2216 } 2217 2218 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) { 2219 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template) 2220 << (NestedNameSpecifier*) SS.getScopeRep() 2221 << NameInfo.getName() << SS.getRange(); 2222 Diag(Temp->getLocation(), diag::note_referenced_class_template); 2223 return ExprError(); 2224 } 2225 2226 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs); 2227} 2228 2229/// \brief Form a dependent template name. 2230/// 2231/// This action forms a dependent template name given the template 2232/// name and its (presumably dependent) scope specifier. For 2233/// example, given "MetaFun::template apply", the scope specifier \p 2234/// SS will be "MetaFun::", \p TemplateKWLoc contains the location 2235/// of the "template" keyword, and "apply" is the \p Name. 2236TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S, 2237 SourceLocation TemplateKWLoc, 2238 CXXScopeSpec &SS, 2239 UnqualifiedId &Name, 2240 ParsedType ObjectType, 2241 bool EnteringContext, 2242 TemplateTy &Result) { 2243 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent() && 2244 !getLangOptions().CPlusPlus0x) 2245 Diag(TemplateKWLoc, diag::ext_template_outside_of_template) 2246 << FixItHint::CreateRemoval(TemplateKWLoc); 2247 2248 DeclContext *LookupCtx = 0; 2249 if (SS.isSet()) 2250 LookupCtx = computeDeclContext(SS, EnteringContext); 2251 if (!LookupCtx && ObjectType) 2252 LookupCtx = computeDeclContext(ObjectType.get()); 2253 if (LookupCtx) { 2254 // C++0x [temp.names]p5: 2255 // If a name prefixed by the keyword template is not the name of 2256 // a template, the program is ill-formed. [Note: the keyword 2257 // template may not be applied to non-template members of class 2258 // templates. -end note ] [ Note: as is the case with the 2259 // typename prefix, the template prefix is allowed in cases 2260 // where it is not strictly necessary; i.e., when the 2261 // nested-name-specifier or the expression on the left of the -> 2262 // or . is not dependent on a template-parameter, or the use 2263 // does not appear in the scope of a template. -end note] 2264 // 2265 // Note: C++03 was more strict here, because it banned the use of 2266 // the "template" keyword prior to a template-name that was not a 2267 // dependent name. C++ DR468 relaxed this requirement (the 2268 // "template" keyword is now permitted). We follow the C++0x 2269 // rules, even in C++03 mode with a warning, retroactively applying the DR. 2270 bool MemberOfUnknownSpecialization; 2271 TemplateNameKind TNK = isTemplateName(0, SS, TemplateKWLoc.isValid(), Name, 2272 ObjectType, EnteringContext, Result, 2273 MemberOfUnknownSpecialization); 2274 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() && 2275 isa<CXXRecordDecl>(LookupCtx) && 2276 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() || 2277 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) { 2278 // This is a dependent template. Handle it below. 2279 } else if (TNK == TNK_Non_template) { 2280 Diag(Name.getSourceRange().getBegin(), 2281 diag::err_template_kw_refers_to_non_template) 2282 << GetNameFromUnqualifiedId(Name).getName() 2283 << Name.getSourceRange() 2284 << TemplateKWLoc; 2285 return TNK_Non_template; 2286 } else { 2287 // We found something; return it. 2288 return TNK; 2289 } 2290 } 2291 2292 NestedNameSpecifier *Qualifier 2293 = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 2294 2295 switch (Name.getKind()) { 2296 case UnqualifiedId::IK_Identifier: 2297 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier, 2298 Name.Identifier)); 2299 return TNK_Dependent_template_name; 2300 2301 case UnqualifiedId::IK_OperatorFunctionId: 2302 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier, 2303 Name.OperatorFunctionId.Operator)); 2304 return TNK_Dependent_template_name; 2305 2306 case UnqualifiedId::IK_LiteralOperatorId: 2307 assert(false && "We don't support these; Parse shouldn't have allowed propagation"); 2308 2309 default: 2310 break; 2311 } 2312 2313 Diag(Name.getSourceRange().getBegin(), 2314 diag::err_template_kw_refers_to_non_template) 2315 << GetNameFromUnqualifiedId(Name).getName() 2316 << Name.getSourceRange() 2317 << TemplateKWLoc; 2318 return TNK_Non_template; 2319} 2320 2321bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, 2322 const TemplateArgumentLoc &AL, 2323 llvm::SmallVectorImpl<TemplateArgument> &Converted) { 2324 const TemplateArgument &Arg = AL.getArgument(); 2325 2326 // Check template type parameter. 2327 switch(Arg.getKind()) { 2328 case TemplateArgument::Type: 2329 // C++ [temp.arg.type]p1: 2330 // A template-argument for a template-parameter which is a 2331 // type shall be a type-id. 2332 break; 2333 case TemplateArgument::Template: { 2334 // We have a template type parameter but the template argument 2335 // is a template without any arguments. 2336 SourceRange SR = AL.getSourceRange(); 2337 TemplateName Name = Arg.getAsTemplate(); 2338 Diag(SR.getBegin(), diag::err_template_missing_args) 2339 << Name << SR; 2340 if (TemplateDecl *Decl = Name.getAsTemplateDecl()) 2341 Diag(Decl->getLocation(), diag::note_template_decl_here); 2342 2343 return true; 2344 } 2345 default: { 2346 // We have a template type parameter but the template argument 2347 // is not a type. 2348 SourceRange SR = AL.getSourceRange(); 2349 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR; 2350 Diag(Param->getLocation(), diag::note_template_param_here); 2351 2352 return true; 2353 } 2354 } 2355 2356 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo())) 2357 return true; 2358 2359 // Add the converted template type argument. 2360 QualType ArgType = Context.getCanonicalType(Arg.getAsType()); 2361 2362 // Objective-C ARC: 2363 // If an explicitly-specified template argument type is a lifetime type 2364 // with no lifetime qualifier, the __strong lifetime qualifier is inferred. 2365 if (getLangOptions().ObjCAutoRefCount && 2366 ArgType->isObjCLifetimeType() && 2367 !ArgType.getObjCLifetime()) { 2368 Qualifiers Qs; 2369 Qs.setObjCLifetime(Qualifiers::OCL_Strong); 2370 ArgType = Context.getQualifiedType(ArgType, Qs); 2371 } 2372 2373 Converted.push_back(TemplateArgument(ArgType)); 2374 return false; 2375} 2376 2377/// \brief Substitute template arguments into the default template argument for 2378/// the given template type parameter. 2379/// 2380/// \param SemaRef the semantic analysis object for which we are performing 2381/// the substitution. 2382/// 2383/// \param Template the template that we are synthesizing template arguments 2384/// for. 2385/// 2386/// \param TemplateLoc the location of the template name that started the 2387/// template-id we are checking. 2388/// 2389/// \param RAngleLoc the location of the right angle bracket ('>') that 2390/// terminates the template-id. 2391/// 2392/// \param Param the template template parameter whose default we are 2393/// substituting into. 2394/// 2395/// \param Converted the list of template arguments provided for template 2396/// parameters that precede \p Param in the template parameter list. 2397/// \returns the substituted template argument, or NULL if an error occurred. 2398static TypeSourceInfo * 2399SubstDefaultTemplateArgument(Sema &SemaRef, 2400 TemplateDecl *Template, 2401 SourceLocation TemplateLoc, 2402 SourceLocation RAngleLoc, 2403 TemplateTypeParmDecl *Param, 2404 llvm::SmallVectorImpl<TemplateArgument> &Converted) { 2405 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo(); 2406 2407 // If the argument type is dependent, instantiate it now based 2408 // on the previously-computed template arguments. 2409 if (ArgType->getType()->isDependentType()) { 2410 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, 2411 Converted.data(), Converted.size()); 2412 2413 MultiLevelTemplateArgumentList AllTemplateArgs 2414 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs); 2415 2416 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, 2417 Template, Converted.data(), 2418 Converted.size(), 2419 SourceRange(TemplateLoc, RAngleLoc)); 2420 2421 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs, 2422 Param->getDefaultArgumentLoc(), 2423 Param->getDeclName()); 2424 } 2425 2426 return ArgType; 2427} 2428 2429/// \brief Substitute template arguments into the default template argument for 2430/// the given non-type template parameter. 2431/// 2432/// \param SemaRef the semantic analysis object for which we are performing 2433/// the substitution. 2434/// 2435/// \param Template the template that we are synthesizing template arguments 2436/// for. 2437/// 2438/// \param TemplateLoc the location of the template name that started the 2439/// template-id we are checking. 2440/// 2441/// \param RAngleLoc the location of the right angle bracket ('>') that 2442/// terminates the template-id. 2443/// 2444/// \param Param the non-type template parameter whose default we are 2445/// substituting into. 2446/// 2447/// \param Converted the list of template arguments provided for template 2448/// parameters that precede \p Param in the template parameter list. 2449/// 2450/// \returns the substituted template argument, or NULL if an error occurred. 2451static ExprResult 2452SubstDefaultTemplateArgument(Sema &SemaRef, 2453 TemplateDecl *Template, 2454 SourceLocation TemplateLoc, 2455 SourceLocation RAngleLoc, 2456 NonTypeTemplateParmDecl *Param, 2457 llvm::SmallVectorImpl<TemplateArgument> &Converted) { 2458 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, 2459 Converted.data(), Converted.size()); 2460 2461 MultiLevelTemplateArgumentList AllTemplateArgs 2462 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs); 2463 2464 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, 2465 Template, Converted.data(), 2466 Converted.size(), 2467 SourceRange(TemplateLoc, RAngleLoc)); 2468 2469 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs); 2470} 2471 2472/// \brief Substitute template arguments into the default template argument for 2473/// the given template template parameter. 2474/// 2475/// \param SemaRef the semantic analysis object for which we are performing 2476/// the substitution. 2477/// 2478/// \param Template the template that we are synthesizing template arguments 2479/// for. 2480/// 2481/// \param TemplateLoc the location of the template name that started the 2482/// template-id we are checking. 2483/// 2484/// \param RAngleLoc the location of the right angle bracket ('>') that 2485/// terminates the template-id. 2486/// 2487/// \param Param the template template parameter whose default we are 2488/// substituting into. 2489/// 2490/// \param Converted the list of template arguments provided for template 2491/// parameters that precede \p Param in the template parameter list. 2492/// 2493/// \param QualifierLoc Will be set to the nested-name-specifier (with 2494/// source-location information) that precedes the template name. 2495/// 2496/// \returns the substituted template argument, or NULL if an error occurred. 2497static TemplateName 2498SubstDefaultTemplateArgument(Sema &SemaRef, 2499 TemplateDecl *Template, 2500 SourceLocation TemplateLoc, 2501 SourceLocation RAngleLoc, 2502 TemplateTemplateParmDecl *Param, 2503 llvm::SmallVectorImpl<TemplateArgument> &Converted, 2504 NestedNameSpecifierLoc &QualifierLoc) { 2505 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, 2506 Converted.data(), Converted.size()); 2507 2508 MultiLevelTemplateArgumentList AllTemplateArgs 2509 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs); 2510 2511 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, 2512 Template, Converted.data(), 2513 Converted.size(), 2514 SourceRange(TemplateLoc, RAngleLoc)); 2515 2516 // Substitute into the nested-name-specifier first, 2517 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc(); 2518 if (QualifierLoc) { 2519 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, 2520 AllTemplateArgs); 2521 if (!QualifierLoc) 2522 return TemplateName(); 2523 } 2524 2525 return SemaRef.SubstTemplateName(QualifierLoc, 2526 Param->getDefaultArgument().getArgument().getAsTemplate(), 2527 Param->getDefaultArgument().getTemplateNameLoc(), 2528 AllTemplateArgs); 2529} 2530 2531/// \brief If the given template parameter has a default template 2532/// argument, substitute into that default template argument and 2533/// return the corresponding template argument. 2534TemplateArgumentLoc 2535Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, 2536 SourceLocation TemplateLoc, 2537 SourceLocation RAngleLoc, 2538 Decl *Param, 2539 llvm::SmallVectorImpl<TemplateArgument> &Converted) { 2540 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) { 2541 if (!TypeParm->hasDefaultArgument()) 2542 return TemplateArgumentLoc(); 2543 2544 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template, 2545 TemplateLoc, 2546 RAngleLoc, 2547 TypeParm, 2548 Converted); 2549 if (DI) 2550 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI); 2551 2552 return TemplateArgumentLoc(); 2553 } 2554 2555 if (NonTypeTemplateParmDecl *NonTypeParm 2556 = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 2557 if (!NonTypeParm->hasDefaultArgument()) 2558 return TemplateArgumentLoc(); 2559 2560 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template, 2561 TemplateLoc, 2562 RAngleLoc, 2563 NonTypeParm, 2564 Converted); 2565 if (Arg.isInvalid()) 2566 return TemplateArgumentLoc(); 2567 2568 Expr *ArgE = Arg.takeAs<Expr>(); 2569 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE); 2570 } 2571 2572 TemplateTemplateParmDecl *TempTempParm 2573 = cast<TemplateTemplateParmDecl>(Param); 2574 if (!TempTempParm->hasDefaultArgument()) 2575 return TemplateArgumentLoc(); 2576 2577 2578 NestedNameSpecifierLoc QualifierLoc; 2579 TemplateName TName = SubstDefaultTemplateArgument(*this, Template, 2580 TemplateLoc, 2581 RAngleLoc, 2582 TempTempParm, 2583 Converted, 2584 QualifierLoc); 2585 if (TName.isNull()) 2586 return TemplateArgumentLoc(); 2587 2588 return TemplateArgumentLoc(TemplateArgument(TName), 2589 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(), 2590 TempTempParm->getDefaultArgument().getTemplateNameLoc()); 2591} 2592 2593/// \brief Check that the given template argument corresponds to the given 2594/// template parameter. 2595/// 2596/// \param Param The template parameter against which the argument will be 2597/// checked. 2598/// 2599/// \param Arg The template argument. 2600/// 2601/// \param Template The template in which the template argument resides. 2602/// 2603/// \param TemplateLoc The location of the template name for the template 2604/// whose argument list we're matching. 2605/// 2606/// \param RAngleLoc The location of the right angle bracket ('>') that closes 2607/// the template argument list. 2608/// 2609/// \param ArgumentPackIndex The index into the argument pack where this 2610/// argument will be placed. Only valid if the parameter is a parameter pack. 2611/// 2612/// \param Converted The checked, converted argument will be added to the 2613/// end of this small vector. 2614/// 2615/// \param CTAK Describes how we arrived at this particular template argument: 2616/// explicitly written, deduced, etc. 2617/// 2618/// \returns true on error, false otherwise. 2619bool Sema::CheckTemplateArgument(NamedDecl *Param, 2620 const TemplateArgumentLoc &Arg, 2621 NamedDecl *Template, 2622 SourceLocation TemplateLoc, 2623 SourceLocation RAngleLoc, 2624 unsigned ArgumentPackIndex, 2625 llvm::SmallVectorImpl<TemplateArgument> &Converted, 2626 CheckTemplateArgumentKind CTAK) { 2627 // Check template type parameters. 2628 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) 2629 return CheckTemplateTypeArgument(TTP, Arg, Converted); 2630 2631 // Check non-type template parameters. 2632 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) { 2633 // Do substitution on the type of the non-type template parameter 2634 // with the template arguments we've seen thus far. But if the 2635 // template has a dependent context then we cannot substitute yet. 2636 QualType NTTPType = NTTP->getType(); 2637 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack()) 2638 NTTPType = NTTP->getExpansionType(ArgumentPackIndex); 2639 2640 if (NTTPType->isDependentType() && 2641 !isa<TemplateTemplateParmDecl>(Template) && 2642 !Template->getDeclContext()->isDependentContext()) { 2643 // Do substitution on the type of the non-type template parameter. 2644 InstantiatingTemplate Inst(*this, TemplateLoc, Template, 2645 NTTP, Converted.data(), Converted.size(), 2646 SourceRange(TemplateLoc, RAngleLoc)); 2647 2648 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, 2649 Converted.data(), Converted.size()); 2650 NTTPType = SubstType(NTTPType, 2651 MultiLevelTemplateArgumentList(TemplateArgs), 2652 NTTP->getLocation(), 2653 NTTP->getDeclName()); 2654 // If that worked, check the non-type template parameter type 2655 // for validity. 2656 if (!NTTPType.isNull()) 2657 NTTPType = CheckNonTypeTemplateParameterType(NTTPType, 2658 NTTP->getLocation()); 2659 if (NTTPType.isNull()) 2660 return true; 2661 } 2662 2663 switch (Arg.getArgument().getKind()) { 2664 case TemplateArgument::Null: 2665 assert(false && "Should never see a NULL template argument here"); 2666 return true; 2667 2668 case TemplateArgument::Expression: { 2669 TemplateArgument Result; 2670 ExprResult Res = 2671 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(), 2672 Result, CTAK); 2673 if (Res.isInvalid()) 2674 return true; 2675 2676 Converted.push_back(Result); 2677 break; 2678 } 2679 2680 case TemplateArgument::Declaration: 2681 case TemplateArgument::Integral: 2682 // We've already checked this template argument, so just copy 2683 // it to the list of converted arguments. 2684 Converted.push_back(Arg.getArgument()); 2685 break; 2686 2687 case TemplateArgument::Template: 2688 case TemplateArgument::TemplateExpansion: 2689 // We were given a template template argument. It may not be ill-formed; 2690 // see below. 2691 if (DependentTemplateName *DTN 2692 = Arg.getArgument().getAsTemplateOrTemplatePattern() 2693 .getAsDependentTemplateName()) { 2694 // We have a template argument such as \c T::template X, which we 2695 // parsed as a template template argument. However, since we now 2696 // know that we need a non-type template argument, convert this 2697 // template name into an expression. 2698 2699 DeclarationNameInfo NameInfo(DTN->getIdentifier(), 2700 Arg.getTemplateNameLoc()); 2701 2702 CXXScopeSpec SS; 2703 SS.Adopt(Arg.getTemplateQualifierLoc()); 2704 ExprResult E = Owned(DependentScopeDeclRefExpr::Create(Context, 2705 SS.getWithLocInContext(Context), 2706 NameInfo)); 2707 2708 // If we parsed the template argument as a pack expansion, create a 2709 // pack expansion expression. 2710 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){ 2711 E = ActOnPackExpansion(E.take(), Arg.getTemplateEllipsisLoc()); 2712 if (E.isInvalid()) 2713 return true; 2714 } 2715 2716 TemplateArgument Result; 2717 E = CheckTemplateArgument(NTTP, NTTPType, E.take(), Result); 2718 if (E.isInvalid()) 2719 return true; 2720 2721 Converted.push_back(Result); 2722 break; 2723 } 2724 2725 // We have a template argument that actually does refer to a class 2726 // template, alias template, or template template parameter, and 2727 // therefore cannot be a non-type template argument. 2728 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr) 2729 << Arg.getSourceRange(); 2730 2731 Diag(Param->getLocation(), diag::note_template_param_here); 2732 return true; 2733 2734 case TemplateArgument::Type: { 2735 // We have a non-type template parameter but the template 2736 // argument is a type. 2737 2738 // C++ [temp.arg]p2: 2739 // In a template-argument, an ambiguity between a type-id and 2740 // an expression is resolved to a type-id, regardless of the 2741 // form of the corresponding template-parameter. 2742 // 2743 // We warn specifically about this case, since it can be rather 2744 // confusing for users. 2745 QualType T = Arg.getArgument().getAsType(); 2746 SourceRange SR = Arg.getSourceRange(); 2747 if (T->isFunctionType()) 2748 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T; 2749 else 2750 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR; 2751 Diag(Param->getLocation(), diag::note_template_param_here); 2752 return true; 2753 } 2754 2755 case TemplateArgument::Pack: 2756 llvm_unreachable("Caller must expand template argument packs"); 2757 break; 2758 } 2759 2760 return false; 2761 } 2762 2763 2764 // Check template template parameters. 2765 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param); 2766 2767 // Substitute into the template parameter list of the template 2768 // template parameter, since previously-supplied template arguments 2769 // may appear within the template template parameter. 2770 { 2771 // Set up a template instantiation context. 2772 LocalInstantiationScope Scope(*this); 2773 InstantiatingTemplate Inst(*this, TemplateLoc, Template, 2774 TempParm, Converted.data(), Converted.size(), 2775 SourceRange(TemplateLoc, RAngleLoc)); 2776 2777 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, 2778 Converted.data(), Converted.size()); 2779 TempParm = cast_or_null<TemplateTemplateParmDecl>( 2780 SubstDecl(TempParm, CurContext, 2781 MultiLevelTemplateArgumentList(TemplateArgs))); 2782 if (!TempParm) 2783 return true; 2784 } 2785 2786 switch (Arg.getArgument().getKind()) { 2787 case TemplateArgument::Null: 2788 assert(false && "Should never see a NULL template argument here"); 2789 return true; 2790 2791 case TemplateArgument::Template: 2792 case TemplateArgument::TemplateExpansion: 2793 if (CheckTemplateArgument(TempParm, Arg)) 2794 return true; 2795 2796 Converted.push_back(Arg.getArgument()); 2797 break; 2798 2799 case TemplateArgument::Expression: 2800 case TemplateArgument::Type: 2801 // We have a template template parameter but the template 2802 // argument does not refer to a template. 2803 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template) 2804 << getLangOptions().CPlusPlus0x; 2805 return true; 2806 2807 case TemplateArgument::Declaration: 2808 llvm_unreachable( 2809 "Declaration argument with template template parameter"); 2810 break; 2811 case TemplateArgument::Integral: 2812 llvm_unreachable( 2813 "Integral argument with template template parameter"); 2814 break; 2815 2816 case TemplateArgument::Pack: 2817 llvm_unreachable("Caller must expand template argument packs"); 2818 break; 2819 } 2820 2821 return false; 2822} 2823 2824/// \brief Check that the given template argument list is well-formed 2825/// for specializing the given template. 2826bool Sema::CheckTemplateArgumentList(TemplateDecl *Template, 2827 SourceLocation TemplateLoc, 2828 TemplateArgumentListInfo &TemplateArgs, 2829 bool PartialTemplateArgs, 2830 llvm::SmallVectorImpl<TemplateArgument> &Converted) { 2831 TemplateParameterList *Params = Template->getTemplateParameters(); 2832 unsigned NumParams = Params->size(); 2833 unsigned NumArgs = TemplateArgs.size(); 2834 bool Invalid = false; 2835 2836 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc(); 2837 2838 bool HasParameterPack = 2839 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack(); 2840 2841 if ((NumArgs > NumParams && !HasParameterPack) || 2842 (NumArgs < Params->getMinRequiredArguments() && 2843 !PartialTemplateArgs)) { 2844 // FIXME: point at either the first arg beyond what we can handle, 2845 // or the '>', depending on whether we have too many or too few 2846 // arguments. 2847 SourceRange Range; 2848 if (NumArgs > NumParams) 2849 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc); 2850 Diag(TemplateLoc, diag::err_template_arg_list_different_arity) 2851 << (NumArgs > NumParams) 2852 << (isa<ClassTemplateDecl>(Template)? 0 : 2853 isa<FunctionTemplateDecl>(Template)? 1 : 2854 isa<TemplateTemplateParmDecl>(Template)? 2 : 3) 2855 << Template << Range; 2856 Diag(Template->getLocation(), diag::note_template_decl_here) 2857 << Params->getSourceRange(); 2858 Invalid = true; 2859 } 2860 2861 // C++ [temp.arg]p1: 2862 // [...] The type and form of each template-argument specified in 2863 // a template-id shall match the type and form specified for the 2864 // corresponding parameter declared by the template in its 2865 // template-parameter-list. 2866 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template); 2867 llvm::SmallVector<TemplateArgument, 2> ArgumentPack; 2868 TemplateParameterList::iterator Param = Params->begin(), 2869 ParamEnd = Params->end(); 2870 unsigned ArgIdx = 0; 2871 LocalInstantiationScope InstScope(*this, true); 2872 while (Param != ParamEnd) { 2873 if (ArgIdx < NumArgs) { 2874 // If we have an expanded parameter pack, make sure we don't have too 2875 // many arguments. 2876 if (NonTypeTemplateParmDecl *NTTP 2877 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) { 2878 if (NTTP->isExpandedParameterPack() && 2879 ArgumentPack.size() >= NTTP->getNumExpansionTypes()) { 2880 Diag(TemplateLoc, diag::err_template_arg_list_different_arity) 2881 << true 2882 << (isa<ClassTemplateDecl>(Template)? 0 : 2883 isa<FunctionTemplateDecl>(Template)? 1 : 2884 isa<TemplateTemplateParmDecl>(Template)? 2 : 3) 2885 << Template; 2886 Diag(Template->getLocation(), diag::note_template_decl_here) 2887 << Params->getSourceRange(); 2888 return true; 2889 } 2890 } 2891 2892 // Check the template argument we were given. 2893 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template, 2894 TemplateLoc, RAngleLoc, 2895 ArgumentPack.size(), Converted)) 2896 return true; 2897 2898 if ((*Param)->isTemplateParameterPack()) { 2899 // The template parameter was a template parameter pack, so take the 2900 // deduced argument and place it on the argument pack. Note that we 2901 // stay on the same template parameter so that we can deduce more 2902 // arguments. 2903 ArgumentPack.push_back(Converted.back()); 2904 Converted.pop_back(); 2905 } else { 2906 // Move to the next template parameter. 2907 ++Param; 2908 } 2909 ++ArgIdx; 2910 continue; 2911 } 2912 2913 // If we're checking a partial template argument list, we're done. 2914 if (PartialTemplateArgs) { 2915 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty()) 2916 Converted.push_back(TemplateArgument::CreatePackCopy(Context, 2917 ArgumentPack.data(), 2918 ArgumentPack.size())); 2919 2920 return Invalid; 2921 } 2922 2923 // If we have a template parameter pack with no more corresponding 2924 // arguments, just break out now and we'll fill in the argument pack below. 2925 if ((*Param)->isTemplateParameterPack()) 2926 break; 2927 2928 // We have a default template argument that we will use. 2929 TemplateArgumentLoc Arg; 2930 2931 // Retrieve the default template argument from the template 2932 // parameter. For each kind of template parameter, we substitute the 2933 // template arguments provided thus far and any "outer" template arguments 2934 // (when the template parameter was part of a nested template) into 2935 // the default argument. 2936 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) { 2937 if (!TTP->hasDefaultArgument()) { 2938 assert(Invalid && "Missing default argument"); 2939 break; 2940 } 2941 2942 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this, 2943 Template, 2944 TemplateLoc, 2945 RAngleLoc, 2946 TTP, 2947 Converted); 2948 if (!ArgType) 2949 return true; 2950 2951 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()), 2952 ArgType); 2953 } else if (NonTypeTemplateParmDecl *NTTP 2954 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) { 2955 if (!NTTP->hasDefaultArgument()) { 2956 assert(Invalid && "Missing default argument"); 2957 break; 2958 } 2959 2960 ExprResult E = SubstDefaultTemplateArgument(*this, Template, 2961 TemplateLoc, 2962 RAngleLoc, 2963 NTTP, 2964 Converted); 2965 if (E.isInvalid()) 2966 return true; 2967 2968 Expr *Ex = E.takeAs<Expr>(); 2969 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex); 2970 } else { 2971 TemplateTemplateParmDecl *TempParm 2972 = cast<TemplateTemplateParmDecl>(*Param); 2973 2974 if (!TempParm->hasDefaultArgument()) { 2975 assert(Invalid && "Missing default argument"); 2976 break; 2977 } 2978 2979 NestedNameSpecifierLoc QualifierLoc; 2980 TemplateName Name = SubstDefaultTemplateArgument(*this, Template, 2981 TemplateLoc, 2982 RAngleLoc, 2983 TempParm, 2984 Converted, 2985 QualifierLoc); 2986 if (Name.isNull()) 2987 return true; 2988 2989 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc, 2990 TempParm->getDefaultArgument().getTemplateNameLoc()); 2991 } 2992 2993 // Introduce an instantiation record that describes where we are using 2994 // the default template argument. 2995 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param, 2996 Converted.data(), Converted.size(), 2997 SourceRange(TemplateLoc, RAngleLoc)); 2998 2999 // Check the default template argument. 3000 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, 3001 RAngleLoc, 0, Converted)) 3002 return true; 3003 3004 // Core issue 150 (assumed resolution): if this is a template template 3005 // parameter, keep track of the default template arguments from the 3006 // template definition. 3007 if (isTemplateTemplateParameter) 3008 TemplateArgs.addArgument(Arg); 3009 3010 // Move to the next template parameter and argument. 3011 ++Param; 3012 ++ArgIdx; 3013 } 3014 3015 // Form argument packs for each of the parameter packs remaining. 3016 while (Param != ParamEnd) { 3017 // If we're checking a partial list of template arguments, don't fill 3018 // in arguments for non-template parameter packs. 3019 3020 if ((*Param)->isTemplateParameterPack()) { 3021 if (ArgumentPack.empty()) 3022 Converted.push_back(TemplateArgument(0, 0)); 3023 else { 3024 Converted.push_back(TemplateArgument::CreatePackCopy(Context, 3025 ArgumentPack.data(), 3026 ArgumentPack.size())); 3027 ArgumentPack.clear(); 3028 } 3029 } 3030 3031 ++Param; 3032 } 3033 3034 return Invalid; 3035} 3036 3037namespace { 3038 class UnnamedLocalNoLinkageFinder 3039 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool> 3040 { 3041 Sema &S; 3042 SourceRange SR; 3043 3044 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited; 3045 3046 public: 3047 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { } 3048 3049 bool Visit(QualType T) { 3050 return inherited::Visit(T.getTypePtr()); 3051 } 3052 3053#define TYPE(Class, Parent) \ 3054 bool Visit##Class##Type(const Class##Type *); 3055#define ABSTRACT_TYPE(Class, Parent) \ 3056 bool Visit##Class##Type(const Class##Type *) { return false; } 3057#define NON_CANONICAL_TYPE(Class, Parent) \ 3058 bool Visit##Class##Type(const Class##Type *) { return false; } 3059#include "clang/AST/TypeNodes.def" 3060 3061 bool VisitTagDecl(const TagDecl *Tag); 3062 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS); 3063 }; 3064} 3065 3066bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) { 3067 return false; 3068} 3069 3070bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) { 3071 return Visit(T->getElementType()); 3072} 3073 3074bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) { 3075 return Visit(T->getPointeeType()); 3076} 3077 3078bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType( 3079 const BlockPointerType* T) { 3080 return Visit(T->getPointeeType()); 3081} 3082 3083bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType( 3084 const LValueReferenceType* T) { 3085 return Visit(T->getPointeeType()); 3086} 3087 3088bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType( 3089 const RValueReferenceType* T) { 3090 return Visit(T->getPointeeType()); 3091} 3092 3093bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType( 3094 const MemberPointerType* T) { 3095 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0)); 3096} 3097 3098bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType( 3099 const ConstantArrayType* T) { 3100 return Visit(T->getElementType()); 3101} 3102 3103bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType( 3104 const IncompleteArrayType* T) { 3105 return Visit(T->getElementType()); 3106} 3107 3108bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType( 3109 const VariableArrayType* T) { 3110 return Visit(T->getElementType()); 3111} 3112 3113bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType( 3114 const DependentSizedArrayType* T) { 3115 return Visit(T->getElementType()); 3116} 3117 3118bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType( 3119 const DependentSizedExtVectorType* T) { 3120 return Visit(T->getElementType()); 3121} 3122 3123bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) { 3124 return Visit(T->getElementType()); 3125} 3126 3127bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) { 3128 return Visit(T->getElementType()); 3129} 3130 3131bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType( 3132 const FunctionProtoType* T) { 3133 for (FunctionProtoType::arg_type_iterator A = T->arg_type_begin(), 3134 AEnd = T->arg_type_end(); 3135 A != AEnd; ++A) { 3136 if (Visit(*A)) 3137 return true; 3138 } 3139 3140 return Visit(T->getResultType()); 3141} 3142 3143bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType( 3144 const FunctionNoProtoType* T) { 3145 return Visit(T->getResultType()); 3146} 3147 3148bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType( 3149 const UnresolvedUsingType*) { 3150 return false; 3151} 3152 3153bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) { 3154 return false; 3155} 3156 3157bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) { 3158 return Visit(T->getUnderlyingType()); 3159} 3160 3161bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) { 3162 return false; 3163} 3164 3165bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType( 3166 const UnaryTransformType*) { 3167 return false; 3168} 3169 3170bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) { 3171 return Visit(T->getDeducedType()); 3172} 3173 3174bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) { 3175 return VisitTagDecl(T->getDecl()); 3176} 3177 3178bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) { 3179 return VisitTagDecl(T->getDecl()); 3180} 3181 3182bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType( 3183 const TemplateTypeParmType*) { 3184 return false; 3185} 3186 3187bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType( 3188 const SubstTemplateTypeParmPackType *) { 3189 return false; 3190} 3191 3192bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType( 3193 const TemplateSpecializationType*) { 3194 return false; 3195} 3196 3197bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType( 3198 const InjectedClassNameType* T) { 3199 return VisitTagDecl(T->getDecl()); 3200} 3201 3202bool UnnamedLocalNoLinkageFinder::VisitDependentNameType( 3203 const DependentNameType* T) { 3204 return VisitNestedNameSpecifier(T->getQualifier()); 3205} 3206 3207bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType( 3208 const DependentTemplateSpecializationType* T) { 3209 return VisitNestedNameSpecifier(T->getQualifier()); 3210} 3211 3212bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType( 3213 const PackExpansionType* T) { 3214 return Visit(T->getPattern()); 3215} 3216 3217bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) { 3218 return false; 3219} 3220 3221bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType( 3222 const ObjCInterfaceType *) { 3223 return false; 3224} 3225 3226bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType( 3227 const ObjCObjectPointerType *) { 3228 return false; 3229} 3230 3231bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) { 3232 if (Tag->getDeclContext()->isFunctionOrMethod()) { 3233 S.Diag(SR.getBegin(), diag::ext_template_arg_local_type) 3234 << S.Context.getTypeDeclType(Tag) << SR; 3235 return true; 3236 } 3237 3238 if (!Tag->getDeclName() && !Tag->getTypedefNameForAnonDecl()) { 3239 S.Diag(SR.getBegin(), diag::ext_template_arg_unnamed_type) << SR; 3240 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here); 3241 return true; 3242 } 3243 3244 return false; 3245} 3246 3247bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier( 3248 NestedNameSpecifier *NNS) { 3249 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix())) 3250 return true; 3251 3252 switch (NNS->getKind()) { 3253 case NestedNameSpecifier::Identifier: 3254 case NestedNameSpecifier::Namespace: 3255 case NestedNameSpecifier::NamespaceAlias: 3256 case NestedNameSpecifier::Global: 3257 return false; 3258 3259 case NestedNameSpecifier::TypeSpec: 3260 case NestedNameSpecifier::TypeSpecWithTemplate: 3261 return Visit(QualType(NNS->getAsType(), 0)); 3262 } 3263 return false; 3264} 3265 3266 3267/// \brief Check a template argument against its corresponding 3268/// template type parameter. 3269/// 3270/// This routine implements the semantics of C++ [temp.arg.type]. It 3271/// returns true if an error occurred, and false otherwise. 3272bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param, 3273 TypeSourceInfo *ArgInfo) { 3274 assert(ArgInfo && "invalid TypeSourceInfo"); 3275 QualType Arg = ArgInfo->getType(); 3276 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange(); 3277 3278 if (Arg->isVariablyModifiedType()) { 3279 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg; 3280 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) { 3281 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR; 3282 } 3283 3284 // C++03 [temp.arg.type]p2: 3285 // A local type, a type with no linkage, an unnamed type or a type 3286 // compounded from any of these types shall not be used as a 3287 // template-argument for a template type-parameter. 3288 // 3289 // C++0x allows these, and even in C++03 we allow them as an extension with 3290 // a warning. 3291 if (!LangOpts.CPlusPlus0x && Arg->hasUnnamedOrLocalType()) { 3292 UnnamedLocalNoLinkageFinder Finder(*this, SR); 3293 (void)Finder.Visit(Context.getCanonicalType(Arg)); 3294 } 3295 3296 return false; 3297} 3298 3299/// \brief Checks whether the given template argument is the address 3300/// of an object or function according to C++ [temp.arg.nontype]p1. 3301static bool 3302CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S, 3303 NonTypeTemplateParmDecl *Param, 3304 QualType ParamType, 3305 Expr *ArgIn, 3306 TemplateArgument &Converted) { 3307 bool Invalid = false; 3308 Expr *Arg = ArgIn; 3309 QualType ArgType = Arg->getType(); 3310 3311 // See through any implicit casts we added to fix the type. 3312 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg)) 3313 Arg = Cast->getSubExpr(); 3314 3315 // C++ [temp.arg.nontype]p1: 3316 // 3317 // A template-argument for a non-type, non-template 3318 // template-parameter shall be one of: [...] 3319 // 3320 // -- the address of an object or function with external 3321 // linkage, including function templates and function 3322 // template-ids but excluding non-static class members, 3323 // expressed as & id-expression where the & is optional if 3324 // the name refers to a function or array, or if the 3325 // corresponding template-parameter is a reference; or 3326 DeclRefExpr *DRE = 0; 3327 3328 // In C++98/03 mode, give an extension warning on any extra parentheses. 3329 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773 3330 bool ExtraParens = false; 3331 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) { 3332 if (!Invalid && !ExtraParens && !S.getLangOptions().CPlusPlus0x) { 3333 S.Diag(Arg->getSourceRange().getBegin(), 3334 diag::ext_template_arg_extra_parens) 3335 << Arg->getSourceRange(); 3336 ExtraParens = true; 3337 } 3338 3339 Arg = Parens->getSubExpr(); 3340 } 3341 3342 bool AddressTaken = false; 3343 SourceLocation AddrOpLoc; 3344 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) { 3345 if (UnOp->getOpcode() == UO_AddrOf) { 3346 // Support &__uuidof(class_with_uuid) as a non-type template argument. 3347 // Very common in Microsoft COM headers. 3348 if (S.getLangOptions().Microsoft && 3349 isa<CXXUuidofExpr>(UnOp->getSubExpr())) { 3350 Converted = TemplateArgument(ArgIn); 3351 return false; 3352 } 3353 3354 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr()); 3355 AddressTaken = true; 3356 AddrOpLoc = UnOp->getOperatorLoc(); 3357 } 3358 } else { 3359 if (S.getLangOptions().Microsoft && isa<CXXUuidofExpr>(Arg)) { 3360 Converted = TemplateArgument(ArgIn); 3361 return false; 3362 } 3363 DRE = dyn_cast<DeclRefExpr>(Arg); 3364 } 3365 if (!DRE) { 3366 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref) 3367 << Arg->getSourceRange(); 3368 S.Diag(Param->getLocation(), diag::note_template_param_here); 3369 return true; 3370 } 3371 3372 // Stop checking the precise nature of the argument if it is value dependent, 3373 // it should be checked when instantiated. 3374 if (Arg->isValueDependent()) { 3375 Converted = TemplateArgument(ArgIn); 3376 return false; 3377 } 3378 3379 if (!isa<ValueDecl>(DRE->getDecl())) { 3380 S.Diag(Arg->getSourceRange().getBegin(), 3381 diag::err_template_arg_not_object_or_func_form) 3382 << Arg->getSourceRange(); 3383 S.Diag(Param->getLocation(), diag::note_template_param_here); 3384 return true; 3385 } 3386 3387 NamedDecl *Entity = 0; 3388 3389 // Cannot refer to non-static data members 3390 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) { 3391 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field) 3392 << Field << Arg->getSourceRange(); 3393 S.Diag(Param->getLocation(), diag::note_template_param_here); 3394 return true; 3395 } 3396 3397 // Cannot refer to non-static member functions 3398 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl())) 3399 if (!Method->isStatic()) { 3400 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method) 3401 << Method << Arg->getSourceRange(); 3402 S.Diag(Param->getLocation(), diag::note_template_param_here); 3403 return true; 3404 } 3405 3406 // Functions must have external linkage. 3407 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) { 3408 if (!isExternalLinkage(Func->getLinkage())) { 3409 S.Diag(Arg->getSourceRange().getBegin(), 3410 diag::err_template_arg_function_not_extern) 3411 << Func << Arg->getSourceRange(); 3412 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object) 3413 << true; 3414 return true; 3415 } 3416 3417 // Okay: we've named a function with external linkage. 3418 Entity = Func; 3419 3420 // If the template parameter has pointer type, the function decays. 3421 if (ParamType->isPointerType() && !AddressTaken) 3422 ArgType = S.Context.getPointerType(Func->getType()); 3423 else if (AddressTaken && ParamType->isReferenceType()) { 3424 // If we originally had an address-of operator, but the 3425 // parameter has reference type, complain and (if things look 3426 // like they will work) drop the address-of operator. 3427 if (!S.Context.hasSameUnqualifiedType(Func->getType(), 3428 ParamType.getNonReferenceType())) { 3429 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer) 3430 << ParamType; 3431 S.Diag(Param->getLocation(), diag::note_template_param_here); 3432 return true; 3433 } 3434 3435 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer) 3436 << ParamType 3437 << FixItHint::CreateRemoval(AddrOpLoc); 3438 S.Diag(Param->getLocation(), diag::note_template_param_here); 3439 3440 ArgType = Func->getType(); 3441 } 3442 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 3443 if (!isExternalLinkage(Var->getLinkage())) { 3444 S.Diag(Arg->getSourceRange().getBegin(), 3445 diag::err_template_arg_object_not_extern) 3446 << Var << Arg->getSourceRange(); 3447 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object) 3448 << true; 3449 return true; 3450 } 3451 3452 // A value of reference type is not an object. 3453 if (Var->getType()->isReferenceType()) { 3454 S.Diag(Arg->getSourceRange().getBegin(), 3455 diag::err_template_arg_reference_var) 3456 << Var->getType() << Arg->getSourceRange(); 3457 S.Diag(Param->getLocation(), diag::note_template_param_here); 3458 return true; 3459 } 3460 3461 // Okay: we've named an object with external linkage 3462 Entity = Var; 3463 3464 // If the template parameter has pointer type, we must have taken 3465 // the address of this object. 3466 if (ParamType->isReferenceType()) { 3467 if (AddressTaken) { 3468 // If we originally had an address-of operator, but the 3469 // parameter has reference type, complain and (if things look 3470 // like they will work) drop the address-of operator. 3471 if (!S.Context.hasSameUnqualifiedType(Var->getType(), 3472 ParamType.getNonReferenceType())) { 3473 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer) 3474 << ParamType; 3475 S.Diag(Param->getLocation(), diag::note_template_param_here); 3476 return true; 3477 } 3478 3479 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer) 3480 << ParamType 3481 << FixItHint::CreateRemoval(AddrOpLoc); 3482 S.Diag(Param->getLocation(), diag::note_template_param_here); 3483 3484 ArgType = Var->getType(); 3485 } 3486 } else if (!AddressTaken && ParamType->isPointerType()) { 3487 if (Var->getType()->isArrayType()) { 3488 // Array-to-pointer decay. 3489 ArgType = S.Context.getArrayDecayedType(Var->getType()); 3490 } else { 3491 // If the template parameter has pointer type but the address of 3492 // this object was not taken, complain and (possibly) recover by 3493 // taking the address of the entity. 3494 ArgType = S.Context.getPointerType(Var->getType()); 3495 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) { 3496 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of) 3497 << ParamType; 3498 S.Diag(Param->getLocation(), diag::note_template_param_here); 3499 return true; 3500 } 3501 3502 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of) 3503 << ParamType 3504 << FixItHint::CreateInsertion(Arg->getLocStart(), "&"); 3505 3506 S.Diag(Param->getLocation(), diag::note_template_param_here); 3507 } 3508 } 3509 } else { 3510 // We found something else, but we don't know specifically what it is. 3511 S.Diag(Arg->getSourceRange().getBegin(), 3512 diag::err_template_arg_not_object_or_func) 3513 << Arg->getSourceRange(); 3514 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here); 3515 return true; 3516 } 3517 3518 bool ObjCLifetimeConversion; 3519 if (ParamType->isPointerType() && 3520 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() && 3521 S.IsQualificationConversion(ArgType, ParamType, false, 3522 ObjCLifetimeConversion)) { 3523 // For pointer-to-object types, qualification conversions are 3524 // permitted. 3525 } else { 3526 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) { 3527 if (!ParamRef->getPointeeType()->isFunctionType()) { 3528 // C++ [temp.arg.nontype]p5b3: 3529 // For a non-type template-parameter of type reference to 3530 // object, no conversions apply. The type referred to by the 3531 // reference may be more cv-qualified than the (otherwise 3532 // identical) type of the template- argument. The 3533 // template-parameter is bound directly to the 3534 // template-argument, which shall be an lvalue. 3535 3536 // FIXME: Other qualifiers? 3537 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers(); 3538 unsigned ArgQuals = ArgType.getCVRQualifiers(); 3539 3540 if ((ParamQuals | ArgQuals) != ParamQuals) { 3541 S.Diag(Arg->getSourceRange().getBegin(), 3542 diag::err_template_arg_ref_bind_ignores_quals) 3543 << ParamType << Arg->getType() 3544 << Arg->getSourceRange(); 3545 S.Diag(Param->getLocation(), diag::note_template_param_here); 3546 return true; 3547 } 3548 } 3549 } 3550 3551 // At this point, the template argument refers to an object or 3552 // function with external linkage. We now need to check whether the 3553 // argument and parameter types are compatible. 3554 if (!S.Context.hasSameUnqualifiedType(ArgType, 3555 ParamType.getNonReferenceType())) { 3556 // We can't perform this conversion or binding. 3557 if (ParamType->isReferenceType()) 3558 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind) 3559 << ParamType << Arg->getType() << Arg->getSourceRange(); 3560 else 3561 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible) 3562 << Arg->getType() << ParamType << Arg->getSourceRange(); 3563 S.Diag(Param->getLocation(), diag::note_template_param_here); 3564 return true; 3565 } 3566 } 3567 3568 // Create the template argument. 3569 Converted = TemplateArgument(Entity->getCanonicalDecl()); 3570 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity); 3571 return false; 3572} 3573 3574/// \brief Checks whether the given template argument is a pointer to 3575/// member constant according to C++ [temp.arg.nontype]p1. 3576bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, 3577 TemplateArgument &Converted) { 3578 bool Invalid = false; 3579 3580 // See through any implicit casts we added to fix the type. 3581 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg)) 3582 Arg = Cast->getSubExpr(); 3583 3584 // C++ [temp.arg.nontype]p1: 3585 // 3586 // A template-argument for a non-type, non-template 3587 // template-parameter shall be one of: [...] 3588 // 3589 // -- a pointer to member expressed as described in 5.3.1. 3590 DeclRefExpr *DRE = 0; 3591 3592 // In C++98/03 mode, give an extension warning on any extra parentheses. 3593 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773 3594 bool ExtraParens = false; 3595 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) { 3596 if (!Invalid && !ExtraParens && !getLangOptions().CPlusPlus0x) { 3597 Diag(Arg->getSourceRange().getBegin(), 3598 diag::ext_template_arg_extra_parens) 3599 << Arg->getSourceRange(); 3600 ExtraParens = true; 3601 } 3602 3603 Arg = Parens->getSubExpr(); 3604 } 3605 3606 // A pointer-to-member constant written &Class::member. 3607 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) { 3608 if (UnOp->getOpcode() == UO_AddrOf) { 3609 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr()); 3610 if (DRE && !DRE->getQualifier()) 3611 DRE = 0; 3612 } 3613 } 3614 // A constant of pointer-to-member type. 3615 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) { 3616 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) { 3617 if (VD->getType()->isMemberPointerType()) { 3618 if (isa<NonTypeTemplateParmDecl>(VD) || 3619 (isa<VarDecl>(VD) && 3620 Context.getCanonicalType(VD->getType()).isConstQualified())) { 3621 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3622 Converted = TemplateArgument(Arg); 3623 else 3624 Converted = TemplateArgument(VD->getCanonicalDecl()); 3625 return Invalid; 3626 } 3627 } 3628 } 3629 3630 DRE = 0; 3631 } 3632 3633 if (!DRE) 3634 return Diag(Arg->getSourceRange().getBegin(), 3635 diag::err_template_arg_not_pointer_to_member_form) 3636 << Arg->getSourceRange(); 3637 3638 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) { 3639 assert((isa<FieldDecl>(DRE->getDecl()) || 3640 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) && 3641 "Only non-static member pointers can make it here"); 3642 3643 // Okay: this is the address of a non-static member, and therefore 3644 // a member pointer constant. 3645 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3646 Converted = TemplateArgument(Arg); 3647 else 3648 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl()); 3649 return Invalid; 3650 } 3651 3652 // We found something else, but we don't know specifically what it is. 3653 Diag(Arg->getSourceRange().getBegin(), 3654 diag::err_template_arg_not_pointer_to_member_form) 3655 << Arg->getSourceRange(); 3656 Diag(DRE->getDecl()->getLocation(), 3657 diag::note_template_arg_refers_here); 3658 return true; 3659} 3660 3661/// \brief Check a template argument against its corresponding 3662/// non-type template parameter. 3663/// 3664/// This routine implements the semantics of C++ [temp.arg.nontype]. 3665/// If an error occurred, it returns ExprError(); otherwise, it 3666/// returns the converted template argument. \p 3667/// InstantiatedParamType is the type of the non-type template 3668/// parameter after it has been instantiated. 3669ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param, 3670 QualType InstantiatedParamType, Expr *Arg, 3671 TemplateArgument &Converted, 3672 CheckTemplateArgumentKind CTAK) { 3673 SourceLocation StartLoc = Arg->getSourceRange().getBegin(); 3674 3675 // If either the parameter has a dependent type or the argument is 3676 // type-dependent, there's nothing we can check now. 3677 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) { 3678 // FIXME: Produce a cloned, canonical expression? 3679 Converted = TemplateArgument(Arg); 3680 return Owned(Arg); 3681 } 3682 3683 // C++ [temp.arg.nontype]p5: 3684 // The following conversions are performed on each expression used 3685 // as a non-type template-argument. If a non-type 3686 // template-argument cannot be converted to the type of the 3687 // corresponding template-parameter then the program is 3688 // ill-formed. 3689 // 3690 // -- for a non-type template-parameter of integral or 3691 // enumeration type, integral promotions (4.5) and integral 3692 // conversions (4.7) are applied. 3693 QualType ParamType = InstantiatedParamType; 3694 QualType ArgType = Arg->getType(); 3695 if (ParamType->isIntegralOrEnumerationType()) { 3696 // C++ [temp.arg.nontype]p1: 3697 // A template-argument for a non-type, non-template 3698 // template-parameter shall be one of: 3699 // 3700 // -- an integral constant-expression of integral or enumeration 3701 // type; or 3702 // -- the name of a non-type template-parameter; or 3703 SourceLocation NonConstantLoc; 3704 llvm::APSInt Value; 3705 if (!ArgType->isIntegralOrEnumerationType()) { 3706 Diag(Arg->getSourceRange().getBegin(), 3707 diag::err_template_arg_not_integral_or_enumeral) 3708 << ArgType << Arg->getSourceRange(); 3709 Diag(Param->getLocation(), diag::note_template_param_here); 3710 return ExprError(); 3711 } else if (!Arg->isValueDependent() && 3712 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) { 3713 Diag(NonConstantLoc, diag::err_template_arg_not_ice) 3714 << ArgType << Arg->getSourceRange(); 3715 return ExprError(); 3716 } 3717 3718 // From here on out, all we care about are the unqualified forms 3719 // of the parameter and argument types. 3720 ParamType = ParamType.getUnqualifiedType(); 3721 ArgType = ArgType.getUnqualifiedType(); 3722 3723 // Try to convert the argument to the parameter's type. 3724 if (Context.hasSameType(ParamType, ArgType)) { 3725 // Okay: no conversion necessary 3726 } else if (CTAK == CTAK_Deduced) { 3727 // C++ [temp.deduct.type]p17: 3728 // If, in the declaration of a function template with a non-type 3729 // template-parameter, the non-type template- parameter is used 3730 // in an expression in the function parameter-list and, if the 3731 // corresponding template-argument is deduced, the 3732 // template-argument type shall match the type of the 3733 // template-parameter exactly, except that a template-argument 3734 // deduced from an array bound may be of any integral type. 3735 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch) 3736 << ArgType << ParamType; 3737 Diag(Param->getLocation(), diag::note_template_param_here); 3738 return ExprError(); 3739 } else if (ParamType->isBooleanType()) { 3740 // This is an integral-to-boolean conversion. 3741 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).take(); 3742 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) || 3743 !ParamType->isEnumeralType()) { 3744 // This is an integral promotion or conversion. 3745 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).take(); 3746 } else { 3747 // We can't perform this conversion. 3748 Diag(Arg->getSourceRange().getBegin(), 3749 diag::err_template_arg_not_convertible) 3750 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange(); 3751 Diag(Param->getLocation(), diag::note_template_param_here); 3752 return ExprError(); 3753 } 3754 3755 // Add the value of this argument to the list of converted 3756 // arguments. We use the bitwidth and signedness of the template 3757 // parameter. 3758 if (Arg->isValueDependent()) { 3759 // The argument is value-dependent. Create a new 3760 // TemplateArgument with the converted expression. 3761 Converted = TemplateArgument(Arg); 3762 return Owned(Arg); 3763 } 3764 3765 QualType IntegerType = Context.getCanonicalType(ParamType); 3766 if (const EnumType *Enum = IntegerType->getAs<EnumType>()) 3767 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType()); 3768 3769 if (ParamType->isBooleanType()) { 3770 // Value must be zero or one. 3771 Value = Value != 0; 3772 unsigned AllowedBits = Context.getTypeSize(IntegerType); 3773 if (Value.getBitWidth() != AllowedBits) 3774 Value = Value.extOrTrunc(AllowedBits); 3775 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType()); 3776 } else { 3777 llvm::APSInt OldValue = Value; 3778 3779 // Coerce the template argument's value to the value it will have 3780 // based on the template parameter's type. 3781 unsigned AllowedBits = Context.getTypeSize(IntegerType); 3782 if (Value.getBitWidth() != AllowedBits) 3783 Value = Value.extOrTrunc(AllowedBits); 3784 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType()); 3785 3786 // Complain if an unsigned parameter received a negative value. 3787 if (IntegerType->isUnsignedIntegerOrEnumerationType() 3788 && (OldValue.isSigned() && OldValue.isNegative())) { 3789 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative) 3790 << OldValue.toString(10) << Value.toString(10) << Param->getType() 3791 << Arg->getSourceRange(); 3792 Diag(Param->getLocation(), diag::note_template_param_here); 3793 } 3794 3795 // Complain if we overflowed the template parameter's type. 3796 unsigned RequiredBits; 3797 if (IntegerType->isUnsignedIntegerOrEnumerationType()) 3798 RequiredBits = OldValue.getActiveBits(); 3799 else if (OldValue.isUnsigned()) 3800 RequiredBits = OldValue.getActiveBits() + 1; 3801 else 3802 RequiredBits = OldValue.getMinSignedBits(); 3803 if (RequiredBits > AllowedBits) { 3804 Diag(Arg->getSourceRange().getBegin(), 3805 diag::warn_template_arg_too_large) 3806 << OldValue.toString(10) << Value.toString(10) << Param->getType() 3807 << Arg->getSourceRange(); 3808 Diag(Param->getLocation(), diag::note_template_param_here); 3809 } 3810 } 3811 3812 Converted = TemplateArgument(Value, 3813 ParamType->isEnumeralType() ? ParamType 3814 : IntegerType); 3815 return Owned(Arg); 3816 } 3817 3818 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction 3819 3820 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion 3821 // from a template argument of type std::nullptr_t to a non-type 3822 // template parameter of type pointer to object, pointer to 3823 // function, or pointer-to-member, respectively. 3824 if (ArgType->isNullPtrType()) { 3825 if (ParamType->isPointerType() || ParamType->isMemberPointerType()) { 3826 Converted = TemplateArgument((NamedDecl *)0); 3827 return Owned(Arg); 3828 } 3829 3830 if (ParamType->isNullPtrType()) { 3831 llvm::APSInt Zero(Context.getTypeSize(Context.NullPtrTy), true); 3832 Converted = TemplateArgument(Zero, Context.NullPtrTy); 3833 return Owned(Arg); 3834 } 3835 } 3836 3837 // Handle pointer-to-function, reference-to-function, and 3838 // pointer-to-member-function all in (roughly) the same way. 3839 if (// -- For a non-type template-parameter of type pointer to 3840 // function, only the function-to-pointer conversion (4.3) is 3841 // applied. If the template-argument represents a set of 3842 // overloaded functions (or a pointer to such), the matching 3843 // function is selected from the set (13.4). 3844 (ParamType->isPointerType() && 3845 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) || 3846 // -- For a non-type template-parameter of type reference to 3847 // function, no conversions apply. If the template-argument 3848 // represents a set of overloaded functions, the matching 3849 // function is selected from the set (13.4). 3850 (ParamType->isReferenceType() && 3851 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) || 3852 // -- For a non-type template-parameter of type pointer to 3853 // member function, no conversions apply. If the 3854 // template-argument represents a set of overloaded member 3855 // functions, the matching member function is selected from 3856 // the set (13.4). 3857 (ParamType->isMemberPointerType() && 3858 ParamType->getAs<MemberPointerType>()->getPointeeType() 3859 ->isFunctionType())) { 3860 3861 if (Arg->getType() == Context.OverloadTy) { 3862 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType, 3863 true, 3864 FoundResult)) { 3865 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin())) 3866 return ExprError(); 3867 3868 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn); 3869 ArgType = Arg->getType(); 3870 } else 3871 return ExprError(); 3872 } 3873 3874 if (!ParamType->isMemberPointerType()) { 3875 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param, 3876 ParamType, 3877 Arg, Converted)) 3878 return ExprError(); 3879 return Owned(Arg); 3880 } 3881 3882 bool ObjCLifetimeConversion; 3883 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType(), 3884 false, ObjCLifetimeConversion)) { 3885 Arg = ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg)).take(); 3886 } else if (!Context.hasSameUnqualifiedType(ArgType, 3887 ParamType.getNonReferenceType())) { 3888 // We can't perform this conversion. 3889 Diag(Arg->getSourceRange().getBegin(), 3890 diag::err_template_arg_not_convertible) 3891 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange(); 3892 Diag(Param->getLocation(), diag::note_template_param_here); 3893 return ExprError(); 3894 } 3895 3896 if (CheckTemplateArgumentPointerToMember(Arg, Converted)) 3897 return ExprError(); 3898 return Owned(Arg); 3899 } 3900 3901 if (ParamType->isPointerType()) { 3902 // -- for a non-type template-parameter of type pointer to 3903 // object, qualification conversions (4.4) and the 3904 // array-to-pointer conversion (4.2) are applied. 3905 // C++0x also allows a value of std::nullptr_t. 3906 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() && 3907 "Only object pointers allowed here"); 3908 3909 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param, 3910 ParamType, 3911 Arg, Converted)) 3912 return ExprError(); 3913 return Owned(Arg); 3914 } 3915 3916 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) { 3917 // -- For a non-type template-parameter of type reference to 3918 // object, no conversions apply. The type referred to by the 3919 // reference may be more cv-qualified than the (otherwise 3920 // identical) type of the template-argument. The 3921 // template-parameter is bound directly to the 3922 // template-argument, which must be an lvalue. 3923 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() && 3924 "Only object references allowed here"); 3925 3926 if (Arg->getType() == Context.OverloadTy) { 3927 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, 3928 ParamRefType->getPointeeType(), 3929 true, 3930 FoundResult)) { 3931 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin())) 3932 return ExprError(); 3933 3934 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn); 3935 ArgType = Arg->getType(); 3936 } else 3937 return ExprError(); 3938 } 3939 3940 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param, 3941 ParamType, 3942 Arg, Converted)) 3943 return ExprError(); 3944 return Owned(Arg); 3945 } 3946 3947 // -- For a non-type template-parameter of type pointer to data 3948 // member, qualification conversions (4.4) are applied. 3949 assert(ParamType->isMemberPointerType() && "Only pointers to members remain"); 3950 3951 bool ObjCLifetimeConversion; 3952 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) { 3953 // Types match exactly: nothing more to do here. 3954 } else if (IsQualificationConversion(ArgType, ParamType, false, 3955 ObjCLifetimeConversion)) { 3956 Arg = ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg)).take(); 3957 } else { 3958 // We can't perform this conversion. 3959 Diag(Arg->getSourceRange().getBegin(), 3960 diag::err_template_arg_not_convertible) 3961 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange(); 3962 Diag(Param->getLocation(), diag::note_template_param_here); 3963 return ExprError(); 3964 } 3965 3966 if (CheckTemplateArgumentPointerToMember(Arg, Converted)) 3967 return ExprError(); 3968 return Owned(Arg); 3969} 3970 3971/// \brief Check a template argument against its corresponding 3972/// template template parameter. 3973/// 3974/// This routine implements the semantics of C++ [temp.arg.template]. 3975/// It returns true if an error occurred, and false otherwise. 3976bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param, 3977 const TemplateArgumentLoc &Arg) { 3978 TemplateName Name = Arg.getArgument().getAsTemplate(); 3979 TemplateDecl *Template = Name.getAsTemplateDecl(); 3980 if (!Template) { 3981 // Any dependent template name is fine. 3982 assert(Name.isDependent() && "Non-dependent template isn't a declaration?"); 3983 return false; 3984 } 3985 3986 // C++0x [temp.arg.template]p1: 3987 // A template-argument for a template template-parameter shall be 3988 // the name of a class template or an alias template, expressed as an 3989 // id-expression. When the template-argument names a class template, only 3990 // primary class templates are considered when matching the 3991 // template template argument with the corresponding parameter; 3992 // partial specializations are not considered even if their 3993 // parameter lists match that of the template template parameter. 3994 // 3995 // Note that we also allow template template parameters here, which 3996 // will happen when we are dealing with, e.g., class template 3997 // partial specializations. 3998 if (!isa<ClassTemplateDecl>(Template) && 3999 !isa<TemplateTemplateParmDecl>(Template) && 4000 !isa<TypeAliasTemplateDecl>(Template)) { 4001 assert(isa<FunctionTemplateDecl>(Template) && 4002 "Only function templates are possible here"); 4003 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template); 4004 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func) 4005 << Template; 4006 } 4007 4008 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(), 4009 Param->getTemplateParameters(), 4010 true, 4011 TPL_TemplateTemplateArgumentMatch, 4012 Arg.getLocation()); 4013} 4014 4015/// \brief Given a non-type template argument that refers to a 4016/// declaration and the type of its corresponding non-type template 4017/// parameter, produce an expression that properly refers to that 4018/// declaration. 4019ExprResult 4020Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, 4021 QualType ParamType, 4022 SourceLocation Loc) { 4023 assert(Arg.getKind() == TemplateArgument::Declaration && 4024 "Only declaration template arguments permitted here"); 4025 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl()); 4026 4027 if (VD->getDeclContext()->isRecord() && 4028 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) { 4029 // If the value is a class member, we might have a pointer-to-member. 4030 // Determine whether the non-type template template parameter is of 4031 // pointer-to-member type. If so, we need to build an appropriate 4032 // expression for a pointer-to-member, since a "normal" DeclRefExpr 4033 // would refer to the member itself. 4034 if (ParamType->isMemberPointerType()) { 4035 QualType ClassType 4036 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext())); 4037 NestedNameSpecifier *Qualifier 4038 = NestedNameSpecifier::Create(Context, 0, false, 4039 ClassType.getTypePtr()); 4040 CXXScopeSpec SS; 4041 SS.MakeTrivial(Context, Qualifier, Loc); 4042 4043 // The actual value-ness of this is unimportant, but for 4044 // internal consistency's sake, references to instance methods 4045 // are r-values. 4046 ExprValueKind VK = VK_LValue; 4047 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance()) 4048 VK = VK_RValue; 4049 4050 ExprResult RefExpr = BuildDeclRefExpr(VD, 4051 VD->getType().getNonReferenceType(), 4052 VK, 4053 Loc, 4054 &SS); 4055 if (RefExpr.isInvalid()) 4056 return ExprError(); 4057 4058 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get()); 4059 4060 // We might need to perform a trailing qualification conversion, since 4061 // the element type on the parameter could be more qualified than the 4062 // element type in the expression we constructed. 4063 bool ObjCLifetimeConversion; 4064 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(), 4065 ParamType.getUnqualifiedType(), false, 4066 ObjCLifetimeConversion)) 4067 RefExpr = ImpCastExprToType(RefExpr.take(), ParamType.getUnqualifiedType(), CK_NoOp); 4068 4069 assert(!RefExpr.isInvalid() && 4070 Context.hasSameType(((Expr*) RefExpr.get())->getType(), 4071 ParamType.getUnqualifiedType())); 4072 return move(RefExpr); 4073 } 4074 } 4075 4076 QualType T = VD->getType().getNonReferenceType(); 4077 if (ParamType->isPointerType()) { 4078 // When the non-type template parameter is a pointer, take the 4079 // address of the declaration. 4080 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc); 4081 if (RefExpr.isInvalid()) 4082 return ExprError(); 4083 4084 if (T->isFunctionType() || T->isArrayType()) { 4085 // Decay functions and arrays. 4086 RefExpr = DefaultFunctionArrayConversion(RefExpr.take()); 4087 if (RefExpr.isInvalid()) 4088 return ExprError(); 4089 4090 return move(RefExpr); 4091 } 4092 4093 // Take the address of everything else 4094 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get()); 4095 } 4096 4097 ExprValueKind VK = VK_RValue; 4098 4099 // If the non-type template parameter has reference type, qualify the 4100 // resulting declaration reference with the extra qualifiers on the 4101 // type that the reference refers to. 4102 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) { 4103 VK = VK_LValue; 4104 T = Context.getQualifiedType(T, 4105 TargetRef->getPointeeType().getQualifiers()); 4106 } 4107 4108 return BuildDeclRefExpr(VD, T, VK, Loc); 4109} 4110 4111/// \brief Construct a new expression that refers to the given 4112/// integral template argument with the given source-location 4113/// information. 4114/// 4115/// This routine takes care of the mapping from an integral template 4116/// argument (which may have any integral type) to the appropriate 4117/// literal value. 4118ExprResult 4119Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, 4120 SourceLocation Loc) { 4121 assert(Arg.getKind() == TemplateArgument::Integral && 4122 "Operation is only valid for integral template arguments"); 4123 QualType T = Arg.getIntegralType(); 4124 if (T->isCharType() || T->isWideCharType()) 4125 return Owned(new (Context) CharacterLiteral( 4126 Arg.getAsIntegral()->getZExtValue(), 4127 T->isWideCharType(), T, Loc)); 4128 if (T->isBooleanType()) 4129 return Owned(new (Context) CXXBoolLiteralExpr( 4130 Arg.getAsIntegral()->getBoolValue(), 4131 T, Loc)); 4132 4133 if (T->isNullPtrType()) 4134 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc)); 4135 4136 // If this is an enum type that we're instantiating, we need to use an integer 4137 // type the same size as the enumerator. We don't want to build an 4138 // IntegerLiteral with enum type. 4139 QualType BT; 4140 if (const EnumType *ET = T->getAs<EnumType>()) 4141 BT = ET->getDecl()->getIntegerType(); 4142 else 4143 BT = T; 4144 4145 Expr *E = IntegerLiteral::Create(Context, *Arg.getAsIntegral(), BT, Loc); 4146 if (T->isEnumeralType()) { 4147 // FIXME: This is a hack. We need a better way to handle substituted 4148 // non-type template parameters. 4149 E = CStyleCastExpr::Create(Context, T, VK_RValue, CK_IntegralCast, E, 0, 4150 Context.getTrivialTypeSourceInfo(T, Loc), 4151 Loc, Loc); 4152 } 4153 4154 return Owned(E); 4155} 4156 4157/// \brief Match two template parameters within template parameter lists. 4158static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old, 4159 bool Complain, 4160 Sema::TemplateParameterListEqualKind Kind, 4161 SourceLocation TemplateArgLoc) { 4162 // Check the actual kind (type, non-type, template). 4163 if (Old->getKind() != New->getKind()) { 4164 if (Complain) { 4165 unsigned NextDiag = diag::err_template_param_different_kind; 4166 if (TemplateArgLoc.isValid()) { 4167 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch); 4168 NextDiag = diag::note_template_param_different_kind; 4169 } 4170 S.Diag(New->getLocation(), NextDiag) 4171 << (Kind != Sema::TPL_TemplateMatch); 4172 S.Diag(Old->getLocation(), diag::note_template_prev_declaration) 4173 << (Kind != Sema::TPL_TemplateMatch); 4174 } 4175 4176 return false; 4177 } 4178 4179 // Check that both are parameter packs are neither are parameter packs. 4180 // However, if we are matching a template template argument to a 4181 // template template parameter, the template template parameter can have 4182 // a parameter pack where the template template argument does not. 4183 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() && 4184 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch && 4185 Old->isTemplateParameterPack())) { 4186 if (Complain) { 4187 unsigned NextDiag = diag::err_template_parameter_pack_non_pack; 4188 if (TemplateArgLoc.isValid()) { 4189 S.Diag(TemplateArgLoc, 4190 diag::err_template_arg_template_params_mismatch); 4191 NextDiag = diag::note_template_parameter_pack_non_pack; 4192 } 4193 4194 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0 4195 : isa<NonTypeTemplateParmDecl>(New)? 1 4196 : 2; 4197 S.Diag(New->getLocation(), NextDiag) 4198 << ParamKind << New->isParameterPack(); 4199 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here) 4200 << ParamKind << Old->isParameterPack(); 4201 } 4202 4203 return false; 4204 } 4205 4206 // For non-type template parameters, check the type of the parameter. 4207 if (NonTypeTemplateParmDecl *OldNTTP 4208 = dyn_cast<NonTypeTemplateParmDecl>(Old)) { 4209 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New); 4210 4211 // If we are matching a template template argument to a template 4212 // template parameter and one of the non-type template parameter types 4213 // is dependent, then we must wait until template instantiation time 4214 // to actually compare the arguments. 4215 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch && 4216 (OldNTTP->getType()->isDependentType() || 4217 NewNTTP->getType()->isDependentType())) 4218 return true; 4219 4220 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) { 4221 if (Complain) { 4222 unsigned NextDiag = diag::err_template_nontype_parm_different_type; 4223 if (TemplateArgLoc.isValid()) { 4224 S.Diag(TemplateArgLoc, 4225 diag::err_template_arg_template_params_mismatch); 4226 NextDiag = diag::note_template_nontype_parm_different_type; 4227 } 4228 S.Diag(NewNTTP->getLocation(), NextDiag) 4229 << NewNTTP->getType() 4230 << (Kind != Sema::TPL_TemplateMatch); 4231 S.Diag(OldNTTP->getLocation(), 4232 diag::note_template_nontype_parm_prev_declaration) 4233 << OldNTTP->getType(); 4234 } 4235 4236 return false; 4237 } 4238 4239 return true; 4240 } 4241 4242 // For template template parameters, check the template parameter types. 4243 // The template parameter lists of template template 4244 // parameters must agree. 4245 if (TemplateTemplateParmDecl *OldTTP 4246 = dyn_cast<TemplateTemplateParmDecl>(Old)) { 4247 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New); 4248 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(), 4249 OldTTP->getTemplateParameters(), 4250 Complain, 4251 (Kind == Sema::TPL_TemplateMatch 4252 ? Sema::TPL_TemplateTemplateParmMatch 4253 : Kind), 4254 TemplateArgLoc); 4255 } 4256 4257 return true; 4258} 4259 4260/// \brief Diagnose a known arity mismatch when comparing template argument 4261/// lists. 4262static 4263void DiagnoseTemplateParameterListArityMismatch(Sema &S, 4264 TemplateParameterList *New, 4265 TemplateParameterList *Old, 4266 Sema::TemplateParameterListEqualKind Kind, 4267 SourceLocation TemplateArgLoc) { 4268 unsigned NextDiag = diag::err_template_param_list_different_arity; 4269 if (TemplateArgLoc.isValid()) { 4270 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch); 4271 NextDiag = diag::note_template_param_list_different_arity; 4272 } 4273 S.Diag(New->getTemplateLoc(), NextDiag) 4274 << (New->size() > Old->size()) 4275 << (Kind != Sema::TPL_TemplateMatch) 4276 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc()); 4277 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration) 4278 << (Kind != Sema::TPL_TemplateMatch) 4279 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc()); 4280} 4281 4282/// \brief Determine whether the given template parameter lists are 4283/// equivalent. 4284/// 4285/// \param New The new template parameter list, typically written in the 4286/// source code as part of a new template declaration. 4287/// 4288/// \param Old The old template parameter list, typically found via 4289/// name lookup of the template declared with this template parameter 4290/// list. 4291/// 4292/// \param Complain If true, this routine will produce a diagnostic if 4293/// the template parameter lists are not equivalent. 4294/// 4295/// \param Kind describes how we are to match the template parameter lists. 4296/// 4297/// \param TemplateArgLoc If this source location is valid, then we 4298/// are actually checking the template parameter list of a template 4299/// argument (New) against the template parameter list of its 4300/// corresponding template template parameter (Old). We produce 4301/// slightly different diagnostics in this scenario. 4302/// 4303/// \returns True if the template parameter lists are equal, false 4304/// otherwise. 4305bool 4306Sema::TemplateParameterListsAreEqual(TemplateParameterList *New, 4307 TemplateParameterList *Old, 4308 bool Complain, 4309 TemplateParameterListEqualKind Kind, 4310 SourceLocation TemplateArgLoc) { 4311 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) { 4312 if (Complain) 4313 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind, 4314 TemplateArgLoc); 4315 4316 return false; 4317 } 4318 4319 // C++0x [temp.arg.template]p3: 4320 // A template-argument matches a template template-parameter (call it P) 4321 // when each of the template parameters in the template-parameter-list of 4322 // the template-argument's corresponding class template or alias template 4323 // (call it A) matches the corresponding template parameter in the 4324 // template-parameter-list of P. [...] 4325 TemplateParameterList::iterator NewParm = New->begin(); 4326 TemplateParameterList::iterator NewParmEnd = New->end(); 4327 for (TemplateParameterList::iterator OldParm = Old->begin(), 4328 OldParmEnd = Old->end(); 4329 OldParm != OldParmEnd; ++OldParm) { 4330 if (Kind != TPL_TemplateTemplateArgumentMatch || 4331 !(*OldParm)->isTemplateParameterPack()) { 4332 if (NewParm == NewParmEnd) { 4333 if (Complain) 4334 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind, 4335 TemplateArgLoc); 4336 4337 return false; 4338 } 4339 4340 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain, 4341 Kind, TemplateArgLoc)) 4342 return false; 4343 4344 ++NewParm; 4345 continue; 4346 } 4347 4348 // C++0x [temp.arg.template]p3: 4349 // [...] When P's template- parameter-list contains a template parameter 4350 // pack (14.5.3), the template parameter pack will match zero or more 4351 // template parameters or template parameter packs in the 4352 // template-parameter-list of A with the same type and form as the 4353 // template parameter pack in P (ignoring whether those template 4354 // parameters are template parameter packs). 4355 for (; NewParm != NewParmEnd; ++NewParm) { 4356 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain, 4357 Kind, TemplateArgLoc)) 4358 return false; 4359 } 4360 } 4361 4362 // Make sure we exhausted all of the arguments. 4363 if (NewParm != NewParmEnd) { 4364 if (Complain) 4365 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind, 4366 TemplateArgLoc); 4367 4368 return false; 4369 } 4370 4371 return true; 4372} 4373 4374/// \brief Check whether a template can be declared within this scope. 4375/// 4376/// If the template declaration is valid in this scope, returns 4377/// false. Otherwise, issues a diagnostic and returns true. 4378bool 4379Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) { 4380 // Find the nearest enclosing declaration scope. 4381 while ((S->getFlags() & Scope::DeclScope) == 0 || 4382 (S->getFlags() & Scope::TemplateParamScope) != 0) 4383 S = S->getParent(); 4384 4385 // C++ [temp]p2: 4386 // A template-declaration can appear only as a namespace scope or 4387 // class scope declaration. 4388 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity()); 4389 if (Ctx && isa<LinkageSpecDecl>(Ctx) && 4390 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx) 4391 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage) 4392 << TemplateParams->getSourceRange(); 4393 4394 while (Ctx && isa<LinkageSpecDecl>(Ctx)) 4395 Ctx = Ctx->getParent(); 4396 4397 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord())) 4398 return false; 4399 4400 return Diag(TemplateParams->getTemplateLoc(), 4401 diag::err_template_outside_namespace_or_class_scope) 4402 << TemplateParams->getSourceRange(); 4403} 4404 4405/// \brief Determine what kind of template specialization the given declaration 4406/// is. 4407static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) { 4408 if (!D) 4409 return TSK_Undeclared; 4410 4411 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) 4412 return Record->getTemplateSpecializationKind(); 4413 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) 4414 return Function->getTemplateSpecializationKind(); 4415 if (VarDecl *Var = dyn_cast<VarDecl>(D)) 4416 return Var->getTemplateSpecializationKind(); 4417 4418 return TSK_Undeclared; 4419} 4420 4421/// \brief Check whether a specialization is well-formed in the current 4422/// context. 4423/// 4424/// This routine determines whether a template specialization can be declared 4425/// in the current context (C++ [temp.expl.spec]p2). 4426/// 4427/// \param S the semantic analysis object for which this check is being 4428/// performed. 4429/// 4430/// \param Specialized the entity being specialized or instantiated, which 4431/// may be a kind of template (class template, function template, etc.) or 4432/// a member of a class template (member function, static data member, 4433/// member class). 4434/// 4435/// \param PrevDecl the previous declaration of this entity, if any. 4436/// 4437/// \param Loc the location of the explicit specialization or instantiation of 4438/// this entity. 4439/// 4440/// \param IsPartialSpecialization whether this is a partial specialization of 4441/// a class template. 4442/// 4443/// \returns true if there was an error that we cannot recover from, false 4444/// otherwise. 4445static bool CheckTemplateSpecializationScope(Sema &S, 4446 NamedDecl *Specialized, 4447 NamedDecl *PrevDecl, 4448 SourceLocation Loc, 4449 bool IsPartialSpecialization) { 4450 // Keep these "kind" numbers in sync with the %select statements in the 4451 // various diagnostics emitted by this routine. 4452 int EntityKind = 0; 4453 if (isa<ClassTemplateDecl>(Specialized)) 4454 EntityKind = IsPartialSpecialization? 1 : 0; 4455 else if (isa<FunctionTemplateDecl>(Specialized)) 4456 EntityKind = 2; 4457 else if (isa<CXXMethodDecl>(Specialized)) 4458 EntityKind = 3; 4459 else if (isa<VarDecl>(Specialized)) 4460 EntityKind = 4; 4461 else if (isa<RecordDecl>(Specialized)) 4462 EntityKind = 5; 4463 else { 4464 S.Diag(Loc, diag::err_template_spec_unknown_kind); 4465 S.Diag(Specialized->getLocation(), diag::note_specialized_entity); 4466 return true; 4467 } 4468 4469 // C++ [temp.expl.spec]p2: 4470 // An explicit specialization shall be declared in the namespace 4471 // of which the template is a member, or, for member templates, in 4472 // the namespace of which the enclosing class or enclosing class 4473 // template is a member. An explicit specialization of a member 4474 // function, member class or static data member of a class 4475 // template shall be declared in the namespace of which the class 4476 // template is a member. Such a declaration may also be a 4477 // definition. If the declaration is not a definition, the 4478 // specialization may be defined later in the name- space in which 4479 // the explicit specialization was declared, or in a namespace 4480 // that encloses the one in which the explicit specialization was 4481 // declared. 4482 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) { 4483 S.Diag(Loc, diag::err_template_spec_decl_function_scope) 4484 << Specialized; 4485 return true; 4486 } 4487 4488 if (S.CurContext->isRecord() && !IsPartialSpecialization) { 4489 S.Diag(Loc, diag::err_template_spec_decl_class_scope) 4490 << Specialized; 4491 return true; 4492 } 4493 4494 // C++ [temp.class.spec]p6: 4495 // A class template partial specialization may be declared or redeclared 4496 // in any namespace scope in which its definition may be defined (14.5.1 4497 // and 14.5.2). 4498 bool ComplainedAboutScope = false; 4499 DeclContext *SpecializedContext 4500 = Specialized->getDeclContext()->getEnclosingNamespaceContext(); 4501 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext(); 4502 if ((!PrevDecl || 4503 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared || 4504 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){ 4505 // C++ [temp.exp.spec]p2: 4506 // An explicit specialization shall be declared in the namespace of which 4507 // the template is a member, or, for member templates, in the namespace 4508 // of which the enclosing class or enclosing class template is a member. 4509 // An explicit specialization of a member function, member class or 4510 // static data member of a class template shall be declared in the 4511 // namespace of which the class template is a member. 4512 // 4513 // C++0x [temp.expl.spec]p2: 4514 // An explicit specialization shall be declared in a namespace enclosing 4515 // the specialized template. 4516 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext) && 4517 !(S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext))) { 4518 bool IsCPlusPlus0xExtension 4519 = !S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext); 4520 if (isa<TranslationUnitDecl>(SpecializedContext)) 4521 S.Diag(Loc, IsCPlusPlus0xExtension 4522 ? diag::ext_template_spec_decl_out_of_scope_global 4523 : diag::err_template_spec_decl_out_of_scope_global) 4524 << EntityKind << Specialized; 4525 else if (isa<NamespaceDecl>(SpecializedContext)) 4526 S.Diag(Loc, IsCPlusPlus0xExtension 4527 ? diag::ext_template_spec_decl_out_of_scope 4528 : diag::err_template_spec_decl_out_of_scope) 4529 << EntityKind << Specialized 4530 << cast<NamedDecl>(SpecializedContext); 4531 4532 S.Diag(Specialized->getLocation(), diag::note_specialized_entity); 4533 ComplainedAboutScope = true; 4534 } 4535 } 4536 4537 // Make sure that this redeclaration (or definition) occurs in an enclosing 4538 // namespace. 4539 // Note that HandleDeclarator() performs this check for explicit 4540 // specializations of function templates, static data members, and member 4541 // functions, so we skip the check here for those kinds of entities. 4542 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though. 4543 // Should we refactor that check, so that it occurs later? 4544 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) && 4545 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) || 4546 isa<FunctionDecl>(Specialized))) { 4547 if (isa<TranslationUnitDecl>(SpecializedContext)) 4548 S.Diag(Loc, diag::err_template_spec_redecl_global_scope) 4549 << EntityKind << Specialized; 4550 else if (isa<NamespaceDecl>(SpecializedContext)) 4551 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope) 4552 << EntityKind << Specialized 4553 << cast<NamedDecl>(SpecializedContext); 4554 4555 S.Diag(Specialized->getLocation(), diag::note_specialized_entity); 4556 } 4557 4558 // FIXME: check for specialization-after-instantiation errors and such. 4559 4560 return false; 4561} 4562 4563/// \brief Subroutine of Sema::CheckClassTemplatePartialSpecializationArgs 4564/// that checks non-type template partial specialization arguments. 4565static bool CheckNonTypeClassTemplatePartialSpecializationArgs(Sema &S, 4566 NonTypeTemplateParmDecl *Param, 4567 const TemplateArgument *Args, 4568 unsigned NumArgs) { 4569 for (unsigned I = 0; I != NumArgs; ++I) { 4570 if (Args[I].getKind() == TemplateArgument::Pack) { 4571 if (CheckNonTypeClassTemplatePartialSpecializationArgs(S, Param, 4572 Args[I].pack_begin(), 4573 Args[I].pack_size())) 4574 return true; 4575 4576 continue; 4577 } 4578 4579 Expr *ArgExpr = Args[I].getAsExpr(); 4580 if (!ArgExpr) { 4581 continue; 4582 } 4583 4584 // We can have a pack expansion of any of the bullets below. 4585 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr)) 4586 ArgExpr = Expansion->getPattern(); 4587 4588 // Strip off any implicit casts we added as part of type checking. 4589 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 4590 ArgExpr = ICE->getSubExpr(); 4591 4592 // C++ [temp.class.spec]p8: 4593 // A non-type argument is non-specialized if it is the name of a 4594 // non-type parameter. All other non-type arguments are 4595 // specialized. 4596 // 4597 // Below, we check the two conditions that only apply to 4598 // specialized non-type arguments, so skip any non-specialized 4599 // arguments. 4600 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr)) 4601 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl())) 4602 continue; 4603 4604 // C++ [temp.class.spec]p9: 4605 // Within the argument list of a class template partial 4606 // specialization, the following restrictions apply: 4607 // -- A partially specialized non-type argument expression 4608 // shall not involve a template parameter of the partial 4609 // specialization except when the argument expression is a 4610 // simple identifier. 4611 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) { 4612 S.Diag(ArgExpr->getLocStart(), 4613 diag::err_dependent_non_type_arg_in_partial_spec) 4614 << ArgExpr->getSourceRange(); 4615 return true; 4616 } 4617 4618 // -- The type of a template parameter corresponding to a 4619 // specialized non-type argument shall not be dependent on a 4620 // parameter of the specialization. 4621 if (Param->getType()->isDependentType()) { 4622 S.Diag(ArgExpr->getLocStart(), 4623 diag::err_dependent_typed_non_type_arg_in_partial_spec) 4624 << Param->getType() 4625 << ArgExpr->getSourceRange(); 4626 S.Diag(Param->getLocation(), diag::note_template_param_here); 4627 return true; 4628 } 4629 } 4630 4631 return false; 4632} 4633 4634/// \brief Check the non-type template arguments of a class template 4635/// partial specialization according to C++ [temp.class.spec]p9. 4636/// 4637/// \param TemplateParams the template parameters of the primary class 4638/// template. 4639/// 4640/// \param TemplateArg the template arguments of the class template 4641/// partial specialization. 4642/// 4643/// \returns true if there was an error, false otherwise. 4644static bool CheckClassTemplatePartialSpecializationArgs(Sema &S, 4645 TemplateParameterList *TemplateParams, 4646 llvm::SmallVectorImpl<TemplateArgument> &TemplateArgs) { 4647 const TemplateArgument *ArgList = TemplateArgs.data(); 4648 4649 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) { 4650 NonTypeTemplateParmDecl *Param 4651 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I)); 4652 if (!Param) 4653 continue; 4654 4655 if (CheckNonTypeClassTemplatePartialSpecializationArgs(S, Param, 4656 &ArgList[I], 1)) 4657 return true; 4658 } 4659 4660 return false; 4661} 4662 4663/// \brief Retrieve the previous declaration of the given declaration. 4664static NamedDecl *getPreviousDecl(NamedDecl *ND) { 4665 if (VarDecl *VD = dyn_cast<VarDecl>(ND)) 4666 return VD->getPreviousDeclaration(); 4667 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) 4668 return FD->getPreviousDeclaration(); 4669 if (TagDecl *TD = dyn_cast<TagDecl>(ND)) 4670 return TD->getPreviousDeclaration(); 4671 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 4672 return TD->getPreviousDeclaration(); 4673 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 4674 return FTD->getPreviousDeclaration(); 4675 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND)) 4676 return CTD->getPreviousDeclaration(); 4677 return 0; 4678} 4679 4680DeclResult 4681Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, 4682 TagUseKind TUK, 4683 SourceLocation KWLoc, 4684 CXXScopeSpec &SS, 4685 TemplateTy TemplateD, 4686 SourceLocation TemplateNameLoc, 4687 SourceLocation LAngleLoc, 4688 ASTTemplateArgsPtr TemplateArgsIn, 4689 SourceLocation RAngleLoc, 4690 AttributeList *Attr, 4691 MultiTemplateParamsArg TemplateParameterLists) { 4692 assert(TUK != TUK_Reference && "References are not specializations"); 4693 4694 // NOTE: KWLoc is the location of the tag keyword. This will instead 4695 // store the location of the outermost template keyword in the declaration. 4696 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0 4697 ? TemplateParameterLists.get()[0]->getTemplateLoc() : SourceLocation(); 4698 4699 // Find the class template we're specializing 4700 TemplateName Name = TemplateD.getAsVal<TemplateName>(); 4701 ClassTemplateDecl *ClassTemplate 4702 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl()); 4703 4704 if (!ClassTemplate) { 4705 Diag(TemplateNameLoc, diag::err_not_class_template_specialization) 4706 << (Name.getAsTemplateDecl() && 4707 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())); 4708 return true; 4709 } 4710 4711 bool isExplicitSpecialization = false; 4712 bool isPartialSpecialization = false; 4713 4714 // Check the validity of the template headers that introduce this 4715 // template. 4716 // FIXME: We probably shouldn't complain about these headers for 4717 // friend declarations. 4718 bool Invalid = false; 4719 TemplateParameterList *TemplateParams 4720 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, 4721 TemplateNameLoc, 4722 SS, 4723 (TemplateParameterList**)TemplateParameterLists.get(), 4724 TemplateParameterLists.size(), 4725 TUK == TUK_Friend, 4726 isExplicitSpecialization, 4727 Invalid); 4728 if (Invalid) 4729 return true; 4730 4731 if (TemplateParams && TemplateParams->size() > 0) { 4732 isPartialSpecialization = true; 4733 4734 if (TUK == TUK_Friend) { 4735 Diag(KWLoc, diag::err_partial_specialization_friend) 4736 << SourceRange(LAngleLoc, RAngleLoc); 4737 return true; 4738 } 4739 4740 // C++ [temp.class.spec]p10: 4741 // The template parameter list of a specialization shall not 4742 // contain default template argument values. 4743 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) { 4744 Decl *Param = TemplateParams->getParam(I); 4745 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) { 4746 if (TTP->hasDefaultArgument()) { 4747 Diag(TTP->getDefaultArgumentLoc(), 4748 diag::err_default_arg_in_partial_spec); 4749 TTP->removeDefaultArgument(); 4750 } 4751 } else if (NonTypeTemplateParmDecl *NTTP 4752 = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 4753 if (Expr *DefArg = NTTP->getDefaultArgument()) { 4754 Diag(NTTP->getDefaultArgumentLoc(), 4755 diag::err_default_arg_in_partial_spec) 4756 << DefArg->getSourceRange(); 4757 NTTP->removeDefaultArgument(); 4758 } 4759 } else { 4760 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param); 4761 if (TTP->hasDefaultArgument()) { 4762 Diag(TTP->getDefaultArgument().getLocation(), 4763 diag::err_default_arg_in_partial_spec) 4764 << TTP->getDefaultArgument().getSourceRange(); 4765 TTP->removeDefaultArgument(); 4766 } 4767 } 4768 } 4769 } else if (TemplateParams) { 4770 if (TUK == TUK_Friend) 4771 Diag(KWLoc, diag::err_template_spec_friend) 4772 << FixItHint::CreateRemoval( 4773 SourceRange(TemplateParams->getTemplateLoc(), 4774 TemplateParams->getRAngleLoc())) 4775 << SourceRange(LAngleLoc, RAngleLoc); 4776 else 4777 isExplicitSpecialization = true; 4778 } else if (TUK != TUK_Friend) { 4779 Diag(KWLoc, diag::err_template_spec_needs_header) 4780 << FixItHint::CreateInsertion(KWLoc, "template<> "); 4781 isExplicitSpecialization = true; 4782 } 4783 4784 // Check that the specialization uses the same tag kind as the 4785 // original template. 4786 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 4787 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!"); 4788 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), 4789 Kind, TUK == TUK_Definition, KWLoc, 4790 *ClassTemplate->getIdentifier())) { 4791 Diag(KWLoc, diag::err_use_with_wrong_tag) 4792 << ClassTemplate 4793 << FixItHint::CreateReplacement(KWLoc, 4794 ClassTemplate->getTemplatedDecl()->getKindName()); 4795 Diag(ClassTemplate->getTemplatedDecl()->getLocation(), 4796 diag::note_previous_use); 4797 Kind = ClassTemplate->getTemplatedDecl()->getTagKind(); 4798 } 4799 4800 // Translate the parser's template argument list in our AST format. 4801 TemplateArgumentListInfo TemplateArgs; 4802 TemplateArgs.setLAngleLoc(LAngleLoc); 4803 TemplateArgs.setRAngleLoc(RAngleLoc); 4804 translateTemplateArguments(TemplateArgsIn, TemplateArgs); 4805 4806 // Check for unexpanded parameter packs in any of the template arguments. 4807 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 4808 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I], 4809 UPPC_PartialSpecialization)) 4810 return true; 4811 4812 // Check that the template argument list is well-formed for this 4813 // template. 4814 llvm::SmallVector<TemplateArgument, 4> Converted; 4815 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, 4816 TemplateArgs, false, Converted)) 4817 return true; 4818 4819 assert((Converted.size() == ClassTemplate->getTemplateParameters()->size()) && 4820 "Converted template argument list is too short!"); 4821 4822 // Find the class template (partial) specialization declaration that 4823 // corresponds to these arguments. 4824 if (isPartialSpecialization) { 4825 if (CheckClassTemplatePartialSpecializationArgs(*this, 4826 ClassTemplate->getTemplateParameters(), 4827 Converted)) 4828 return true; 4829 4830 if (!Name.isDependent() && 4831 !TemplateSpecializationType::anyDependentTemplateArguments( 4832 TemplateArgs.getArgumentArray(), 4833 TemplateArgs.size())) { 4834 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized) 4835 << ClassTemplate->getDeclName(); 4836 isPartialSpecialization = false; 4837 } 4838 } 4839 4840 void *InsertPos = 0; 4841 ClassTemplateSpecializationDecl *PrevDecl = 0; 4842 4843 if (isPartialSpecialization) 4844 // FIXME: Template parameter list matters, too 4845 PrevDecl 4846 = ClassTemplate->findPartialSpecialization(Converted.data(), 4847 Converted.size(), 4848 InsertPos); 4849 else 4850 PrevDecl 4851 = ClassTemplate->findSpecialization(Converted.data(), 4852 Converted.size(), InsertPos); 4853 4854 ClassTemplateSpecializationDecl *Specialization = 0; 4855 4856 // Check whether we can declare a class template specialization in 4857 // the current scope. 4858 if (TUK != TUK_Friend && 4859 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl, 4860 TemplateNameLoc, 4861 isPartialSpecialization)) 4862 return true; 4863 4864 // The canonical type 4865 QualType CanonType; 4866 if (PrevDecl && 4867 (PrevDecl->getSpecializationKind() == TSK_Undeclared || 4868 TUK == TUK_Friend)) { 4869 // Since the only prior class template specialization with these 4870 // arguments was referenced but not declared, or we're only 4871 // referencing this specialization as a friend, reuse that 4872 // declaration node as our own, updating its source location and 4873 // the list of outer template parameters to reflect our new declaration. 4874 Specialization = PrevDecl; 4875 Specialization->setLocation(TemplateNameLoc); 4876 if (TemplateParameterLists.size() > 0) { 4877 Specialization->setTemplateParameterListsInfo(Context, 4878 TemplateParameterLists.size(), 4879 (TemplateParameterList**) TemplateParameterLists.release()); 4880 } 4881 PrevDecl = 0; 4882 CanonType = Context.getTypeDeclType(Specialization); 4883 } else if (isPartialSpecialization) { 4884 // Build the canonical type that describes the converted template 4885 // arguments of the class template partial specialization. 4886 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name); 4887 CanonType = Context.getTemplateSpecializationType(CanonTemplate, 4888 Converted.data(), 4889 Converted.size()); 4890 4891 if (Context.hasSameType(CanonType, 4892 ClassTemplate->getInjectedClassNameSpecialization())) { 4893 // C++ [temp.class.spec]p9b3: 4894 // 4895 // -- The argument list of the specialization shall not be identical 4896 // to the implicit argument list of the primary template. 4897 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template) 4898 << (TUK == TUK_Definition) 4899 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc)); 4900 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS, 4901 ClassTemplate->getIdentifier(), 4902 TemplateNameLoc, 4903 Attr, 4904 TemplateParams, 4905 AS_none, 4906 TemplateParameterLists.size() - 1, 4907 (TemplateParameterList**) TemplateParameterLists.release()); 4908 } 4909 4910 // Create a new class template partial specialization declaration node. 4911 ClassTemplatePartialSpecializationDecl *PrevPartial 4912 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl); 4913 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber() 4914 : ClassTemplate->getNextPartialSpecSequenceNumber(); 4915 ClassTemplatePartialSpecializationDecl *Partial 4916 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind, 4917 ClassTemplate->getDeclContext(), 4918 KWLoc, TemplateNameLoc, 4919 TemplateParams, 4920 ClassTemplate, 4921 Converted.data(), 4922 Converted.size(), 4923 TemplateArgs, 4924 CanonType, 4925 PrevPartial, 4926 SequenceNumber); 4927 SetNestedNameSpecifier(Partial, SS); 4928 if (TemplateParameterLists.size() > 1 && SS.isSet()) { 4929 Partial->setTemplateParameterListsInfo(Context, 4930 TemplateParameterLists.size() - 1, 4931 (TemplateParameterList**) TemplateParameterLists.release()); 4932 } 4933 4934 if (!PrevPartial) 4935 ClassTemplate->AddPartialSpecialization(Partial, InsertPos); 4936 Specialization = Partial; 4937 4938 // If we are providing an explicit specialization of a member class 4939 // template specialization, make a note of that. 4940 if (PrevPartial && PrevPartial->getInstantiatedFromMember()) 4941 PrevPartial->setMemberSpecialization(); 4942 4943 // Check that all of the template parameters of the class template 4944 // partial specialization are deducible from the template 4945 // arguments. If not, this class template partial specialization 4946 // will never be used. 4947 llvm::SmallVector<bool, 8> DeducibleParams; 4948 DeducibleParams.resize(TemplateParams->size()); 4949 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true, 4950 TemplateParams->getDepth(), 4951 DeducibleParams); 4952 unsigned NumNonDeducible = 0; 4953 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) 4954 if (!DeducibleParams[I]) 4955 ++NumNonDeducible; 4956 4957 if (NumNonDeducible) { 4958 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible) 4959 << (NumNonDeducible > 1) 4960 << SourceRange(TemplateNameLoc, RAngleLoc); 4961 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) { 4962 if (!DeducibleParams[I]) { 4963 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I)); 4964 if (Param->getDeclName()) 4965 Diag(Param->getLocation(), 4966 diag::note_partial_spec_unused_parameter) 4967 << Param->getDeclName(); 4968 else 4969 Diag(Param->getLocation(), 4970 diag::note_partial_spec_unused_parameter) 4971 << "<anonymous>"; 4972 } 4973 } 4974 } 4975 } else { 4976 // Create a new class template specialization declaration node for 4977 // this explicit specialization or friend declaration. 4978 Specialization 4979 = ClassTemplateSpecializationDecl::Create(Context, Kind, 4980 ClassTemplate->getDeclContext(), 4981 KWLoc, TemplateNameLoc, 4982 ClassTemplate, 4983 Converted.data(), 4984 Converted.size(), 4985 PrevDecl); 4986 SetNestedNameSpecifier(Specialization, SS); 4987 if (TemplateParameterLists.size() > 0) { 4988 Specialization->setTemplateParameterListsInfo(Context, 4989 TemplateParameterLists.size(), 4990 (TemplateParameterList**) TemplateParameterLists.release()); 4991 } 4992 4993 if (!PrevDecl) 4994 ClassTemplate->AddSpecialization(Specialization, InsertPos); 4995 4996 CanonType = Context.getTypeDeclType(Specialization); 4997 } 4998 4999 // C++ [temp.expl.spec]p6: 5000 // If a template, a member template or the member of a class template is 5001 // explicitly specialized then that specialization shall be declared 5002 // before the first use of that specialization that would cause an implicit 5003 // instantiation to take place, in every translation unit in which such a 5004 // use occurs; no diagnostic is required. 5005 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) { 5006 bool Okay = false; 5007 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) { 5008 // Is there any previous explicit specialization declaration? 5009 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) { 5010 Okay = true; 5011 break; 5012 } 5013 } 5014 5015 if (!Okay) { 5016 SourceRange Range(TemplateNameLoc, RAngleLoc); 5017 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation) 5018 << Context.getTypeDeclType(Specialization) << Range; 5019 5020 Diag(PrevDecl->getPointOfInstantiation(), 5021 diag::note_instantiation_required_here) 5022 << (PrevDecl->getTemplateSpecializationKind() 5023 != TSK_ImplicitInstantiation); 5024 return true; 5025 } 5026 } 5027 5028 // If this is not a friend, note that this is an explicit specialization. 5029 if (TUK != TUK_Friend) 5030 Specialization->setSpecializationKind(TSK_ExplicitSpecialization); 5031 5032 // Check that this isn't a redefinition of this specialization. 5033 if (TUK == TUK_Definition) { 5034 if (RecordDecl *Def = Specialization->getDefinition()) { 5035 SourceRange Range(TemplateNameLoc, RAngleLoc); 5036 Diag(TemplateNameLoc, diag::err_redefinition) 5037 << Context.getTypeDeclType(Specialization) << Range; 5038 Diag(Def->getLocation(), diag::note_previous_definition); 5039 Specialization->setInvalidDecl(); 5040 return true; 5041 } 5042 } 5043 5044 if (Attr) 5045 ProcessDeclAttributeList(S, Specialization, Attr); 5046 5047 // Build the fully-sugared type for this class template 5048 // specialization as the user wrote in the specialization 5049 // itself. This means that we'll pretty-print the type retrieved 5050 // from the specialization's declaration the way that the user 5051 // actually wrote the specialization, rather than formatting the 5052 // name based on the "canonical" representation used to store the 5053 // template arguments in the specialization. 5054 TypeSourceInfo *WrittenTy 5055 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc, 5056 TemplateArgs, CanonType); 5057 if (TUK != TUK_Friend) { 5058 Specialization->setTypeAsWritten(WrittenTy); 5059 Specialization->setTemplateKeywordLoc(TemplateKWLoc); 5060 } 5061 TemplateArgsIn.release(); 5062 5063 // C++ [temp.expl.spec]p9: 5064 // A template explicit specialization is in the scope of the 5065 // namespace in which the template was defined. 5066 // 5067 // We actually implement this paragraph where we set the semantic 5068 // context (in the creation of the ClassTemplateSpecializationDecl), 5069 // but we also maintain the lexical context where the actual 5070 // definition occurs. 5071 Specialization->setLexicalDeclContext(CurContext); 5072 5073 // We may be starting the definition of this specialization. 5074 if (TUK == TUK_Definition) 5075 Specialization->startDefinition(); 5076 5077 if (TUK == TUK_Friend) { 5078 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, 5079 TemplateNameLoc, 5080 WrittenTy, 5081 /*FIXME:*/KWLoc); 5082 Friend->setAccess(AS_public); 5083 CurContext->addDecl(Friend); 5084 } else { 5085 // Add the specialization into its lexical context, so that it can 5086 // be seen when iterating through the list of declarations in that 5087 // context. However, specializations are not found by name lookup. 5088 CurContext->addDecl(Specialization); 5089 } 5090 return Specialization; 5091} 5092 5093Decl *Sema::ActOnTemplateDeclarator(Scope *S, 5094 MultiTemplateParamsArg TemplateParameterLists, 5095 Declarator &D) { 5096 return HandleDeclarator(S, D, move(TemplateParameterLists), false); 5097} 5098 5099Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope, 5100 MultiTemplateParamsArg TemplateParameterLists, 5101 Declarator &D) { 5102 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 5103 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 5104 5105 if (FTI.hasPrototype) { 5106 // FIXME: Diagnose arguments without names in C. 5107 } 5108 5109 Scope *ParentScope = FnBodyScope->getParent(); 5110 5111 Decl *DP = HandleDeclarator(ParentScope, D, 5112 move(TemplateParameterLists), 5113 /*IsFunctionDefinition=*/true); 5114 if (FunctionTemplateDecl *FunctionTemplate 5115 = dyn_cast_or_null<FunctionTemplateDecl>(DP)) 5116 return ActOnStartOfFunctionDef(FnBodyScope, 5117 FunctionTemplate->getTemplatedDecl()); 5118 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP)) 5119 return ActOnStartOfFunctionDef(FnBodyScope, Function); 5120 return 0; 5121} 5122 5123/// \brief Strips various properties off an implicit instantiation 5124/// that has just been explicitly specialized. 5125static void StripImplicitInstantiation(NamedDecl *D) { 5126 D->dropAttrs(); 5127 5128 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 5129 FD->setInlineSpecified(false); 5130 } 5131} 5132 5133/// \brief Diagnose cases where we have an explicit template specialization 5134/// before/after an explicit template instantiation, producing diagnostics 5135/// for those cases where they are required and determining whether the 5136/// new specialization/instantiation will have any effect. 5137/// 5138/// \param NewLoc the location of the new explicit specialization or 5139/// instantiation. 5140/// 5141/// \param NewTSK the kind of the new explicit specialization or instantiation. 5142/// 5143/// \param PrevDecl the previous declaration of the entity. 5144/// 5145/// \param PrevTSK the kind of the old explicit specialization or instantiatin. 5146/// 5147/// \param PrevPointOfInstantiation if valid, indicates where the previus 5148/// declaration was instantiated (either implicitly or explicitly). 5149/// 5150/// \param HasNoEffect will be set to true to indicate that the new 5151/// specialization or instantiation has no effect and should be ignored. 5152/// 5153/// \returns true if there was an error that should prevent the introduction of 5154/// the new declaration into the AST, false otherwise. 5155bool 5156Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, 5157 TemplateSpecializationKind NewTSK, 5158 NamedDecl *PrevDecl, 5159 TemplateSpecializationKind PrevTSK, 5160 SourceLocation PrevPointOfInstantiation, 5161 bool &HasNoEffect) { 5162 HasNoEffect = false; 5163 5164 switch (NewTSK) { 5165 case TSK_Undeclared: 5166 case TSK_ImplicitInstantiation: 5167 assert(false && "Don't check implicit instantiations here"); 5168 return false; 5169 5170 case TSK_ExplicitSpecialization: 5171 switch (PrevTSK) { 5172 case TSK_Undeclared: 5173 case TSK_ExplicitSpecialization: 5174 // Okay, we're just specializing something that is either already 5175 // explicitly specialized or has merely been mentioned without any 5176 // instantiation. 5177 return false; 5178 5179 case TSK_ImplicitInstantiation: 5180 if (PrevPointOfInstantiation.isInvalid()) { 5181 // The declaration itself has not actually been instantiated, so it is 5182 // still okay to specialize it. 5183 StripImplicitInstantiation(PrevDecl); 5184 return false; 5185 } 5186 // Fall through 5187 5188 case TSK_ExplicitInstantiationDeclaration: 5189 case TSK_ExplicitInstantiationDefinition: 5190 assert((PrevTSK == TSK_ImplicitInstantiation || 5191 PrevPointOfInstantiation.isValid()) && 5192 "Explicit instantiation without point of instantiation?"); 5193 5194 // C++ [temp.expl.spec]p6: 5195 // If a template, a member template or the member of a class template 5196 // is explicitly specialized then that specialization shall be declared 5197 // before the first use of that specialization that would cause an 5198 // implicit instantiation to take place, in every translation unit in 5199 // which such a use occurs; no diagnostic is required. 5200 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) { 5201 // Is there any previous explicit specialization declaration? 5202 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) 5203 return false; 5204 } 5205 5206 Diag(NewLoc, diag::err_specialization_after_instantiation) 5207 << PrevDecl; 5208 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here) 5209 << (PrevTSK != TSK_ImplicitInstantiation); 5210 5211 return true; 5212 } 5213 break; 5214 5215 case TSK_ExplicitInstantiationDeclaration: 5216 switch (PrevTSK) { 5217 case TSK_ExplicitInstantiationDeclaration: 5218 // This explicit instantiation declaration is redundant (that's okay). 5219 HasNoEffect = true; 5220 return false; 5221 5222 case TSK_Undeclared: 5223 case TSK_ImplicitInstantiation: 5224 // We're explicitly instantiating something that may have already been 5225 // implicitly instantiated; that's fine. 5226 return false; 5227 5228 case TSK_ExplicitSpecialization: 5229 // C++0x [temp.explicit]p4: 5230 // For a given set of template parameters, if an explicit instantiation 5231 // of a template appears after a declaration of an explicit 5232 // specialization for that template, the explicit instantiation has no 5233 // effect. 5234 HasNoEffect = true; 5235 return false; 5236 5237 case TSK_ExplicitInstantiationDefinition: 5238 // C++0x [temp.explicit]p10: 5239 // If an entity is the subject of both an explicit instantiation 5240 // declaration and an explicit instantiation definition in the same 5241 // translation unit, the definition shall follow the declaration. 5242 Diag(NewLoc, 5243 diag::err_explicit_instantiation_declaration_after_definition); 5244 Diag(PrevPointOfInstantiation, 5245 diag::note_explicit_instantiation_definition_here); 5246 assert(PrevPointOfInstantiation.isValid() && 5247 "Explicit instantiation without point of instantiation?"); 5248 HasNoEffect = true; 5249 return false; 5250 } 5251 break; 5252 5253 case TSK_ExplicitInstantiationDefinition: 5254 switch (PrevTSK) { 5255 case TSK_Undeclared: 5256 case TSK_ImplicitInstantiation: 5257 // We're explicitly instantiating something that may have already been 5258 // implicitly instantiated; that's fine. 5259 return false; 5260 5261 case TSK_ExplicitSpecialization: 5262 // C++ DR 259, C++0x [temp.explicit]p4: 5263 // For a given set of template parameters, if an explicit 5264 // instantiation of a template appears after a declaration of 5265 // an explicit specialization for that template, the explicit 5266 // instantiation has no effect. 5267 // 5268 // In C++98/03 mode, we only give an extension warning here, because it 5269 // is not harmful to try to explicitly instantiate something that 5270 // has been explicitly specialized. 5271 if (!getLangOptions().CPlusPlus0x) { 5272 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization) 5273 << PrevDecl; 5274 Diag(PrevDecl->getLocation(), 5275 diag::note_previous_template_specialization); 5276 } 5277 HasNoEffect = true; 5278 return false; 5279 5280 case TSK_ExplicitInstantiationDeclaration: 5281 // We're explicity instantiating a definition for something for which we 5282 // were previously asked to suppress instantiations. That's fine. 5283 return false; 5284 5285 case TSK_ExplicitInstantiationDefinition: 5286 // C++0x [temp.spec]p5: 5287 // For a given template and a given set of template-arguments, 5288 // - an explicit instantiation definition shall appear at most once 5289 // in a program, 5290 Diag(NewLoc, diag::err_explicit_instantiation_duplicate) 5291 << PrevDecl; 5292 Diag(PrevPointOfInstantiation, 5293 diag::note_previous_explicit_instantiation); 5294 HasNoEffect = true; 5295 return false; 5296 } 5297 break; 5298 } 5299 5300 assert(false && "Missing specialization/instantiation case?"); 5301 5302 return false; 5303} 5304 5305/// \brief Perform semantic analysis for the given dependent function 5306/// template specialization. The only possible way to get a dependent 5307/// function template specialization is with a friend declaration, 5308/// like so: 5309/// 5310/// template <class T> void foo(T); 5311/// template <class T> class A { 5312/// friend void foo<>(T); 5313/// }; 5314/// 5315/// There really isn't any useful analysis we can do here, so we 5316/// just store the information. 5317bool 5318Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, 5319 const TemplateArgumentListInfo &ExplicitTemplateArgs, 5320 LookupResult &Previous) { 5321 // Remove anything from Previous that isn't a function template in 5322 // the correct context. 5323 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext(); 5324 LookupResult::Filter F = Previous.makeFilter(); 5325 while (F.hasNext()) { 5326 NamedDecl *D = F.next()->getUnderlyingDecl(); 5327 if (!isa<FunctionTemplateDecl>(D) || 5328 !FDLookupContext->InEnclosingNamespaceSetOf( 5329 D->getDeclContext()->getRedeclContext())) 5330 F.erase(); 5331 } 5332 F.done(); 5333 5334 // Should this be diagnosed here? 5335 if (Previous.empty()) return true; 5336 5337 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(), 5338 ExplicitTemplateArgs); 5339 return false; 5340} 5341 5342/// \brief Perform semantic analysis for the given function template 5343/// specialization. 5344/// 5345/// This routine performs all of the semantic analysis required for an 5346/// explicit function template specialization. On successful completion, 5347/// the function declaration \p FD will become a function template 5348/// specialization. 5349/// 5350/// \param FD the function declaration, which will be updated to become a 5351/// function template specialization. 5352/// 5353/// \param ExplicitTemplateArgs the explicitly-provided template arguments, 5354/// if any. Note that this may be valid info even when 0 arguments are 5355/// explicitly provided as in, e.g., \c void sort<>(char*, char*); 5356/// as it anyway contains info on the angle brackets locations. 5357/// 5358/// \param PrevDecl the set of declarations that may be specialized by 5359/// this function specialization. 5360bool 5361Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD, 5362 TemplateArgumentListInfo *ExplicitTemplateArgs, 5363 LookupResult &Previous) { 5364 // The set of function template specializations that could match this 5365 // explicit function template specialization. 5366 UnresolvedSet<8> Candidates; 5367 5368 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext(); 5369 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 5370 I != E; ++I) { 5371 NamedDecl *Ovl = (*I)->getUnderlyingDecl(); 5372 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) { 5373 // Only consider templates found within the same semantic lookup scope as 5374 // FD. 5375 if (!FDLookupContext->InEnclosingNamespaceSetOf( 5376 Ovl->getDeclContext()->getRedeclContext())) 5377 continue; 5378 5379 // C++ [temp.expl.spec]p11: 5380 // A trailing template-argument can be left unspecified in the 5381 // template-id naming an explicit function template specialization 5382 // provided it can be deduced from the function argument type. 5383 // Perform template argument deduction to determine whether we may be 5384 // specializing this template. 5385 // FIXME: It is somewhat wasteful to build 5386 TemplateDeductionInfo Info(Context, FD->getLocation()); 5387 FunctionDecl *Specialization = 0; 5388 if (TemplateDeductionResult TDK 5389 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs, 5390 FD->getType(), 5391 Specialization, 5392 Info)) { 5393 // FIXME: Template argument deduction failed; record why it failed, so 5394 // that we can provide nifty diagnostics. 5395 (void)TDK; 5396 continue; 5397 } 5398 5399 // Record this candidate. 5400 Candidates.addDecl(Specialization, I.getAccess()); 5401 } 5402 } 5403 5404 // Find the most specialized function template. 5405 UnresolvedSetIterator Result 5406 = getMostSpecialized(Candidates.begin(), Candidates.end(), 5407 TPOC_Other, 0, FD->getLocation(), 5408 PDiag(diag::err_function_template_spec_no_match) 5409 << FD->getDeclName(), 5410 PDiag(diag::err_function_template_spec_ambiguous) 5411 << FD->getDeclName() << (ExplicitTemplateArgs != 0), 5412 PDiag(diag::note_function_template_spec_matched)); 5413 if (Result == Candidates.end()) 5414 return true; 5415 5416 // Ignore access information; it doesn't figure into redeclaration checking. 5417 FunctionDecl *Specialization = cast<FunctionDecl>(*Result); 5418 5419 FunctionTemplateSpecializationInfo *SpecInfo 5420 = Specialization->getTemplateSpecializationInfo(); 5421 assert(SpecInfo && "Function template specialization info missing?"); 5422 { 5423 // Note: do not overwrite location info if previous template 5424 // specialization kind was explicit. 5425 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind(); 5426 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) 5427 Specialization->setLocation(FD->getLocation()); 5428 } 5429 5430 // FIXME: Check if the prior specialization has a point of instantiation. 5431 // If so, we have run afoul of . 5432 5433 // If this is a friend declaration, then we're not really declaring 5434 // an explicit specialization. 5435 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None); 5436 5437 // Check the scope of this explicit specialization. 5438 if (!isFriend && 5439 CheckTemplateSpecializationScope(*this, 5440 Specialization->getPrimaryTemplate(), 5441 Specialization, FD->getLocation(), 5442 false)) 5443 return true; 5444 5445 // C++ [temp.expl.spec]p6: 5446 // If a template, a member template or the member of a class template is 5447 // explicitly specialized then that specialization shall be declared 5448 // before the first use of that specialization that would cause an implicit 5449 // instantiation to take place, in every translation unit in which such a 5450 // use occurs; no diagnostic is required. 5451 bool HasNoEffect = false; 5452 if (!isFriend && 5453 CheckSpecializationInstantiationRedecl(FD->getLocation(), 5454 TSK_ExplicitSpecialization, 5455 Specialization, 5456 SpecInfo->getTemplateSpecializationKind(), 5457 SpecInfo->getPointOfInstantiation(), 5458 HasNoEffect)) 5459 return true; 5460 5461 // Mark the prior declaration as an explicit specialization, so that later 5462 // clients know that this is an explicit specialization. 5463 if (!isFriend) { 5464 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization); 5465 MarkUnusedFileScopedDecl(Specialization); 5466 } 5467 5468 // Turn the given function declaration into a function template 5469 // specialization, with the template arguments from the previous 5470 // specialization. 5471 // Take copies of (semantic and syntactic) template argument lists. 5472 const TemplateArgumentList* TemplArgs = new (Context) 5473 TemplateArgumentList(Specialization->getTemplateSpecializationArgs()); 5474 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs 5475 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0; 5476 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(), 5477 TemplArgs, /*InsertPos=*/0, 5478 SpecInfo->getTemplateSpecializationKind(), 5479 TemplArgsAsWritten); 5480 FD->setStorageClass(Specialization->getStorageClass()); 5481 5482 // The "previous declaration" for this function template specialization is 5483 // the prior function template specialization. 5484 Previous.clear(); 5485 Previous.addDecl(Specialization); 5486 return false; 5487} 5488 5489/// \brief Perform semantic analysis for the given non-template member 5490/// specialization. 5491/// 5492/// This routine performs all of the semantic analysis required for an 5493/// explicit member function specialization. On successful completion, 5494/// the function declaration \p FD will become a member function 5495/// specialization. 5496/// 5497/// \param Member the member declaration, which will be updated to become a 5498/// specialization. 5499/// 5500/// \param Previous the set of declarations, one of which may be specialized 5501/// by this function specialization; the set will be modified to contain the 5502/// redeclared member. 5503bool 5504Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) { 5505 assert(!isa<TemplateDecl>(Member) && "Only for non-template members"); 5506 5507 // Try to find the member we are instantiating. 5508 NamedDecl *Instantiation = 0; 5509 NamedDecl *InstantiatedFrom = 0; 5510 MemberSpecializationInfo *MSInfo = 0; 5511 5512 if (Previous.empty()) { 5513 // Nowhere to look anyway. 5514 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) { 5515 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 5516 I != E; ++I) { 5517 NamedDecl *D = (*I)->getUnderlyingDecl(); 5518 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 5519 if (Context.hasSameType(Function->getType(), Method->getType())) { 5520 Instantiation = Method; 5521 InstantiatedFrom = Method->getInstantiatedFromMemberFunction(); 5522 MSInfo = Method->getMemberSpecializationInfo(); 5523 break; 5524 } 5525 } 5526 } 5527 } else if (isa<VarDecl>(Member)) { 5528 VarDecl *PrevVar; 5529 if (Previous.isSingleResult() && 5530 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl()))) 5531 if (PrevVar->isStaticDataMember()) { 5532 Instantiation = PrevVar; 5533 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember(); 5534 MSInfo = PrevVar->getMemberSpecializationInfo(); 5535 } 5536 } else if (isa<RecordDecl>(Member)) { 5537 CXXRecordDecl *PrevRecord; 5538 if (Previous.isSingleResult() && 5539 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) { 5540 Instantiation = PrevRecord; 5541 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass(); 5542 MSInfo = PrevRecord->getMemberSpecializationInfo(); 5543 } 5544 } 5545 5546 if (!Instantiation) { 5547 // There is no previous declaration that matches. Since member 5548 // specializations are always out-of-line, the caller will complain about 5549 // this mismatch later. 5550 return false; 5551 } 5552 5553 // If this is a friend, just bail out here before we start turning 5554 // things into explicit specializations. 5555 if (Member->getFriendObjectKind() != Decl::FOK_None) { 5556 // Preserve instantiation information. 5557 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) { 5558 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction( 5559 cast<CXXMethodDecl>(InstantiatedFrom), 5560 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind()); 5561 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) { 5562 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass( 5563 cast<CXXRecordDecl>(InstantiatedFrom), 5564 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind()); 5565 } 5566 5567 Previous.clear(); 5568 Previous.addDecl(Instantiation); 5569 return false; 5570 } 5571 5572 // Make sure that this is a specialization of a member. 5573 if (!InstantiatedFrom) { 5574 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated) 5575 << Member; 5576 Diag(Instantiation->getLocation(), diag::note_specialized_decl); 5577 return true; 5578 } 5579 5580 // C++ [temp.expl.spec]p6: 5581 // If a template, a member template or the member of a class template is 5582 // explicitly specialized then that spe- cialization shall be declared 5583 // before the first use of that specialization that would cause an implicit 5584 // instantiation to take place, in every translation unit in which such a 5585 // use occurs; no diagnostic is required. 5586 assert(MSInfo && "Member specialization info missing?"); 5587 5588 bool HasNoEffect = false; 5589 if (CheckSpecializationInstantiationRedecl(Member->getLocation(), 5590 TSK_ExplicitSpecialization, 5591 Instantiation, 5592 MSInfo->getTemplateSpecializationKind(), 5593 MSInfo->getPointOfInstantiation(), 5594 HasNoEffect)) 5595 return true; 5596 5597 // Check the scope of this explicit specialization. 5598 if (CheckTemplateSpecializationScope(*this, 5599 InstantiatedFrom, 5600 Instantiation, Member->getLocation(), 5601 false)) 5602 return true; 5603 5604 // Note that this is an explicit instantiation of a member. 5605 // the original declaration to note that it is an explicit specialization 5606 // (if it was previously an implicit instantiation). This latter step 5607 // makes bookkeeping easier. 5608 if (isa<FunctionDecl>(Member)) { 5609 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation); 5610 if (InstantiationFunction->getTemplateSpecializationKind() == 5611 TSK_ImplicitInstantiation) { 5612 InstantiationFunction->setTemplateSpecializationKind( 5613 TSK_ExplicitSpecialization); 5614 InstantiationFunction->setLocation(Member->getLocation()); 5615 } 5616 5617 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction( 5618 cast<CXXMethodDecl>(InstantiatedFrom), 5619 TSK_ExplicitSpecialization); 5620 MarkUnusedFileScopedDecl(InstantiationFunction); 5621 } else if (isa<VarDecl>(Member)) { 5622 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation); 5623 if (InstantiationVar->getTemplateSpecializationKind() == 5624 TSK_ImplicitInstantiation) { 5625 InstantiationVar->setTemplateSpecializationKind( 5626 TSK_ExplicitSpecialization); 5627 InstantiationVar->setLocation(Member->getLocation()); 5628 } 5629 5630 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member), 5631 cast<VarDecl>(InstantiatedFrom), 5632 TSK_ExplicitSpecialization); 5633 MarkUnusedFileScopedDecl(InstantiationVar); 5634 } else { 5635 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain"); 5636 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation); 5637 if (InstantiationClass->getTemplateSpecializationKind() == 5638 TSK_ImplicitInstantiation) { 5639 InstantiationClass->setTemplateSpecializationKind( 5640 TSK_ExplicitSpecialization); 5641 InstantiationClass->setLocation(Member->getLocation()); 5642 } 5643 5644 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass( 5645 cast<CXXRecordDecl>(InstantiatedFrom), 5646 TSK_ExplicitSpecialization); 5647 } 5648 5649 // Save the caller the trouble of having to figure out which declaration 5650 // this specialization matches. 5651 Previous.clear(); 5652 Previous.addDecl(Instantiation); 5653 return false; 5654} 5655 5656/// \brief Check the scope of an explicit instantiation. 5657/// 5658/// \returns true if a serious error occurs, false otherwise. 5659static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D, 5660 SourceLocation InstLoc, 5661 bool WasQualifiedName) { 5662 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext(); 5663 DeclContext *CurContext = S.CurContext->getRedeclContext(); 5664 5665 if (CurContext->isRecord()) { 5666 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class) 5667 << D; 5668 return true; 5669 } 5670 5671 // C++0x [temp.explicit]p2: 5672 // An explicit instantiation shall appear in an enclosing namespace of its 5673 // template. 5674 // 5675 // This is DR275, which we do not retroactively apply to C++98/03. 5676 if (S.getLangOptions().CPlusPlus0x && 5677 !CurContext->Encloses(OrigContext)) { 5678 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) 5679 S.Diag(InstLoc, 5680 S.getLangOptions().CPlusPlus0x? 5681 diag::err_explicit_instantiation_out_of_scope 5682 : diag::warn_explicit_instantiation_out_of_scope_0x) 5683 << D << NS; 5684 else 5685 S.Diag(InstLoc, 5686 S.getLangOptions().CPlusPlus0x? 5687 diag::err_explicit_instantiation_must_be_global 5688 : diag::warn_explicit_instantiation_out_of_scope_0x) 5689 << D; 5690 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here); 5691 return false; 5692 } 5693 5694 // C++0x [temp.explicit]p2: 5695 // If the name declared in the explicit instantiation is an unqualified 5696 // name, the explicit instantiation shall appear in the namespace where 5697 // its template is declared or, if that namespace is inline (7.3.1), any 5698 // namespace from its enclosing namespace set. 5699 if (WasQualifiedName) 5700 return false; 5701 5702 if (CurContext->InEnclosingNamespaceSetOf(OrigContext)) 5703 return false; 5704 5705 S.Diag(InstLoc, 5706 S.getLangOptions().CPlusPlus0x? 5707 diag::err_explicit_instantiation_unqualified_wrong_namespace 5708 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x) 5709 << D << OrigContext; 5710 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here); 5711 return false; 5712} 5713 5714/// \brief Determine whether the given scope specifier has a template-id in it. 5715static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) { 5716 if (!SS.isSet()) 5717 return false; 5718 5719 // C++0x [temp.explicit]p2: 5720 // If the explicit instantiation is for a member function, a member class 5721 // or a static data member of a class template specialization, the name of 5722 // the class template specialization in the qualified-id for the member 5723 // name shall be a simple-template-id. 5724 // 5725 // C++98 has the same restriction, just worded differently. 5726 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep(); 5727 NNS; NNS = NNS->getPrefix()) 5728 if (const Type *T = NNS->getAsType()) 5729 if (isa<TemplateSpecializationType>(T)) 5730 return true; 5731 5732 return false; 5733} 5734 5735// Explicit instantiation of a class template specialization 5736DeclResult 5737Sema::ActOnExplicitInstantiation(Scope *S, 5738 SourceLocation ExternLoc, 5739 SourceLocation TemplateLoc, 5740 unsigned TagSpec, 5741 SourceLocation KWLoc, 5742 const CXXScopeSpec &SS, 5743 TemplateTy TemplateD, 5744 SourceLocation TemplateNameLoc, 5745 SourceLocation LAngleLoc, 5746 ASTTemplateArgsPtr TemplateArgsIn, 5747 SourceLocation RAngleLoc, 5748 AttributeList *Attr) { 5749 // Find the class template we're specializing 5750 TemplateName Name = TemplateD.getAsVal<TemplateName>(); 5751 ClassTemplateDecl *ClassTemplate 5752 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl()); 5753 5754 // Check that the specialization uses the same tag kind as the 5755 // original template. 5756 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 5757 assert(Kind != TTK_Enum && 5758 "Invalid enum tag in class template explicit instantiation!"); 5759 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), 5760 Kind, /*isDefinition*/false, KWLoc, 5761 *ClassTemplate->getIdentifier())) { 5762 Diag(KWLoc, diag::err_use_with_wrong_tag) 5763 << ClassTemplate 5764 << FixItHint::CreateReplacement(KWLoc, 5765 ClassTemplate->getTemplatedDecl()->getKindName()); 5766 Diag(ClassTemplate->getTemplatedDecl()->getLocation(), 5767 diag::note_previous_use); 5768 Kind = ClassTemplate->getTemplatedDecl()->getTagKind(); 5769 } 5770 5771 // C++0x [temp.explicit]p2: 5772 // There are two forms of explicit instantiation: an explicit instantiation 5773 // definition and an explicit instantiation declaration. An explicit 5774 // instantiation declaration begins with the extern keyword. [...] 5775 TemplateSpecializationKind TSK 5776 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition 5777 : TSK_ExplicitInstantiationDeclaration; 5778 5779 // Translate the parser's template argument list in our AST format. 5780 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); 5781 translateTemplateArguments(TemplateArgsIn, TemplateArgs); 5782 5783 // Check that the template argument list is well-formed for this 5784 // template. 5785 llvm::SmallVector<TemplateArgument, 4> Converted; 5786 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, 5787 TemplateArgs, false, Converted)) 5788 return true; 5789 5790 assert((Converted.size() == ClassTemplate->getTemplateParameters()->size()) && 5791 "Converted template argument list is too short!"); 5792 5793 // Find the class template specialization declaration that 5794 // corresponds to these arguments. 5795 void *InsertPos = 0; 5796 ClassTemplateSpecializationDecl *PrevDecl 5797 = ClassTemplate->findSpecialization(Converted.data(), 5798 Converted.size(), InsertPos); 5799 5800 TemplateSpecializationKind PrevDecl_TSK 5801 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared; 5802 5803 // C++0x [temp.explicit]p2: 5804 // [...] An explicit instantiation shall appear in an enclosing 5805 // namespace of its template. [...] 5806 // 5807 // This is C++ DR 275. 5808 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc, 5809 SS.isSet())) 5810 return true; 5811 5812 ClassTemplateSpecializationDecl *Specialization = 0; 5813 5814 bool HasNoEffect = false; 5815 if (PrevDecl) { 5816 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK, 5817 PrevDecl, PrevDecl_TSK, 5818 PrevDecl->getPointOfInstantiation(), 5819 HasNoEffect)) 5820 return PrevDecl; 5821 5822 // Even though HasNoEffect == true means that this explicit instantiation 5823 // has no effect on semantics, we go on to put its syntax in the AST. 5824 5825 if (PrevDecl_TSK == TSK_ImplicitInstantiation || 5826 PrevDecl_TSK == TSK_Undeclared) { 5827 // Since the only prior class template specialization with these 5828 // arguments was referenced but not declared, reuse that 5829 // declaration node as our own, updating the source location 5830 // for the template name to reflect our new declaration. 5831 // (Other source locations will be updated later.) 5832 Specialization = PrevDecl; 5833 Specialization->setLocation(TemplateNameLoc); 5834 PrevDecl = 0; 5835 } 5836 } 5837 5838 if (!Specialization) { 5839 // Create a new class template specialization declaration node for 5840 // this explicit specialization. 5841 Specialization 5842 = ClassTemplateSpecializationDecl::Create(Context, Kind, 5843 ClassTemplate->getDeclContext(), 5844 KWLoc, TemplateNameLoc, 5845 ClassTemplate, 5846 Converted.data(), 5847 Converted.size(), 5848 PrevDecl); 5849 SetNestedNameSpecifier(Specialization, SS); 5850 5851 if (!HasNoEffect && !PrevDecl) { 5852 // Insert the new specialization. 5853 ClassTemplate->AddSpecialization(Specialization, InsertPos); 5854 } 5855 } 5856 5857 // Build the fully-sugared type for this explicit instantiation as 5858 // the user wrote in the explicit instantiation itself. This means 5859 // that we'll pretty-print the type retrieved from the 5860 // specialization's declaration the way that the user actually wrote 5861 // the explicit instantiation, rather than formatting the name based 5862 // on the "canonical" representation used to store the template 5863 // arguments in the specialization. 5864 TypeSourceInfo *WrittenTy 5865 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc, 5866 TemplateArgs, 5867 Context.getTypeDeclType(Specialization)); 5868 Specialization->setTypeAsWritten(WrittenTy); 5869 TemplateArgsIn.release(); 5870 5871 // Set source locations for keywords. 5872 Specialization->setExternLoc(ExternLoc); 5873 Specialization->setTemplateKeywordLoc(TemplateLoc); 5874 5875 // Add the explicit instantiation into its lexical context. However, 5876 // since explicit instantiations are never found by name lookup, we 5877 // just put it into the declaration context directly. 5878 Specialization->setLexicalDeclContext(CurContext); 5879 CurContext->addDecl(Specialization); 5880 5881 // Syntax is now OK, so return if it has no other effect on semantics. 5882 if (HasNoEffect) { 5883 // Set the template specialization kind. 5884 Specialization->setTemplateSpecializationKind(TSK); 5885 return Specialization; 5886 } 5887 5888 // C++ [temp.explicit]p3: 5889 // A definition of a class template or class member template 5890 // shall be in scope at the point of the explicit instantiation of 5891 // the class template or class member template. 5892 // 5893 // This check comes when we actually try to perform the 5894 // instantiation. 5895 ClassTemplateSpecializationDecl *Def 5896 = cast_or_null<ClassTemplateSpecializationDecl>( 5897 Specialization->getDefinition()); 5898 if (!Def) 5899 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK); 5900 else if (TSK == TSK_ExplicitInstantiationDefinition) { 5901 MarkVTableUsed(TemplateNameLoc, Specialization, true); 5902 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation()); 5903 } 5904 5905 // Instantiate the members of this class template specialization. 5906 Def = cast_or_null<ClassTemplateSpecializationDecl>( 5907 Specialization->getDefinition()); 5908 if (Def) { 5909 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind(); 5910 5911 // Fix a TSK_ExplicitInstantiationDeclaration followed by a 5912 // TSK_ExplicitInstantiationDefinition 5913 if (Old_TSK == TSK_ExplicitInstantiationDeclaration && 5914 TSK == TSK_ExplicitInstantiationDefinition) 5915 Def->setTemplateSpecializationKind(TSK); 5916 5917 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK); 5918 } 5919 5920 // Set the template specialization kind. 5921 Specialization->setTemplateSpecializationKind(TSK); 5922 return Specialization; 5923} 5924 5925// Explicit instantiation of a member class of a class template. 5926DeclResult 5927Sema::ActOnExplicitInstantiation(Scope *S, 5928 SourceLocation ExternLoc, 5929 SourceLocation TemplateLoc, 5930 unsigned TagSpec, 5931 SourceLocation KWLoc, 5932 CXXScopeSpec &SS, 5933 IdentifierInfo *Name, 5934 SourceLocation NameLoc, 5935 AttributeList *Attr) { 5936 5937 bool Owned = false; 5938 bool IsDependent = false; 5939 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference, 5940 KWLoc, SS, Name, NameLoc, Attr, AS_none, 5941 MultiTemplateParamsArg(*this, 0, 0), 5942 Owned, IsDependent, false, false, 5943 TypeResult()); 5944 assert(!IsDependent && "explicit instantiation of dependent name not yet handled"); 5945 5946 if (!TagD) 5947 return true; 5948 5949 TagDecl *Tag = cast<TagDecl>(TagD); 5950 if (Tag->isEnum()) { 5951 Diag(TemplateLoc, diag::err_explicit_instantiation_enum) 5952 << Context.getTypeDeclType(Tag); 5953 return true; 5954 } 5955 5956 if (Tag->isInvalidDecl()) 5957 return true; 5958 5959 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag); 5960 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass(); 5961 if (!Pattern) { 5962 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type) 5963 << Context.getTypeDeclType(Record); 5964 Diag(Record->getLocation(), diag::note_nontemplate_decl_here); 5965 return true; 5966 } 5967 5968 // C++0x [temp.explicit]p2: 5969 // If the explicit instantiation is for a class or member class, the 5970 // elaborated-type-specifier in the declaration shall include a 5971 // simple-template-id. 5972 // 5973 // C++98 has the same restriction, just worded differently. 5974 if (!ScopeSpecifierHasTemplateId(SS)) 5975 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id) 5976 << Record << SS.getRange(); 5977 5978 // C++0x [temp.explicit]p2: 5979 // There are two forms of explicit instantiation: an explicit instantiation 5980 // definition and an explicit instantiation declaration. An explicit 5981 // instantiation declaration begins with the extern keyword. [...] 5982 TemplateSpecializationKind TSK 5983 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition 5984 : TSK_ExplicitInstantiationDeclaration; 5985 5986 // C++0x [temp.explicit]p2: 5987 // [...] An explicit instantiation shall appear in an enclosing 5988 // namespace of its template. [...] 5989 // 5990 // This is C++ DR 275. 5991 CheckExplicitInstantiationScope(*this, Record, NameLoc, true); 5992 5993 // Verify that it is okay to explicitly instantiate here. 5994 CXXRecordDecl *PrevDecl 5995 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration()); 5996 if (!PrevDecl && Record->getDefinition()) 5997 PrevDecl = Record; 5998 if (PrevDecl) { 5999 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo(); 6000 bool HasNoEffect = false; 6001 assert(MSInfo && "No member specialization information?"); 6002 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK, 6003 PrevDecl, 6004 MSInfo->getTemplateSpecializationKind(), 6005 MSInfo->getPointOfInstantiation(), 6006 HasNoEffect)) 6007 return true; 6008 if (HasNoEffect) 6009 return TagD; 6010 } 6011 6012 CXXRecordDecl *RecordDef 6013 = cast_or_null<CXXRecordDecl>(Record->getDefinition()); 6014 if (!RecordDef) { 6015 // C++ [temp.explicit]p3: 6016 // A definition of a member class of a class template shall be in scope 6017 // at the point of an explicit instantiation of the member class. 6018 CXXRecordDecl *Def 6019 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition()); 6020 if (!Def) { 6021 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member) 6022 << 0 << Record->getDeclName() << Record->getDeclContext(); 6023 Diag(Pattern->getLocation(), diag::note_forward_declaration) 6024 << Pattern; 6025 return true; 6026 } else { 6027 if (InstantiateClass(NameLoc, Record, Def, 6028 getTemplateInstantiationArgs(Record), 6029 TSK)) 6030 return true; 6031 6032 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition()); 6033 if (!RecordDef) 6034 return true; 6035 } 6036 } 6037 6038 // Instantiate all of the members of the class. 6039 InstantiateClassMembers(NameLoc, RecordDef, 6040 getTemplateInstantiationArgs(Record), TSK); 6041 6042 if (TSK == TSK_ExplicitInstantiationDefinition) 6043 MarkVTableUsed(NameLoc, RecordDef, true); 6044 6045 // FIXME: We don't have any representation for explicit instantiations of 6046 // member classes. Such a representation is not needed for compilation, but it 6047 // should be available for clients that want to see all of the declarations in 6048 // the source code. 6049 return TagD; 6050} 6051 6052DeclResult Sema::ActOnExplicitInstantiation(Scope *S, 6053 SourceLocation ExternLoc, 6054 SourceLocation TemplateLoc, 6055 Declarator &D) { 6056 // Explicit instantiations always require a name. 6057 // TODO: check if/when DNInfo should replace Name. 6058 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 6059 DeclarationName Name = NameInfo.getName(); 6060 if (!Name) { 6061 if (!D.isInvalidType()) 6062 Diag(D.getDeclSpec().getSourceRange().getBegin(), 6063 diag::err_explicit_instantiation_requires_name) 6064 << D.getDeclSpec().getSourceRange() 6065 << D.getSourceRange(); 6066 6067 return true; 6068 } 6069 6070 // The scope passed in may not be a decl scope. Zip up the scope tree until 6071 // we find one that is. 6072 while ((S->getFlags() & Scope::DeclScope) == 0 || 6073 (S->getFlags() & Scope::TemplateParamScope) != 0) 6074 S = S->getParent(); 6075 6076 // Determine the type of the declaration. 6077 TypeSourceInfo *T = GetTypeForDeclarator(D, S); 6078 QualType R = T->getType(); 6079 if (R.isNull()) 6080 return true; 6081 6082 // C++ [dcl.stc]p1: 6083 // A storage-class-specifier shall not be specified in [...] an explicit 6084 // instantiation (14.7.2) directive. 6085 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 6086 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef) 6087 << Name; 6088 return true; 6089 } else if (D.getDeclSpec().getStorageClassSpec() 6090 != DeclSpec::SCS_unspecified) { 6091 // Complain about then remove the storage class specifier. 6092 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class) 6093 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6094 6095 D.getMutableDeclSpec().ClearStorageClassSpecs(); 6096 } 6097 6098 // C++0x [temp.explicit]p1: 6099 // [...] An explicit instantiation of a function template shall not use the 6100 // inline or constexpr specifiers. 6101 // Presumably, this also applies to member functions of class templates as 6102 // well. 6103 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x) 6104 Diag(D.getDeclSpec().getInlineSpecLoc(), 6105 diag::err_explicit_instantiation_inline) 6106 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6107 6108 // FIXME: check for constexpr specifier. 6109 6110 // C++0x [temp.explicit]p2: 6111 // There are two forms of explicit instantiation: an explicit instantiation 6112 // definition and an explicit instantiation declaration. An explicit 6113 // instantiation declaration begins with the extern keyword. [...] 6114 TemplateSpecializationKind TSK 6115 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition 6116 : TSK_ExplicitInstantiationDeclaration; 6117 6118 LookupResult Previous(*this, NameInfo, LookupOrdinaryName); 6119 LookupParsedName(Previous, S, &D.getCXXScopeSpec()); 6120 6121 if (!R->isFunctionType()) { 6122 // C++ [temp.explicit]p1: 6123 // A [...] static data member of a class template can be explicitly 6124 // instantiated from the member definition associated with its class 6125 // template. 6126 if (Previous.isAmbiguous()) 6127 return true; 6128 6129 VarDecl *Prev = Previous.getAsSingle<VarDecl>(); 6130 if (!Prev || !Prev->isStaticDataMember()) { 6131 // We expect to see a data data member here. 6132 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known) 6133 << Name; 6134 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end(); 6135 P != PEnd; ++P) 6136 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here); 6137 return true; 6138 } 6139 6140 if (!Prev->getInstantiatedFromStaticDataMember()) { 6141 // FIXME: Check for explicit specialization? 6142 Diag(D.getIdentifierLoc(), 6143 diag::err_explicit_instantiation_data_member_not_instantiated) 6144 << Prev; 6145 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here); 6146 // FIXME: Can we provide a note showing where this was declared? 6147 return true; 6148 } 6149 6150 // C++0x [temp.explicit]p2: 6151 // If the explicit instantiation is for a member function, a member class 6152 // or a static data member of a class template specialization, the name of 6153 // the class template specialization in the qualified-id for the member 6154 // name shall be a simple-template-id. 6155 // 6156 // C++98 has the same restriction, just worded differently. 6157 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec())) 6158 Diag(D.getIdentifierLoc(), 6159 diag::ext_explicit_instantiation_without_qualified_id) 6160 << Prev << D.getCXXScopeSpec().getRange(); 6161 6162 // Check the scope of this explicit instantiation. 6163 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true); 6164 6165 // Verify that it is okay to explicitly instantiate here. 6166 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo(); 6167 assert(MSInfo && "Missing static data member specialization info?"); 6168 bool HasNoEffect = false; 6169 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev, 6170 MSInfo->getTemplateSpecializationKind(), 6171 MSInfo->getPointOfInstantiation(), 6172 HasNoEffect)) 6173 return true; 6174 if (HasNoEffect) 6175 return (Decl*) 0; 6176 6177 // Instantiate static data member. 6178 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc()); 6179 if (TSK == TSK_ExplicitInstantiationDefinition) 6180 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev); 6181 6182 // FIXME: Create an ExplicitInstantiation node? 6183 return (Decl*) 0; 6184 } 6185 6186 // If the declarator is a template-id, translate the parser's template 6187 // argument list into our AST format. 6188 bool HasExplicitTemplateArgs = false; 6189 TemplateArgumentListInfo TemplateArgs; 6190 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 6191 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 6192 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 6193 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 6194 ASTTemplateArgsPtr TemplateArgsPtr(*this, 6195 TemplateId->getTemplateArgs(), 6196 TemplateId->NumArgs); 6197 translateTemplateArguments(TemplateArgsPtr, TemplateArgs); 6198 HasExplicitTemplateArgs = true; 6199 TemplateArgsPtr.release(); 6200 } 6201 6202 // C++ [temp.explicit]p1: 6203 // A [...] function [...] can be explicitly instantiated from its template. 6204 // A member function [...] of a class template can be explicitly 6205 // instantiated from the member definition associated with its class 6206 // template. 6207 UnresolvedSet<8> Matches; 6208 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end(); 6209 P != PEnd; ++P) { 6210 NamedDecl *Prev = *P; 6211 if (!HasExplicitTemplateArgs) { 6212 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) { 6213 if (Context.hasSameUnqualifiedType(Method->getType(), R)) { 6214 Matches.clear(); 6215 6216 Matches.addDecl(Method, P.getAccess()); 6217 if (Method->getTemplateSpecializationKind() == TSK_Undeclared) 6218 break; 6219 } 6220 } 6221 } 6222 6223 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev); 6224 if (!FunTmpl) 6225 continue; 6226 6227 TemplateDeductionInfo Info(Context, D.getIdentifierLoc()); 6228 FunctionDecl *Specialization = 0; 6229 if (TemplateDeductionResult TDK 6230 = DeduceTemplateArguments(FunTmpl, 6231 (HasExplicitTemplateArgs ? &TemplateArgs : 0), 6232 R, Specialization, Info)) { 6233 // FIXME: Keep track of almost-matches? 6234 (void)TDK; 6235 continue; 6236 } 6237 6238 Matches.addDecl(Specialization, P.getAccess()); 6239 } 6240 6241 // Find the most specialized function template specialization. 6242 UnresolvedSetIterator Result 6243 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other, 0, 6244 D.getIdentifierLoc(), 6245 PDiag(diag::err_explicit_instantiation_not_known) << Name, 6246 PDiag(diag::err_explicit_instantiation_ambiguous) << Name, 6247 PDiag(diag::note_explicit_instantiation_candidate)); 6248 6249 if (Result == Matches.end()) 6250 return true; 6251 6252 // Ignore access control bits, we don't need them for redeclaration checking. 6253 FunctionDecl *Specialization = cast<FunctionDecl>(*Result); 6254 6255 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) { 6256 Diag(D.getIdentifierLoc(), 6257 diag::err_explicit_instantiation_member_function_not_instantiated) 6258 << Specialization 6259 << (Specialization->getTemplateSpecializationKind() == 6260 TSK_ExplicitSpecialization); 6261 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here); 6262 return true; 6263 } 6264 6265 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration(); 6266 if (!PrevDecl && Specialization->isThisDeclarationADefinition()) 6267 PrevDecl = Specialization; 6268 6269 if (PrevDecl) { 6270 bool HasNoEffect = false; 6271 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, 6272 PrevDecl, 6273 PrevDecl->getTemplateSpecializationKind(), 6274 PrevDecl->getPointOfInstantiation(), 6275 HasNoEffect)) 6276 return true; 6277 6278 // FIXME: We may still want to build some representation of this 6279 // explicit specialization. 6280 if (HasNoEffect) 6281 return (Decl*) 0; 6282 } 6283 6284 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc()); 6285 6286 if (TSK == TSK_ExplicitInstantiationDefinition) 6287 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization); 6288 6289 // C++0x [temp.explicit]p2: 6290 // If the explicit instantiation is for a member function, a member class 6291 // or a static data member of a class template specialization, the name of 6292 // the class template specialization in the qualified-id for the member 6293 // name shall be a simple-template-id. 6294 // 6295 // C++98 has the same restriction, just worded differently. 6296 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate(); 6297 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl && 6298 D.getCXXScopeSpec().isSet() && 6299 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec())) 6300 Diag(D.getIdentifierLoc(), 6301 diag::ext_explicit_instantiation_without_qualified_id) 6302 << Specialization << D.getCXXScopeSpec().getRange(); 6303 6304 CheckExplicitInstantiationScope(*this, 6305 FunTmpl? (NamedDecl *)FunTmpl 6306 : Specialization->getInstantiatedFromMemberFunction(), 6307 D.getIdentifierLoc(), 6308 D.getCXXScopeSpec().isSet()); 6309 6310 // FIXME: Create some kind of ExplicitInstantiationDecl here. 6311 return (Decl*) 0; 6312} 6313 6314TypeResult 6315Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 6316 const CXXScopeSpec &SS, IdentifierInfo *Name, 6317 SourceLocation TagLoc, SourceLocation NameLoc) { 6318 // This has to hold, because SS is expected to be defined. 6319 assert(Name && "Expected a name in a dependent tag"); 6320 6321 NestedNameSpecifier *NNS 6322 = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 6323 if (!NNS) 6324 return true; 6325 6326 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 6327 6328 if (TUK == TUK_Declaration || TUK == TUK_Definition) { 6329 Diag(NameLoc, diag::err_dependent_tag_decl) 6330 << (TUK == TUK_Definition) << Kind << SS.getRange(); 6331 return true; 6332 } 6333 6334 // Create the resulting type. 6335 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 6336 QualType Result = Context.getDependentNameType(Kwd, NNS, Name); 6337 6338 // Create type-source location information for this type. 6339 TypeLocBuilder TLB; 6340 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result); 6341 TL.setKeywordLoc(TagLoc); 6342 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 6343 TL.setNameLoc(NameLoc); 6344 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result)); 6345} 6346 6347TypeResult 6348Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, 6349 const CXXScopeSpec &SS, const IdentifierInfo &II, 6350 SourceLocation IdLoc) { 6351 if (SS.isInvalid()) 6352 return true; 6353 6354 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() && 6355 !getLangOptions().CPlusPlus0x) 6356 Diag(TypenameLoc, diag::ext_typename_outside_of_template) 6357 << FixItHint::CreateRemoval(TypenameLoc); 6358 6359 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 6360 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None, 6361 TypenameLoc, QualifierLoc, II, IdLoc); 6362 if (T.isNull()) 6363 return true; 6364 6365 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 6366 if (isa<DependentNameType>(T)) { 6367 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc()); 6368 TL.setKeywordLoc(TypenameLoc); 6369 TL.setQualifierLoc(QualifierLoc); 6370 TL.setNameLoc(IdLoc); 6371 } else { 6372 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc()); 6373 TL.setKeywordLoc(TypenameLoc); 6374 TL.setQualifierLoc(QualifierLoc); 6375 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc); 6376 } 6377 6378 return CreateParsedType(T, TSI); 6379} 6380 6381TypeResult 6382Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, 6383 const CXXScopeSpec &SS, 6384 SourceLocation TemplateLoc, 6385 TemplateTy TemplateIn, 6386 SourceLocation TemplateNameLoc, 6387 SourceLocation LAngleLoc, 6388 ASTTemplateArgsPtr TemplateArgsIn, 6389 SourceLocation RAngleLoc) { 6390 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() && 6391 !getLangOptions().CPlusPlus0x) 6392 Diag(TypenameLoc, diag::ext_typename_outside_of_template) 6393 << FixItHint::CreateRemoval(TypenameLoc); 6394 6395 // Translate the parser's template argument list in our AST format. 6396 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); 6397 translateTemplateArguments(TemplateArgsIn, TemplateArgs); 6398 6399 TemplateName Template = TemplateIn.get(); 6400 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) { 6401 // Construct a dependent template specialization type. 6402 assert(DTN && "dependent template has non-dependent name?"); 6403 assert(DTN->getQualifier() 6404 == static_cast<NestedNameSpecifier*>(SS.getScopeRep())); 6405 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename, 6406 DTN->getQualifier(), 6407 DTN->getIdentifier(), 6408 TemplateArgs); 6409 6410 // Create source-location information for this type. 6411 TypeLocBuilder Builder; 6412 DependentTemplateSpecializationTypeLoc SpecTL 6413 = Builder.push<DependentTemplateSpecializationTypeLoc>(T); 6414 SpecTL.setLAngleLoc(LAngleLoc); 6415 SpecTL.setRAngleLoc(RAngleLoc); 6416 SpecTL.setKeywordLoc(TypenameLoc); 6417 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context)); 6418 SpecTL.setNameLoc(TemplateNameLoc); 6419 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 6420 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo()); 6421 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 6422 } 6423 6424 QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs); 6425 if (T.isNull()) 6426 return true; 6427 6428 // Provide source-location information for the template specialization 6429 // type. 6430 TypeLocBuilder Builder; 6431 TemplateSpecializationTypeLoc SpecTL 6432 = Builder.push<TemplateSpecializationTypeLoc>(T); 6433 6434 // FIXME: No place to set the location of the 'template' keyword! 6435 SpecTL.setLAngleLoc(LAngleLoc); 6436 SpecTL.setRAngleLoc(RAngleLoc); 6437 SpecTL.setTemplateNameLoc(TemplateNameLoc); 6438 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 6439 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo()); 6440 6441 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T); 6442 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T); 6443 TL.setKeywordLoc(TypenameLoc); 6444 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 6445 6446 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T); 6447 return CreateParsedType(T, TSI); 6448} 6449 6450 6451/// \brief Build the type that describes a C++ typename specifier, 6452/// e.g., "typename T::type". 6453QualType 6454Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword, 6455 SourceLocation KeywordLoc, 6456 NestedNameSpecifierLoc QualifierLoc, 6457 const IdentifierInfo &II, 6458 SourceLocation IILoc) { 6459 CXXScopeSpec SS; 6460 SS.Adopt(QualifierLoc); 6461 6462 DeclContext *Ctx = computeDeclContext(SS); 6463 if (!Ctx) { 6464 // If the nested-name-specifier is dependent and couldn't be 6465 // resolved to a type, build a typename type. 6466 assert(QualifierLoc.getNestedNameSpecifier()->isDependent()); 6467 return Context.getDependentNameType(Keyword, 6468 QualifierLoc.getNestedNameSpecifier(), 6469 &II); 6470 } 6471 6472 // If the nested-name-specifier refers to the current instantiation, 6473 // the "typename" keyword itself is superfluous. In C++03, the 6474 // program is actually ill-formed. However, DR 382 (in C++0x CD1) 6475 // allows such extraneous "typename" keywords, and we retroactively 6476 // apply this DR to C++03 code with only a warning. In any case we continue. 6477 6478 if (RequireCompleteDeclContext(SS, Ctx)) 6479 return QualType(); 6480 6481 DeclarationName Name(&II); 6482 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName); 6483 LookupQualifiedName(Result, Ctx); 6484 unsigned DiagID = 0; 6485 Decl *Referenced = 0; 6486 switch (Result.getResultKind()) { 6487 case LookupResult::NotFound: 6488 DiagID = diag::err_typename_nested_not_found; 6489 break; 6490 6491 case LookupResult::FoundUnresolvedValue: { 6492 // We found a using declaration that is a value. Most likely, the using 6493 // declaration itself is meant to have the 'typename' keyword. 6494 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(), 6495 IILoc); 6496 Diag(IILoc, diag::err_typename_refers_to_using_value_decl) 6497 << Name << Ctx << FullRange; 6498 if (UnresolvedUsingValueDecl *Using 6499 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){ 6500 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc(); 6501 Diag(Loc, diag::note_using_value_decl_missing_typename) 6502 << FixItHint::CreateInsertion(Loc, "typename "); 6503 } 6504 } 6505 // Fall through to create a dependent typename type, from which we can recover 6506 // better. 6507 6508 case LookupResult::NotFoundInCurrentInstantiation: 6509 // Okay, it's a member of an unknown instantiation. 6510 return Context.getDependentNameType(Keyword, 6511 QualifierLoc.getNestedNameSpecifier(), 6512 &II); 6513 6514 case LookupResult::Found: 6515 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) { 6516 // We found a type. Build an ElaboratedType, since the 6517 // typename-specifier was just sugar. 6518 return Context.getElaboratedType(ETK_Typename, 6519 QualifierLoc.getNestedNameSpecifier(), 6520 Context.getTypeDeclType(Type)); 6521 } 6522 6523 DiagID = diag::err_typename_nested_not_type; 6524 Referenced = Result.getFoundDecl(); 6525 break; 6526 6527 6528 llvm_unreachable("unresolved using decl in non-dependent context"); 6529 return QualType(); 6530 6531 case LookupResult::FoundOverloaded: 6532 DiagID = diag::err_typename_nested_not_type; 6533 Referenced = *Result.begin(); 6534 break; 6535 6536 case LookupResult::Ambiguous: 6537 return QualType(); 6538 } 6539 6540 // If we get here, it's because name lookup did not find a 6541 // type. Emit an appropriate diagnostic and return an error. 6542 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(), 6543 IILoc); 6544 Diag(IILoc, DiagID) << FullRange << Name << Ctx; 6545 if (Referenced) 6546 Diag(Referenced->getLocation(), diag::note_typename_refers_here) 6547 << Name; 6548 return QualType(); 6549} 6550 6551namespace { 6552 // See Sema::RebuildTypeInCurrentInstantiation 6553 class CurrentInstantiationRebuilder 6554 : public TreeTransform<CurrentInstantiationRebuilder> { 6555 SourceLocation Loc; 6556 DeclarationName Entity; 6557 6558 public: 6559 typedef TreeTransform<CurrentInstantiationRebuilder> inherited; 6560 6561 CurrentInstantiationRebuilder(Sema &SemaRef, 6562 SourceLocation Loc, 6563 DeclarationName Entity) 6564 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef), 6565 Loc(Loc), Entity(Entity) { } 6566 6567 /// \brief Determine whether the given type \p T has already been 6568 /// transformed. 6569 /// 6570 /// For the purposes of type reconstruction, a type has already been 6571 /// transformed if it is NULL or if it is not dependent. 6572 bool AlreadyTransformed(QualType T) { 6573 return T.isNull() || !T->isDependentType(); 6574 } 6575 6576 /// \brief Returns the location of the entity whose type is being 6577 /// rebuilt. 6578 SourceLocation getBaseLocation() { return Loc; } 6579 6580 /// \brief Returns the name of the entity whose type is being rebuilt. 6581 DeclarationName getBaseEntity() { return Entity; } 6582 6583 /// \brief Sets the "base" location and entity when that 6584 /// information is known based on another transformation. 6585 void setBase(SourceLocation Loc, DeclarationName Entity) { 6586 this->Loc = Loc; 6587 this->Entity = Entity; 6588 } 6589 }; 6590} 6591 6592/// \brief Rebuilds a type within the context of the current instantiation. 6593/// 6594/// The type \p T is part of the type of an out-of-line member definition of 6595/// a class template (or class template partial specialization) that was parsed 6596/// and constructed before we entered the scope of the class template (or 6597/// partial specialization thereof). This routine will rebuild that type now 6598/// that we have entered the declarator's scope, which may produce different 6599/// canonical types, e.g., 6600/// 6601/// \code 6602/// template<typename T> 6603/// struct X { 6604/// typedef T* pointer; 6605/// pointer data(); 6606/// }; 6607/// 6608/// template<typename T> 6609/// typename X<T>::pointer X<T>::data() { ... } 6610/// \endcode 6611/// 6612/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType, 6613/// since we do not know that we can look into X<T> when we parsed the type. 6614/// This function will rebuild the type, performing the lookup of "pointer" 6615/// in X<T> and returning an ElaboratedType whose canonical type is the same 6616/// as the canonical type of T*, allowing the return types of the out-of-line 6617/// definition and the declaration to match. 6618TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, 6619 SourceLocation Loc, 6620 DeclarationName Name) { 6621 if (!T || !T->getType()->isDependentType()) 6622 return T; 6623 6624 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name); 6625 return Rebuilder.TransformType(T); 6626} 6627 6628ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) { 6629 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(), 6630 DeclarationName()); 6631 return Rebuilder.TransformExpr(E); 6632} 6633 6634bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) { 6635 if (SS.isInvalid()) 6636 return true; 6637 6638 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 6639 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(), 6640 DeclarationName()); 6641 NestedNameSpecifierLoc Rebuilt 6642 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc); 6643 if (!Rebuilt) 6644 return true; 6645 6646 SS.Adopt(Rebuilt); 6647 return false; 6648} 6649 6650/// \brief Produces a formatted string that describes the binding of 6651/// template parameters to template arguments. 6652std::string 6653Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params, 6654 const TemplateArgumentList &Args) { 6655 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size()); 6656} 6657 6658std::string 6659Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params, 6660 const TemplateArgument *Args, 6661 unsigned NumArgs) { 6662 llvm::SmallString<128> Str; 6663 llvm::raw_svector_ostream Out(Str); 6664 6665 if (!Params || Params->size() == 0 || NumArgs == 0) 6666 return std::string(); 6667 6668 for (unsigned I = 0, N = Params->size(); I != N; ++I) { 6669 if (I >= NumArgs) 6670 break; 6671 6672 if (I == 0) 6673 Out << "[with "; 6674 else 6675 Out << ", "; 6676 6677 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) { 6678 Out << Id->getName(); 6679 } else { 6680 Out << '$' << I; 6681 } 6682 6683 Out << " = "; 6684 Args[I].print(Context.PrintingPolicy, Out); 6685 } 6686 6687 Out << ']'; 6688 return Out.str(); 6689} 6690 6691void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, bool Flag) { 6692 if (!FD) 6693 return; 6694 FD->setLateTemplateParsed(Flag); 6695} 6696 6697bool Sema::IsInsideALocalClassWithinATemplateFunction() { 6698 DeclContext *DC = CurContext; 6699 6700 while (DC) { 6701 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) { 6702 const FunctionDecl *FD = RD->isLocalClass(); 6703 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate); 6704 } else if (DC->isTranslationUnit() || DC->isNamespace()) 6705 return false; 6706 6707 DC = DC->getParent(); 6708 } 6709 return false; 6710} 6711