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