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