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