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