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