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