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