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