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