1//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/ 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7//===----------------------------------------------------------------------===/ 8// 9// This file implements semantic analysis for C++ templates. 10//===----------------------------------------------------------------------===/ 11 12#include "TreeTransform.h" 13#include "clang/AST/ASTConsumer.h" 14#include "clang/AST/ASTContext.h" 15#include "clang/AST/DeclFriend.h" 16#include "clang/AST/DeclTemplate.h" 17#include "clang/AST/Expr.h" 18#include "clang/AST/ExprCXX.h" 19#include "clang/AST/RecursiveASTVisitor.h" 20#include "clang/AST/TypeVisitor.h" 21#include "clang/Basic/LangOptions.h" 22#include "clang/Basic/PartialDiagnostic.h" 23#include "clang/Basic/TargetInfo.h" 24#include "clang/Sema/DeclSpec.h" 25#include "clang/Sema/Lookup.h" 26#include "clang/Sema/ParsedTemplate.h" 27#include "clang/Sema/Scope.h" 28#include "clang/Sema/SemaInternal.h" 29#include "clang/Sema/Template.h" 30#include "clang/Sema/TemplateDeduction.h" 31#include "llvm/ADT/SmallBitVector.h" 32#include "llvm/ADT/SmallString.h" 33#include "llvm/ADT/StringExtras.h" 34using namespace clang; 35using namespace sema; 36 37// Exported for use by Parser. 38SourceRange 39clang::getTemplateParamsRange(TemplateParameterList const * const *Ps, 40 unsigned N) { 41 if (!N) return SourceRange(); 42 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc()); 43} 44 45/// \brief Determine whether the declaration found is acceptable as the name 46/// of a template and, if so, return that template declaration. Otherwise, 47/// returns NULL. 48static NamedDecl *isAcceptableTemplateName(ASTContext &Context, 49 NamedDecl *Orig, 50 bool AllowFunctionTemplates) { 51 NamedDecl *D = Orig->getUnderlyingDecl(); 52 53 if (isa<TemplateDecl>(D)) { 54 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D)) 55 return nullptr; 56 57 return Orig; 58 } 59 60 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) { 61 // C++ [temp.local]p1: 62 // Like normal (non-template) classes, class templates have an 63 // injected-class-name (Clause 9). The injected-class-name 64 // can be used with or without a template-argument-list. When 65 // it is used without a template-argument-list, it is 66 // equivalent to the injected-class-name followed by the 67 // template-parameters of the class template enclosed in 68 // <>. When it is used with a template-argument-list, it 69 // refers to the specified class template specialization, 70 // which could be the current specialization or another 71 // specialization. 72 if (Record->isInjectedClassName()) { 73 Record = cast<CXXRecordDecl>(Record->getDeclContext()); 74 if (Record->getDescribedClassTemplate()) 75 return Record->getDescribedClassTemplate(); 76 77 if (ClassTemplateSpecializationDecl *Spec 78 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) 79 return Spec->getSpecializedTemplate(); 80 } 81 82 return nullptr; 83 } 84 85 return nullptr; 86} 87 88void Sema::FilterAcceptableTemplateNames(LookupResult &R, 89 bool AllowFunctionTemplates) { 90 // The set of class templates we've already seen. 91 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates; 92 LookupResult::Filter filter = R.makeFilter(); 93 while (filter.hasNext()) { 94 NamedDecl *Orig = filter.next(); 95 NamedDecl *Repl = isAcceptableTemplateName(Context, Orig, 96 AllowFunctionTemplates); 97 if (!Repl) 98 filter.erase(); 99 else if (Repl != Orig) { 100 101 // C++ [temp.local]p3: 102 // A lookup that finds an injected-class-name (10.2) can result in an 103 // ambiguity in certain cases (for example, if it is found in more than 104 // one base class). If all of the injected-class-names that are found 105 // refer to specializations of the same class template, and if the name 106 // is used as a template-name, the reference refers to the class 107 // template itself and not a specialization thereof, and is not 108 // ambiguous. 109 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl)) 110 if (!ClassTemplates.insert(ClassTmpl)) { 111 filter.erase(); 112 continue; 113 } 114 115 // FIXME: we promote access to public here as a workaround to 116 // the fact that LookupResult doesn't let us remember that we 117 // found this template through a particular injected class name, 118 // which means we end up doing nasty things to the invariants. 119 // Pretending that access is public is *much* safer. 120 filter.replace(Repl, AS_public); 121 } 122 } 123 filter.done(); 124} 125 126bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R, 127 bool AllowFunctionTemplates) { 128 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) 129 if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates)) 130 return true; 131 132 return false; 133} 134 135TemplateNameKind Sema::isTemplateName(Scope *S, 136 CXXScopeSpec &SS, 137 bool hasTemplateKeyword, 138 UnqualifiedId &Name, 139 ParsedType ObjectTypePtr, 140 bool EnteringContext, 141 TemplateTy &TemplateResult, 142 bool &MemberOfUnknownSpecialization) { 143 assert(getLangOpts().CPlusPlus && "No template names in C!"); 144 145 DeclarationName TName; 146 MemberOfUnknownSpecialization = false; 147 148 switch (Name.getKind()) { 149 case UnqualifiedId::IK_Identifier: 150 TName = DeclarationName(Name.Identifier); 151 break; 152 153 case UnqualifiedId::IK_OperatorFunctionId: 154 TName = Context.DeclarationNames.getCXXOperatorName( 155 Name.OperatorFunctionId.Operator); 156 break; 157 158 case UnqualifiedId::IK_LiteralOperatorId: 159 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier); 160 break; 161 162 default: 163 return TNK_Non_template; 164 } 165 166 QualType ObjectType = ObjectTypePtr.get(); 167 168 LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName); 169 LookupTemplateName(R, S, SS, ObjectType, EnteringContext, 170 MemberOfUnknownSpecialization); 171 if (R.empty()) return TNK_Non_template; 172 if (R.isAmbiguous()) { 173 // Suppress diagnostics; we'll redo this lookup later. 174 R.suppressDiagnostics(); 175 176 // FIXME: we might have ambiguous templates, in which case we 177 // should at least parse them properly! 178 return TNK_Non_template; 179 } 180 181 TemplateName Template; 182 TemplateNameKind TemplateKind; 183 184 unsigned ResultCount = R.end() - R.begin(); 185 if (ResultCount > 1) { 186 // We assume that we'll preserve the qualifier from a function 187 // template name in other ways. 188 Template = Context.getOverloadedTemplateName(R.begin(), R.end()); 189 TemplateKind = TNK_Function_template; 190 191 // We'll do this lookup again later. 192 R.suppressDiagnostics(); 193 } else { 194 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl()); 195 196 if (SS.isSet() && !SS.isInvalid()) { 197 NestedNameSpecifier *Qualifier = SS.getScopeRep(); 198 Template = Context.getQualifiedTemplateName(Qualifier, 199 hasTemplateKeyword, TD); 200 } else { 201 Template = TemplateName(TD); 202 } 203 204 if (isa<FunctionTemplateDecl>(TD)) { 205 TemplateKind = TNK_Function_template; 206 207 // We'll do this lookup again later. 208 R.suppressDiagnostics(); 209 } else { 210 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) || 211 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD)); 212 TemplateKind = 213 isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template; 214 } 215 } 216 217 TemplateResult = TemplateTy::make(Template); 218 return TemplateKind; 219} 220 221bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II, 222 SourceLocation IILoc, 223 Scope *S, 224 const CXXScopeSpec *SS, 225 TemplateTy &SuggestedTemplate, 226 TemplateNameKind &SuggestedKind) { 227 // We can't recover unless there's a dependent scope specifier preceding the 228 // template name. 229 // FIXME: Typo correction? 230 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) || 231 computeDeclContext(*SS)) 232 return false; 233 234 // The code is missing a 'template' keyword prior to the dependent template 235 // name. 236 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep(); 237 Diag(IILoc, diag::err_template_kw_missing) 238 << Qualifier << II.getName() 239 << FixItHint::CreateInsertion(IILoc, "template "); 240 SuggestedTemplate 241 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II)); 242 SuggestedKind = TNK_Dependent_template_name; 243 return true; 244} 245 246void Sema::LookupTemplateName(LookupResult &Found, 247 Scope *S, CXXScopeSpec &SS, 248 QualType ObjectType, 249 bool EnteringContext, 250 bool &MemberOfUnknownSpecialization) { 251 // Determine where to perform name lookup 252 MemberOfUnknownSpecialization = false; 253 DeclContext *LookupCtx = nullptr; 254 bool isDependent = false; 255 if (!ObjectType.isNull()) { 256 // This nested-name-specifier occurs in a member access expression, e.g., 257 // x->B::f, and we are looking into the type of the object. 258 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist"); 259 LookupCtx = computeDeclContext(ObjectType); 260 isDependent = ObjectType->isDependentType(); 261 assert((isDependent || !ObjectType->isIncompleteType() || 262 ObjectType->castAs<TagType>()->isBeingDefined()) && 263 "Caller should have completed object type"); 264 265 // Template names cannot appear inside an Objective-C class or object type. 266 if (ObjectType->isObjCObjectOrInterfaceType()) { 267 Found.clear(); 268 return; 269 } 270 } else if (SS.isSet()) { 271 // This nested-name-specifier occurs after another nested-name-specifier, 272 // so long into the context associated with the prior nested-name-specifier. 273 LookupCtx = computeDeclContext(SS, EnteringContext); 274 isDependent = isDependentScopeSpecifier(SS); 275 276 // The declaration context must be complete. 277 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx)) 278 return; 279 } 280 281 bool ObjectTypeSearchedInScope = false; 282 bool AllowFunctionTemplatesInLookup = true; 283 if (LookupCtx) { 284 // Perform "qualified" name lookup into the declaration context we 285 // computed, which is either the type of the base of a member access 286 // expression or the declaration context associated with a prior 287 // nested-name-specifier. 288 LookupQualifiedName(Found, LookupCtx); 289 if (!ObjectType.isNull() && Found.empty()) { 290 // C++ [basic.lookup.classref]p1: 291 // In a class member access expression (5.2.5), if the . or -> token is 292 // immediately followed by an identifier followed by a <, the 293 // identifier must be looked up to determine whether the < is the 294 // beginning of a template argument list (14.2) or a less-than operator. 295 // The identifier is first looked up in the class of the object 296 // expression. If the identifier is not found, it is then looked up in 297 // the context of the entire postfix-expression and shall name a class 298 // or function template. 299 if (S) LookupName(Found, S); 300 ObjectTypeSearchedInScope = true; 301 AllowFunctionTemplatesInLookup = false; 302 } 303 } else if (isDependent && (!S || ObjectType.isNull())) { 304 // We cannot look into a dependent object type or nested nme 305 // specifier. 306 MemberOfUnknownSpecialization = true; 307 return; 308 } else { 309 // Perform unqualified name lookup in the current scope. 310 LookupName(Found, S); 311 312 if (!ObjectType.isNull()) 313 AllowFunctionTemplatesInLookup = false; 314 } 315 316 if (Found.empty() && !isDependent) { 317 // If we did not find any names, attempt to correct any typos. 318 DeclarationName Name = Found.getLookupName(); 319 Found.clear(); 320 // Simple filter callback that, for keywords, only accepts the C++ *_cast 321 CorrectionCandidateCallback FilterCCC; 322 FilterCCC.WantTypeSpecifiers = false; 323 FilterCCC.WantExpressionKeywords = false; 324 FilterCCC.WantRemainingKeywords = false; 325 FilterCCC.WantCXXNamedCasts = true; 326 if (TypoCorrection Corrected = CorrectTypo(Found.getLookupNameInfo(), 327 Found.getLookupKind(), S, &SS, 328 FilterCCC, CTK_ErrorRecovery, 329 LookupCtx)) { 330 Found.setLookupName(Corrected.getCorrection()); 331 if (Corrected.getCorrectionDecl()) 332 Found.addDecl(Corrected.getCorrectionDecl()); 333 FilterAcceptableTemplateNames(Found); 334 if (!Found.empty()) { 335 if (LookupCtx) { 336 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 337 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 338 Name.getAsString() == CorrectedStr; 339 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest) 340 << Name << LookupCtx << DroppedSpecifier 341 << SS.getRange()); 342 } else { 343 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name); 344 } 345 } 346 } else { 347 Found.setLookupName(Name); 348 } 349 } 350 351 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup); 352 if (Found.empty()) { 353 if (isDependent) 354 MemberOfUnknownSpecialization = true; 355 return; 356 } 357 358 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope && 359 !getLangOpts().CPlusPlus11) { 360 // C++03 [basic.lookup.classref]p1: 361 // [...] If the lookup in the class of the object expression finds a 362 // template, the name is also looked up in the context of the entire 363 // postfix-expression and [...] 364 // 365 // Note: C++11 does not perform this second lookup. 366 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(), 367 LookupOrdinaryName); 368 LookupName(FoundOuter, S); 369 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false); 370 371 if (FoundOuter.empty()) { 372 // - if the name is not found, the name found in the class of the 373 // object expression is used, otherwise 374 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() || 375 FoundOuter.isAmbiguous()) { 376 // - if the name is found in the context of the entire 377 // postfix-expression and does not name a class template, the name 378 // found in the class of the object expression is used, otherwise 379 FoundOuter.clear(); 380 } else if (!Found.isSuppressingDiagnostics()) { 381 // - if the name found is a class template, it must refer to the same 382 // entity as the one found in the class of the object expression, 383 // otherwise the program is ill-formed. 384 if (!Found.isSingleResult() || 385 Found.getFoundDecl()->getCanonicalDecl() 386 != FoundOuter.getFoundDecl()->getCanonicalDecl()) { 387 Diag(Found.getNameLoc(), 388 diag::ext_nested_name_member_ref_lookup_ambiguous) 389 << Found.getLookupName() 390 << ObjectType; 391 Diag(Found.getRepresentativeDecl()->getLocation(), 392 diag::note_ambig_member_ref_object_type) 393 << ObjectType; 394 Diag(FoundOuter.getFoundDecl()->getLocation(), 395 diag::note_ambig_member_ref_scope); 396 397 // Recover by taking the template that we found in the object 398 // expression's type. 399 } 400 } 401 } 402} 403 404/// ActOnDependentIdExpression - Handle a dependent id-expression that 405/// was just parsed. This is only possible with an explicit scope 406/// specifier naming a dependent type. 407ExprResult 408Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS, 409 SourceLocation TemplateKWLoc, 410 const DeclarationNameInfo &NameInfo, 411 bool isAddressOfOperand, 412 const TemplateArgumentListInfo *TemplateArgs) { 413 DeclContext *DC = getFunctionLevelDeclContext(); 414 415 if (!isAddressOfOperand && 416 isa<CXXMethodDecl>(DC) && 417 cast<CXXMethodDecl>(DC)->isInstance()) { 418 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context); 419 420 // Since the 'this' expression is synthesized, we don't need to 421 // perform the double-lookup check. 422 NamedDecl *FirstQualifierInScope = nullptr; 423 424 return CXXDependentScopeMemberExpr::Create( 425 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true, 426 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc, 427 FirstQualifierInScope, NameInfo, TemplateArgs); 428 } 429 430 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs); 431} 432 433ExprResult 434Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS, 435 SourceLocation TemplateKWLoc, 436 const DeclarationNameInfo &NameInfo, 437 const TemplateArgumentListInfo *TemplateArgs) { 438 return DependentScopeDeclRefExpr::Create( 439 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 440 TemplateArgs); 441} 442 443/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining 444/// that the template parameter 'PrevDecl' is being shadowed by a new 445/// declaration at location Loc. Returns true to indicate that this is 446/// an error, and false otherwise. 447void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) { 448 assert(PrevDecl->isTemplateParameter() && "Not a template parameter"); 449 450 // Microsoft Visual C++ permits template parameters to be shadowed. 451 if (getLangOpts().MicrosoftExt) 452 return; 453 454 // C++ [temp.local]p4: 455 // A template-parameter shall not be redeclared within its 456 // scope (including nested scopes). 457 Diag(Loc, diag::err_template_param_shadow) 458 << cast<NamedDecl>(PrevDecl)->getDeclName(); 459 Diag(PrevDecl->getLocation(), diag::note_template_param_here); 460 return; 461} 462 463/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset 464/// the parameter D to reference the templated declaration and return a pointer 465/// to the template declaration. Otherwise, do nothing to D and return null. 466TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) { 467 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) { 468 D = Temp->getTemplatedDecl(); 469 return Temp; 470 } 471 return nullptr; 472} 473 474ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion( 475 SourceLocation EllipsisLoc) const { 476 assert(Kind == Template && 477 "Only template template arguments can be pack expansions here"); 478 assert(getAsTemplate().get().containsUnexpandedParameterPack() && 479 "Template template argument pack expansion without packs"); 480 ParsedTemplateArgument Result(*this); 481 Result.EllipsisLoc = EllipsisLoc; 482 return Result; 483} 484 485static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef, 486 const ParsedTemplateArgument &Arg) { 487 488 switch (Arg.getKind()) { 489 case ParsedTemplateArgument::Type: { 490 TypeSourceInfo *DI; 491 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI); 492 if (!DI) 493 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation()); 494 return TemplateArgumentLoc(TemplateArgument(T), DI); 495 } 496 497 case ParsedTemplateArgument::NonType: { 498 Expr *E = static_cast<Expr *>(Arg.getAsExpr()); 499 return TemplateArgumentLoc(TemplateArgument(E), E); 500 } 501 502 case ParsedTemplateArgument::Template: { 503 TemplateName Template = Arg.getAsTemplate().get(); 504 TemplateArgument TArg; 505 if (Arg.getEllipsisLoc().isValid()) 506 TArg = TemplateArgument(Template, Optional<unsigned int>()); 507 else 508 TArg = Template; 509 return TemplateArgumentLoc(TArg, 510 Arg.getScopeSpec().getWithLocInContext( 511 SemaRef.Context), 512 Arg.getLocation(), 513 Arg.getEllipsisLoc()); 514 } 515 } 516 517 llvm_unreachable("Unhandled parsed template argument"); 518} 519 520/// \brief Translates template arguments as provided by the parser 521/// into template arguments used by semantic analysis. 522void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn, 523 TemplateArgumentListInfo &TemplateArgs) { 524 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I) 525 TemplateArgs.addArgument(translateTemplateArgument(*this, 526 TemplateArgsIn[I])); 527} 528 529static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S, 530 SourceLocation Loc, 531 IdentifierInfo *Name) { 532 NamedDecl *PrevDecl = SemaRef.LookupSingleName( 533 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration); 534 if (PrevDecl && PrevDecl->isTemplateParameter()) 535 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl); 536} 537 538/// ActOnTypeParameter - Called when a C++ template type parameter 539/// (e.g., "typename T") has been parsed. Typename specifies whether 540/// the keyword "typename" was used to declare the type parameter 541/// (otherwise, "class" was used), and KeyLoc is the location of the 542/// "class" or "typename" keyword. ParamName is the name of the 543/// parameter (NULL indicates an unnamed template parameter) and 544/// ParamNameLoc is the location of the parameter name (if any). 545/// If the type parameter has a default argument, it will be added 546/// later via ActOnTypeParameterDefault. 547Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename, 548 SourceLocation EllipsisLoc, 549 SourceLocation KeyLoc, 550 IdentifierInfo *ParamName, 551 SourceLocation ParamNameLoc, 552 unsigned Depth, unsigned Position, 553 SourceLocation EqualLoc, 554 ParsedType DefaultArg) { 555 assert(S->isTemplateParamScope() && 556 "Template type parameter not in template parameter scope!"); 557 bool Invalid = false; 558 559 SourceLocation Loc = ParamNameLoc; 560 if (!ParamName) 561 Loc = KeyLoc; 562 563 bool IsParameterPack = EllipsisLoc.isValid(); 564 TemplateTypeParmDecl *Param 565 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(), 566 KeyLoc, Loc, Depth, Position, ParamName, 567 Typename, IsParameterPack); 568 Param->setAccess(AS_public); 569 if (Invalid) 570 Param->setInvalidDecl(); 571 572 if (ParamName) { 573 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName); 574 575 // Add the template parameter into the current scope. 576 S->AddDecl(Param); 577 IdResolver.AddDecl(Param); 578 } 579 580 // C++0x [temp.param]p9: 581 // A default template-argument may be specified for any kind of 582 // template-parameter that is not a template parameter pack. 583 if (DefaultArg && IsParameterPack) { 584 Diag(EqualLoc, diag::err_template_param_pack_default_arg); 585 DefaultArg = ParsedType(); 586 } 587 588 // Handle the default argument, if provided. 589 if (DefaultArg) { 590 TypeSourceInfo *DefaultTInfo; 591 GetTypeFromParser(DefaultArg, &DefaultTInfo); 592 593 assert(DefaultTInfo && "expected source information for type"); 594 595 // Check for unexpanded parameter packs. 596 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo, 597 UPPC_DefaultArgument)) 598 return Param; 599 600 // Check the template argument itself. 601 if (CheckTemplateArgument(Param, DefaultTInfo)) { 602 Param->setInvalidDecl(); 603 return Param; 604 } 605 606 Param->setDefaultArgument(DefaultTInfo, false); 607 } 608 609 return Param; 610} 611 612/// \brief Check that the type of a non-type template parameter is 613/// well-formed. 614/// 615/// \returns the (possibly-promoted) parameter type if valid; 616/// otherwise, produces a diagnostic and returns a NULL type. 617QualType 618Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) { 619 // We don't allow variably-modified types as the type of non-type template 620 // parameters. 621 if (T->isVariablyModifiedType()) { 622 Diag(Loc, diag::err_variably_modified_nontype_template_param) 623 << T; 624 return QualType(); 625 } 626 627 // C++ [temp.param]p4: 628 // 629 // A non-type template-parameter shall have one of the following 630 // (optionally cv-qualified) types: 631 // 632 // -- integral or enumeration type, 633 if (T->isIntegralOrEnumerationType() || 634 // -- pointer to object or pointer to function, 635 T->isPointerType() || 636 // -- reference to object or reference to function, 637 T->isReferenceType() || 638 // -- pointer to member, 639 T->isMemberPointerType() || 640 // -- std::nullptr_t. 641 T->isNullPtrType() || 642 // If T is a dependent type, we can't do the check now, so we 643 // assume that it is well-formed. 644 T->isDependentType()) { 645 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter 646 // are ignored when determining its type. 647 return T.getUnqualifiedType(); 648 } 649 650 // C++ [temp.param]p8: 651 // 652 // A non-type template-parameter of type "array of T" or 653 // "function returning T" is adjusted to be of type "pointer to 654 // T" or "pointer to function returning T", respectively. 655 else if (T->isArrayType()) 656 // FIXME: Keep the type prior to promotion? 657 return Context.getArrayDecayedType(T); 658 else if (T->isFunctionType()) 659 // FIXME: Keep the type prior to promotion? 660 return Context.getPointerType(T); 661 662 Diag(Loc, diag::err_template_nontype_parm_bad_type) 663 << T; 664 665 return QualType(); 666} 667 668Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, 669 unsigned Depth, 670 unsigned Position, 671 SourceLocation EqualLoc, 672 Expr *Default) { 673 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 674 QualType T = TInfo->getType(); 675 676 assert(S->isTemplateParamScope() && 677 "Non-type template parameter not in template parameter scope!"); 678 bool Invalid = false; 679 680 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc()); 681 if (T.isNull()) { 682 T = Context.IntTy; // Recover with an 'int' type. 683 Invalid = true; 684 } 685 686 IdentifierInfo *ParamName = D.getIdentifier(); 687 bool IsParameterPack = D.hasEllipsis(); 688 NonTypeTemplateParmDecl *Param 689 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(), 690 D.getLocStart(), 691 D.getIdentifierLoc(), 692 Depth, Position, ParamName, T, 693 IsParameterPack, TInfo); 694 Param->setAccess(AS_public); 695 696 if (Invalid) 697 Param->setInvalidDecl(); 698 699 if (ParamName) { 700 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(), 701 ParamName); 702 703 // Add the template parameter into the current scope. 704 S->AddDecl(Param); 705 IdResolver.AddDecl(Param); 706 } 707 708 // C++0x [temp.param]p9: 709 // A default template-argument may be specified for any kind of 710 // template-parameter that is not a template parameter pack. 711 if (Default && IsParameterPack) { 712 Diag(EqualLoc, diag::err_template_param_pack_default_arg); 713 Default = nullptr; 714 } 715 716 // Check the well-formedness of the default template argument, if provided. 717 if (Default) { 718 // Check for unexpanded parameter packs. 719 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument)) 720 return Param; 721 722 TemplateArgument Converted; 723 ExprResult DefaultRes = CheckTemplateArgument(Param, Param->getType(), Default, Converted); 724 if (DefaultRes.isInvalid()) { 725 Param->setInvalidDecl(); 726 return Param; 727 } 728 Default = DefaultRes.get(); 729 730 Param->setDefaultArgument(Default, false); 731 } 732 733 return Param; 734} 735 736/// ActOnTemplateTemplateParameter - Called when a C++ template template 737/// parameter (e.g. T in template <template \<typename> class T> class array) 738/// has been parsed. S is the current scope. 739Decl *Sema::ActOnTemplateTemplateParameter(Scope* S, 740 SourceLocation TmpLoc, 741 TemplateParameterList *Params, 742 SourceLocation EllipsisLoc, 743 IdentifierInfo *Name, 744 SourceLocation NameLoc, 745 unsigned Depth, 746 unsigned Position, 747 SourceLocation EqualLoc, 748 ParsedTemplateArgument Default) { 749 assert(S->isTemplateParamScope() && 750 "Template template parameter not in template parameter scope!"); 751 752 // Construct the parameter object. 753 bool IsParameterPack = EllipsisLoc.isValid(); 754 TemplateTemplateParmDecl *Param = 755 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(), 756 NameLoc.isInvalid()? TmpLoc : NameLoc, 757 Depth, Position, IsParameterPack, 758 Name, Params); 759 Param->setAccess(AS_public); 760 761 // If the template template parameter has a name, then link the identifier 762 // into the scope and lookup mechanisms. 763 if (Name) { 764 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name); 765 766 S->AddDecl(Param); 767 IdResolver.AddDecl(Param); 768 } 769 770 if (Params->size() == 0) { 771 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms) 772 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc()); 773 Param->setInvalidDecl(); 774 } 775 776 // C++0x [temp.param]p9: 777 // A default template-argument may be specified for any kind of 778 // template-parameter that is not a template parameter pack. 779 if (IsParameterPack && !Default.isInvalid()) { 780 Diag(EqualLoc, diag::err_template_param_pack_default_arg); 781 Default = ParsedTemplateArgument(); 782 } 783 784 if (!Default.isInvalid()) { 785 // Check only that we have a template template argument. We don't want to 786 // try to check well-formedness now, because our template template parameter 787 // might have dependent types in its template parameters, which we wouldn't 788 // be able to match now. 789 // 790 // If none of the template template parameter's template arguments mention 791 // other template parameters, we could actually perform more checking here. 792 // However, it isn't worth doing. 793 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default); 794 if (DefaultArg.getArgument().getAsTemplate().isNull()) { 795 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template) 796 << DefaultArg.getSourceRange(); 797 return Param; 798 } 799 800 // Check for unexpanded parameter packs. 801 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(), 802 DefaultArg.getArgument().getAsTemplate(), 803 UPPC_DefaultArgument)) 804 return Param; 805 806 Param->setDefaultArgument(DefaultArg, false); 807 } 808 809 return Param; 810} 811 812/// ActOnTemplateParameterList - Builds a TemplateParameterList that 813/// contains the template parameters in Params/NumParams. 814TemplateParameterList * 815Sema::ActOnTemplateParameterList(unsigned Depth, 816 SourceLocation ExportLoc, 817 SourceLocation TemplateLoc, 818 SourceLocation LAngleLoc, 819 Decl **Params, unsigned NumParams, 820 SourceLocation RAngleLoc) { 821 if (ExportLoc.isValid()) 822 Diag(ExportLoc, diag::warn_template_export_unsupported); 823 824 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc, 825 (NamedDecl**)Params, NumParams, 826 RAngleLoc); 827} 828 829static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) { 830 if (SS.isSet()) 831 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext())); 832} 833 834DeclResult 835Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, 836 SourceLocation KWLoc, CXXScopeSpec &SS, 837 IdentifierInfo *Name, SourceLocation NameLoc, 838 AttributeList *Attr, 839 TemplateParameterList *TemplateParams, 840 AccessSpecifier AS, SourceLocation ModulePrivateLoc, 841 unsigned NumOuterTemplateParamLists, 842 TemplateParameterList** OuterTemplateParamLists) { 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 LookupName(Previous, S); 899 } 900 901 if (Previous.isAmbiguous()) 902 return true; 903 904 NamedDecl *PrevDecl = nullptr; 905 if (Previous.begin() != Previous.end()) 906 PrevDecl = (*Previous.begin())->getUnderlyingDecl(); 907 908 // If there is a previous declaration with the same name, check 909 // whether this is a valid redeclaration. 910 ClassTemplateDecl *PrevClassTemplate 911 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl); 912 913 // We may have found the injected-class-name of a class template, 914 // class template partial specialization, or class template specialization. 915 // In these cases, grab the template that is being defined or specialized. 916 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) && 917 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) { 918 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext()); 919 PrevClassTemplate 920 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate(); 921 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) { 922 PrevClassTemplate 923 = cast<ClassTemplateSpecializationDecl>(PrevDecl) 924 ->getSpecializedTemplate(); 925 } 926 } 927 928 if (TUK == TUK_Friend) { 929 // C++ [namespace.memdef]p3: 930 // [...] When looking for a prior declaration of a class or a function 931 // declared as a friend, and when the name of the friend class or 932 // function is neither a qualified name nor a template-id, scopes outside 933 // the innermost enclosing namespace scope are not considered. 934 if (!SS.isSet()) { 935 DeclContext *OutermostContext = CurContext; 936 while (!OutermostContext->isFileContext()) 937 OutermostContext = OutermostContext->getLookupParent(); 938 939 if (PrevDecl && 940 (OutermostContext->Equals(PrevDecl->getDeclContext()) || 941 OutermostContext->Encloses(PrevDecl->getDeclContext()))) { 942 SemanticContext = PrevDecl->getDeclContext(); 943 } else { 944 // Declarations in outer scopes don't matter. However, the outermost 945 // context we computed is the semantic context for our new 946 // declaration. 947 PrevDecl = PrevClassTemplate = nullptr; 948 SemanticContext = OutermostContext; 949 950 // Check that the chosen semantic context doesn't already contain a 951 // declaration of this name as a non-tag type. 952 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName, 953 ForRedeclaration); 954 DeclContext *LookupContext = SemanticContext; 955 while (LookupContext->isTransparentContext()) 956 LookupContext = LookupContext->getLookupParent(); 957 LookupQualifiedName(Previous, LookupContext); 958 959 if (Previous.isAmbiguous()) 960 return true; 961 962 if (Previous.begin() != Previous.end()) 963 PrevDecl = (*Previous.begin())->getUnderlyingDecl(); 964 } 965 } 966 } else if (PrevDecl && 967 !isDeclInScope(PrevDecl, SemanticContext, S, SS.isValid())) 968 PrevDecl = PrevClassTemplate = nullptr; 969 970 if (PrevClassTemplate) { 971 // Ensure that the template parameter lists are compatible. Skip this check 972 // for a friend in a dependent context: the template parameter list itself 973 // could be dependent. 974 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) && 975 !TemplateParameterListsAreEqual(TemplateParams, 976 PrevClassTemplate->getTemplateParameters(), 977 /*Complain=*/true, 978 TPL_TemplateMatch)) 979 return true; 980 981 // C++ [temp.class]p4: 982 // In a redeclaration, partial specialization, explicit 983 // specialization or explicit instantiation of a class template, 984 // the class-key shall agree in kind with the original class 985 // template declaration (7.1.5.3). 986 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl(); 987 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, 988 TUK == TUK_Definition, KWLoc, *Name)) { 989 Diag(KWLoc, diag::err_use_with_wrong_tag) 990 << Name 991 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName()); 992 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use); 993 Kind = PrevRecordDecl->getTagKind(); 994 } 995 996 // Check for redefinition of this class template. 997 if (TUK == TUK_Definition) { 998 if (TagDecl *Def = PrevRecordDecl->getDefinition()) { 999 Diag(NameLoc, diag::err_redefinition) << Name; 1000 Diag(Def->getLocation(), diag::note_previous_definition); 1001 // FIXME: Would it make sense to try to "forget" the previous 1002 // definition, as part of error recovery? 1003 return true; 1004 } 1005 } 1006 } else if (PrevDecl && PrevDecl->isTemplateParameter()) { 1007 // Maybe we will complain about the shadowed template parameter. 1008 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl); 1009 // Just pretend that we didn't see the previous declaration. 1010 PrevDecl = nullptr; 1011 } else if (PrevDecl) { 1012 // C++ [temp]p5: 1013 // A class template shall not have the same name as any other 1014 // template, class, function, object, enumeration, enumerator, 1015 // namespace, or type in the same scope (3.3), except as specified 1016 // in (14.5.4). 1017 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 1018 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 1019 return true; 1020 } 1021 1022 // Check the template parameter list of this declaration, possibly 1023 // merging in the template parameter list from the previous class 1024 // template declaration. Skip this check for a friend in a dependent 1025 // context, because the template parameter list might be dependent. 1026 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) && 1027 CheckTemplateParameterList( 1028 TemplateParams, 1029 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters() 1030 : nullptr, 1031 (SS.isSet() && SemanticContext && SemanticContext->isRecord() && 1032 SemanticContext->isDependentContext()) 1033 ? TPC_ClassTemplateMember 1034 : TUK == TUK_Friend ? TPC_FriendClassTemplate 1035 : TPC_ClassTemplate)) 1036 Invalid = true; 1037 1038 if (SS.isSet()) { 1039 // If the name of the template was qualified, we must be defining the 1040 // template out-of-line. 1041 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) { 1042 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match 1043 : diag::err_member_decl_does_not_match) 1044 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange(); 1045 Invalid = true; 1046 } 1047 } 1048 1049 CXXRecordDecl *NewClass = 1050 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name, 1051 PrevClassTemplate? 1052 PrevClassTemplate->getTemplatedDecl() : nullptr, 1053 /*DelayTypeCreation=*/true); 1054 SetNestedNameSpecifier(NewClass, SS); 1055 if (NumOuterTemplateParamLists > 0) 1056 NewClass->setTemplateParameterListsInfo(Context, 1057 NumOuterTemplateParamLists, 1058 OuterTemplateParamLists); 1059 1060 // Add alignment attributes if necessary; these attributes are checked when 1061 // the ASTContext lays out the structure. 1062 if (TUK == TUK_Definition) { 1063 AddAlignmentAttributesForRecord(NewClass); 1064 AddMsStructLayoutForRecord(NewClass); 1065 } 1066 1067 ClassTemplateDecl *NewTemplate 1068 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc, 1069 DeclarationName(Name), TemplateParams, 1070 NewClass, PrevClassTemplate); 1071 NewClass->setDescribedClassTemplate(NewTemplate); 1072 1073 if (ModulePrivateLoc.isValid()) 1074 NewTemplate->setModulePrivate(); 1075 1076 // Build the type for the class template declaration now. 1077 QualType T = NewTemplate->getInjectedClassNameSpecialization(); 1078 T = Context.getInjectedClassNameType(NewClass, T); 1079 assert(T->isDependentType() && "Class template type is not dependent?"); 1080 (void)T; 1081 1082 // If we are providing an explicit specialization of a member that is a 1083 // class template, make a note of that. 1084 if (PrevClassTemplate && 1085 PrevClassTemplate->getInstantiatedFromMemberTemplate()) 1086 PrevClassTemplate->setMemberSpecialization(); 1087 1088 // Set the access specifier. 1089 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord()) 1090 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS); 1091 1092 // Set the lexical context of these templates 1093 NewClass->setLexicalDeclContext(CurContext); 1094 NewTemplate->setLexicalDeclContext(CurContext); 1095 1096 if (TUK == TUK_Definition) 1097 NewClass->startDefinition(); 1098 1099 if (Attr) 1100 ProcessDeclAttributeList(S, NewClass, Attr); 1101 1102 if (PrevClassTemplate) 1103 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl()); 1104 1105 AddPushedVisibilityAttribute(NewClass); 1106 1107 if (TUK != TUK_Friend) 1108 PushOnScopeChains(NewTemplate, S); 1109 else { 1110 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) { 1111 NewTemplate->setAccess(PrevClassTemplate->getAccess()); 1112 NewClass->setAccess(PrevClassTemplate->getAccess()); 1113 } 1114 1115 NewTemplate->setObjectOfFriendDecl(); 1116 1117 // Friend templates are visible in fairly strange ways. 1118 if (!CurContext->isDependentContext()) { 1119 DeclContext *DC = SemanticContext->getRedeclContext(); 1120 DC->makeDeclVisibleInContext(NewTemplate); 1121 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 1122 PushOnScopeChains(NewTemplate, EnclosingScope, 1123 /* AddToContext = */ false); 1124 } 1125 1126 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, 1127 NewClass->getLocation(), 1128 NewTemplate, 1129 /*FIXME:*/NewClass->getLocation()); 1130 Friend->setAccess(AS_public); 1131 CurContext->addDecl(Friend); 1132 } 1133 1134 if (Invalid) { 1135 NewTemplate->setInvalidDecl(); 1136 NewClass->setInvalidDecl(); 1137 } 1138 1139 ActOnDocumentableDecl(NewTemplate); 1140 1141 return NewTemplate; 1142} 1143 1144/// \brief Diagnose the presence of a default template argument on a 1145/// template parameter, which is ill-formed in certain contexts. 1146/// 1147/// \returns true if the default template argument should be dropped. 1148static bool DiagnoseDefaultTemplateArgument(Sema &S, 1149 Sema::TemplateParamListContext TPC, 1150 SourceLocation ParamLoc, 1151 SourceRange DefArgRange) { 1152 switch (TPC) { 1153 case Sema::TPC_ClassTemplate: 1154 case Sema::TPC_VarTemplate: 1155 case Sema::TPC_TypeAliasTemplate: 1156 return false; 1157 1158 case Sema::TPC_FunctionTemplate: 1159 case Sema::TPC_FriendFunctionTemplateDefinition: 1160 // C++ [temp.param]p9: 1161 // A default template-argument shall not be specified in a 1162 // function template declaration or a function template 1163 // definition [...] 1164 // If a friend function template declaration specifies a default 1165 // template-argument, that declaration shall be a definition and shall be 1166 // the only declaration of the function template in the translation unit. 1167 // (C++98/03 doesn't have this wording; see DR226). 1168 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ? 1169 diag::warn_cxx98_compat_template_parameter_default_in_function_template 1170 : diag::ext_template_parameter_default_in_function_template) 1171 << DefArgRange; 1172 return false; 1173 1174 case Sema::TPC_ClassTemplateMember: 1175 // C++0x [temp.param]p9: 1176 // A default template-argument shall not be specified in the 1177 // template-parameter-lists of the definition of a member of a 1178 // class template that appears outside of the member's class. 1179 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member) 1180 << DefArgRange; 1181 return true; 1182 1183 case Sema::TPC_FriendClassTemplate: 1184 case Sema::TPC_FriendFunctionTemplate: 1185 // C++ [temp.param]p9: 1186 // A default template-argument shall not be specified in a 1187 // friend template declaration. 1188 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template) 1189 << DefArgRange; 1190 return true; 1191 1192 // FIXME: C++0x [temp.param]p9 allows default template-arguments 1193 // for friend function templates if there is only a single 1194 // declaration (and it is a definition). Strange! 1195 } 1196 1197 llvm_unreachable("Invalid TemplateParamListContext!"); 1198} 1199 1200/// \brief Check for unexpanded parameter packs within the template parameters 1201/// of a template template parameter, recursively. 1202static bool DiagnoseUnexpandedParameterPacks(Sema &S, 1203 TemplateTemplateParmDecl *TTP) { 1204 // A template template parameter which is a parameter pack is also a pack 1205 // expansion. 1206 if (TTP->isParameterPack()) 1207 return false; 1208 1209 TemplateParameterList *Params = TTP->getTemplateParameters(); 1210 for (unsigned I = 0, N = Params->size(); I != N; ++I) { 1211 NamedDecl *P = Params->getParam(I); 1212 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) { 1213 if (!NTTP->isParameterPack() && 1214 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(), 1215 NTTP->getTypeSourceInfo(), 1216 Sema::UPPC_NonTypeTemplateParameterType)) 1217 return true; 1218 1219 continue; 1220 } 1221 1222 if (TemplateTemplateParmDecl *InnerTTP 1223 = dyn_cast<TemplateTemplateParmDecl>(P)) 1224 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP)) 1225 return true; 1226 } 1227 1228 return false; 1229} 1230 1231/// \brief Checks the validity of a template parameter list, possibly 1232/// considering the template parameter list from a previous 1233/// declaration. 1234/// 1235/// If an "old" template parameter list is provided, it must be 1236/// equivalent (per TemplateParameterListsAreEqual) to the "new" 1237/// template parameter list. 1238/// 1239/// \param NewParams Template parameter list for a new template 1240/// declaration. This template parameter list will be updated with any 1241/// default arguments that are carried through from the previous 1242/// template parameter list. 1243/// 1244/// \param OldParams If provided, template parameter list from a 1245/// previous declaration of the same template. Default template 1246/// arguments will be merged from the old template parameter list to 1247/// the new template parameter list. 1248/// 1249/// \param TPC Describes the context in which we are checking the given 1250/// template parameter list. 1251/// 1252/// \returns true if an error occurred, false otherwise. 1253bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams, 1254 TemplateParameterList *OldParams, 1255 TemplateParamListContext TPC) { 1256 bool Invalid = false; 1257 1258 // C++ [temp.param]p10: 1259 // The set of default template-arguments available for use with a 1260 // template declaration or definition is obtained by merging the 1261 // default arguments from the definition (if in scope) and all 1262 // declarations in scope in the same way default function 1263 // arguments are (8.3.6). 1264 bool SawDefaultArgument = false; 1265 SourceLocation PreviousDefaultArgLoc; 1266 1267 // Dummy initialization to avoid warnings. 1268 TemplateParameterList::iterator OldParam = NewParams->end(); 1269 if (OldParams) 1270 OldParam = OldParams->begin(); 1271 1272 bool RemoveDefaultArguments = false; 1273 for (TemplateParameterList::iterator NewParam = NewParams->begin(), 1274 NewParamEnd = NewParams->end(); 1275 NewParam != NewParamEnd; ++NewParam) { 1276 // Variables used to diagnose redundant default arguments 1277 bool RedundantDefaultArg = false; 1278 SourceLocation OldDefaultLoc; 1279 SourceLocation NewDefaultLoc; 1280 1281 // Variable used to diagnose missing default arguments 1282 bool MissingDefaultArg = false; 1283 1284 // Variable used to diagnose non-final parameter packs 1285 bool SawParameterPack = false; 1286 1287 if (TemplateTypeParmDecl *NewTypeParm 1288 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) { 1289 // Check the presence of a default argument here. 1290 if (NewTypeParm->hasDefaultArgument() && 1291 DiagnoseDefaultTemplateArgument(*this, TPC, 1292 NewTypeParm->getLocation(), 1293 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc() 1294 .getSourceRange())) 1295 NewTypeParm->removeDefaultArgument(); 1296 1297 // Merge default arguments for template type parameters. 1298 TemplateTypeParmDecl *OldTypeParm 1299 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr; 1300 1301 if (NewTypeParm->isParameterPack()) { 1302 assert(!NewTypeParm->hasDefaultArgument() && 1303 "Parameter packs can't have a default argument!"); 1304 SawParameterPack = true; 1305 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() && 1306 NewTypeParm->hasDefaultArgument()) { 1307 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc(); 1308 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc(); 1309 SawDefaultArgument = true; 1310 RedundantDefaultArg = true; 1311 PreviousDefaultArgLoc = NewDefaultLoc; 1312 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) { 1313 // Merge the default argument from the old declaration to the 1314 // new declaration. 1315 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(), 1316 true); 1317 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc(); 1318 } else if (NewTypeParm->hasDefaultArgument()) { 1319 SawDefaultArgument = true; 1320 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc(); 1321 } else if (SawDefaultArgument) 1322 MissingDefaultArg = true; 1323 } else if (NonTypeTemplateParmDecl *NewNonTypeParm 1324 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) { 1325 // Check for unexpanded parameter packs. 1326 if (!NewNonTypeParm->isParameterPack() && 1327 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(), 1328 NewNonTypeParm->getTypeSourceInfo(), 1329 UPPC_NonTypeTemplateParameterType)) { 1330 Invalid = true; 1331 continue; 1332 } 1333 1334 // Check the presence of a default argument here. 1335 if (NewNonTypeParm->hasDefaultArgument() && 1336 DiagnoseDefaultTemplateArgument(*this, TPC, 1337 NewNonTypeParm->getLocation(), 1338 NewNonTypeParm->getDefaultArgument()->getSourceRange())) { 1339 NewNonTypeParm->removeDefaultArgument(); 1340 } 1341 1342 // Merge default arguments for non-type template parameters 1343 NonTypeTemplateParmDecl *OldNonTypeParm 1344 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr; 1345 if (NewNonTypeParm->isParameterPack()) { 1346 assert(!NewNonTypeParm->hasDefaultArgument() && 1347 "Parameter packs can't have a default argument!"); 1348 if (!NewNonTypeParm->isPackExpansion()) 1349 SawParameterPack = true; 1350 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() && 1351 NewNonTypeParm->hasDefaultArgument()) { 1352 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc(); 1353 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc(); 1354 SawDefaultArgument = true; 1355 RedundantDefaultArg = true; 1356 PreviousDefaultArgLoc = NewDefaultLoc; 1357 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) { 1358 // Merge the default argument from the old declaration to the 1359 // new declaration. 1360 // FIXME: We need to create a new kind of "default argument" 1361 // expression that points to a previous non-type template 1362 // parameter. 1363 NewNonTypeParm->setDefaultArgument( 1364 OldNonTypeParm->getDefaultArgument(), 1365 /*Inherited=*/ true); 1366 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc(); 1367 } else if (NewNonTypeParm->hasDefaultArgument()) { 1368 SawDefaultArgument = true; 1369 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc(); 1370 } else if (SawDefaultArgument) 1371 MissingDefaultArg = true; 1372 } else { 1373 TemplateTemplateParmDecl *NewTemplateParm 1374 = cast<TemplateTemplateParmDecl>(*NewParam); 1375 1376 // Check for unexpanded parameter packs, recursively. 1377 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) { 1378 Invalid = true; 1379 continue; 1380 } 1381 1382 // Check the presence of a default argument here. 1383 if (NewTemplateParm->hasDefaultArgument() && 1384 DiagnoseDefaultTemplateArgument(*this, TPC, 1385 NewTemplateParm->getLocation(), 1386 NewTemplateParm->getDefaultArgument().getSourceRange())) 1387 NewTemplateParm->removeDefaultArgument(); 1388 1389 // Merge default arguments for template template parameters 1390 TemplateTemplateParmDecl *OldTemplateParm 1391 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr; 1392 if (NewTemplateParm->isParameterPack()) { 1393 assert(!NewTemplateParm->hasDefaultArgument() && 1394 "Parameter packs can't have a default argument!"); 1395 if (!NewTemplateParm->isPackExpansion()) 1396 SawParameterPack = true; 1397 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() && 1398 NewTemplateParm->hasDefaultArgument()) { 1399 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation(); 1400 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation(); 1401 SawDefaultArgument = true; 1402 RedundantDefaultArg = true; 1403 PreviousDefaultArgLoc = NewDefaultLoc; 1404 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) { 1405 // Merge the default argument from the old declaration to the 1406 // new declaration. 1407 // FIXME: We need to create a new kind of "default argument" expression 1408 // that points to a previous template template parameter. 1409 NewTemplateParm->setDefaultArgument( 1410 OldTemplateParm->getDefaultArgument(), 1411 /*Inherited=*/ true); 1412 PreviousDefaultArgLoc 1413 = OldTemplateParm->getDefaultArgument().getLocation(); 1414 } else if (NewTemplateParm->hasDefaultArgument()) { 1415 SawDefaultArgument = true; 1416 PreviousDefaultArgLoc 1417 = NewTemplateParm->getDefaultArgument().getLocation(); 1418 } else if (SawDefaultArgument) 1419 MissingDefaultArg = true; 1420 } 1421 1422 // C++11 [temp.param]p11: 1423 // If a template parameter of a primary class template or alias template 1424 // is a template parameter pack, it shall be the last template parameter. 1425 if (SawParameterPack && (NewParam + 1) != NewParamEnd && 1426 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate || 1427 TPC == TPC_TypeAliasTemplate)) { 1428 Diag((*NewParam)->getLocation(), 1429 diag::err_template_param_pack_must_be_last_template_parameter); 1430 Invalid = true; 1431 } 1432 1433 if (RedundantDefaultArg) { 1434 // C++ [temp.param]p12: 1435 // A template-parameter shall not be given default arguments 1436 // by two different declarations in the same scope. 1437 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition); 1438 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg); 1439 Invalid = true; 1440 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) { 1441 // C++ [temp.param]p11: 1442 // If a template-parameter of a class template has a default 1443 // template-argument, each subsequent template-parameter shall either 1444 // have a default template-argument supplied or be a template parameter 1445 // pack. 1446 Diag((*NewParam)->getLocation(), 1447 diag::err_template_param_default_arg_missing); 1448 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg); 1449 Invalid = true; 1450 RemoveDefaultArguments = true; 1451 } 1452 1453 // If we have an old template parameter list that we're merging 1454 // in, move on to the next parameter. 1455 if (OldParams) 1456 ++OldParam; 1457 } 1458 1459 // We were missing some default arguments at the end of the list, so remove 1460 // all of the default arguments. 1461 if (RemoveDefaultArguments) { 1462 for (TemplateParameterList::iterator NewParam = NewParams->begin(), 1463 NewParamEnd = NewParams->end(); 1464 NewParam != NewParamEnd; ++NewParam) { 1465 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam)) 1466 TTP->removeDefaultArgument(); 1467 else if (NonTypeTemplateParmDecl *NTTP 1468 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) 1469 NTTP->removeDefaultArgument(); 1470 else 1471 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument(); 1472 } 1473 } 1474 1475 return Invalid; 1476} 1477 1478namespace { 1479 1480/// A class which looks for a use of a certain level of template 1481/// parameter. 1482struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> { 1483 typedef RecursiveASTVisitor<DependencyChecker> super; 1484 1485 unsigned Depth; 1486 bool Match; 1487 SourceLocation MatchLoc; 1488 1489 DependencyChecker(unsigned Depth) : Depth(Depth), Match(false) {} 1490 1491 DependencyChecker(TemplateParameterList *Params) : Match(false) { 1492 NamedDecl *ND = Params->getParam(0); 1493 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) { 1494 Depth = PD->getDepth(); 1495 } else if (NonTypeTemplateParmDecl *PD = 1496 dyn_cast<NonTypeTemplateParmDecl>(ND)) { 1497 Depth = PD->getDepth(); 1498 } else { 1499 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth(); 1500 } 1501 } 1502 1503 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) { 1504 if (ParmDepth >= Depth) { 1505 Match = true; 1506 MatchLoc = Loc; 1507 return true; 1508 } 1509 return false; 1510 } 1511 1512 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) { 1513 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc()); 1514 } 1515 1516 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) { 1517 return !Matches(T->getDepth()); 1518 } 1519 1520 bool TraverseTemplateName(TemplateName N) { 1521 if (TemplateTemplateParmDecl *PD = 1522 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl())) 1523 if (Matches(PD->getDepth())) 1524 return false; 1525 return super::TraverseTemplateName(N); 1526 } 1527 1528 bool VisitDeclRefExpr(DeclRefExpr *E) { 1529 if (NonTypeTemplateParmDecl *PD = 1530 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl())) 1531 if (Matches(PD->getDepth(), E->getExprLoc())) 1532 return false; 1533 return super::VisitDeclRefExpr(E); 1534 } 1535 1536 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) { 1537 return TraverseType(T->getReplacementType()); 1538 } 1539 1540 bool 1541 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) { 1542 return TraverseTemplateArgument(T->getArgumentPack()); 1543 } 1544 1545 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) { 1546 return TraverseType(T->getInjectedSpecializationType()); 1547 } 1548}; 1549} 1550 1551/// Determines whether a given type depends on the given parameter 1552/// list. 1553static bool 1554DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) { 1555 DependencyChecker Checker(Params); 1556 Checker.TraverseType(T); 1557 return Checker.Match; 1558} 1559 1560// Find the source range corresponding to the named type in the given 1561// nested-name-specifier, if any. 1562static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context, 1563 QualType T, 1564 const CXXScopeSpec &SS) { 1565 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data()); 1566 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) { 1567 if (const Type *CurType = NNS->getAsType()) { 1568 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0))) 1569 return NNSLoc.getTypeLoc().getSourceRange(); 1570 } else 1571 break; 1572 1573 NNSLoc = NNSLoc.getPrefix(); 1574 } 1575 1576 return SourceRange(); 1577} 1578 1579/// \brief Match the given template parameter lists to the given scope 1580/// specifier, returning the template parameter list that applies to the 1581/// name. 1582/// 1583/// \param DeclStartLoc the start of the declaration that has a scope 1584/// specifier or a template parameter list. 1585/// 1586/// \param DeclLoc The location of the declaration itself. 1587/// 1588/// \param SS the scope specifier that will be matched to the given template 1589/// parameter lists. This scope specifier precedes a qualified name that is 1590/// being declared. 1591/// 1592/// \param TemplateId The template-id following the scope specifier, if there 1593/// is one. Used to check for a missing 'template<>'. 1594/// 1595/// \param ParamLists the template parameter lists, from the outermost to the 1596/// innermost template parameter lists. 1597/// 1598/// \param IsFriend Whether to apply the slightly different rules for 1599/// matching template parameters to scope specifiers in friend 1600/// declarations. 1601/// 1602/// \param IsExplicitSpecialization will be set true if the entity being 1603/// declared is an explicit specialization, false otherwise. 1604/// 1605/// \returns the template parameter list, if any, that corresponds to the 1606/// name that is preceded by the scope specifier @p SS. This template 1607/// parameter list may have template parameters (if we're declaring a 1608/// template) or may have no template parameters (if we're declaring a 1609/// template specialization), or may be NULL (if what we're declaring isn't 1610/// itself a template). 1611TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier( 1612 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, 1613 TemplateIdAnnotation *TemplateId, 1614 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend, 1615 bool &IsExplicitSpecialization, bool &Invalid) { 1616 IsExplicitSpecialization = false; 1617 Invalid = false; 1618 1619 // The sequence of nested types to which we will match up the template 1620 // parameter lists. We first build this list by starting with the type named 1621 // by the nested-name-specifier and walking out until we run out of types. 1622 SmallVector<QualType, 4> NestedTypes; 1623 QualType T; 1624 if (SS.getScopeRep()) { 1625 if (CXXRecordDecl *Record 1626 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true))) 1627 T = Context.getTypeDeclType(Record); 1628 else 1629 T = QualType(SS.getScopeRep()->getAsType(), 0); 1630 } 1631 1632 // If we found an explicit specialization that prevents us from needing 1633 // 'template<>' headers, this will be set to the location of that 1634 // explicit specialization. 1635 SourceLocation ExplicitSpecLoc; 1636 1637 while (!T.isNull()) { 1638 NestedTypes.push_back(T); 1639 1640 // Retrieve the parent of a record type. 1641 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) { 1642 // If this type is an explicit specialization, we're done. 1643 if (ClassTemplateSpecializationDecl *Spec 1644 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) { 1645 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) && 1646 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) { 1647 ExplicitSpecLoc = Spec->getLocation(); 1648 break; 1649 } 1650 } else if (Record->getTemplateSpecializationKind() 1651 == TSK_ExplicitSpecialization) { 1652 ExplicitSpecLoc = Record->getLocation(); 1653 break; 1654 } 1655 1656 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent())) 1657 T = Context.getTypeDeclType(Parent); 1658 else 1659 T = QualType(); 1660 continue; 1661 } 1662 1663 if (const TemplateSpecializationType *TST 1664 = T->getAs<TemplateSpecializationType>()) { 1665 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) { 1666 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext())) 1667 T = Context.getTypeDeclType(Parent); 1668 else 1669 T = QualType(); 1670 continue; 1671 } 1672 } 1673 1674 // Look one step prior in a dependent template specialization type. 1675 if (const DependentTemplateSpecializationType *DependentTST 1676 = T->getAs<DependentTemplateSpecializationType>()) { 1677 if (NestedNameSpecifier *NNS = DependentTST->getQualifier()) 1678 T = QualType(NNS->getAsType(), 0); 1679 else 1680 T = QualType(); 1681 continue; 1682 } 1683 1684 // Look one step prior in a dependent name type. 1685 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){ 1686 if (NestedNameSpecifier *NNS = DependentName->getQualifier()) 1687 T = QualType(NNS->getAsType(), 0); 1688 else 1689 T = QualType(); 1690 continue; 1691 } 1692 1693 // Retrieve the parent of an enumeration type. 1694 if (const EnumType *EnumT = T->getAs<EnumType>()) { 1695 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization 1696 // check here. 1697 EnumDecl *Enum = EnumT->getDecl(); 1698 1699 // Get to the parent type. 1700 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent())) 1701 T = Context.getTypeDeclType(Parent); 1702 else 1703 T = QualType(); 1704 continue; 1705 } 1706 1707 T = QualType(); 1708 } 1709 // Reverse the nested types list, since we want to traverse from the outermost 1710 // to the innermost while checking template-parameter-lists. 1711 std::reverse(NestedTypes.begin(), NestedTypes.end()); 1712 1713 // C++0x [temp.expl.spec]p17: 1714 // A member or a member template may be nested within many 1715 // enclosing class templates. In an explicit specialization for 1716 // such a member, the member declaration shall be preceded by a 1717 // template<> for each enclosing class template that is 1718 // explicitly specialized. 1719 bool SawNonEmptyTemplateParameterList = false; 1720 1721 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) { 1722 if (SawNonEmptyTemplateParameterList) { 1723 Diag(DeclLoc, diag::err_specialize_member_of_template) 1724 << !Recovery << Range; 1725 Invalid = true; 1726 IsExplicitSpecialization = false; 1727 return true; 1728 } 1729 1730 return false; 1731 }; 1732 1733 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) { 1734 // Check that we can have an explicit specialization here. 1735 if (CheckExplicitSpecialization(Range, true)) 1736 return true; 1737 1738 // We don't have a template header, but we should. 1739 SourceLocation ExpectedTemplateLoc; 1740 if (!ParamLists.empty()) 1741 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc(); 1742 else 1743 ExpectedTemplateLoc = DeclStartLoc; 1744 1745 Diag(DeclLoc, diag::err_template_spec_needs_header) 1746 << Range 1747 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> "); 1748 return false; 1749 }; 1750 1751 unsigned ParamIdx = 0; 1752 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes; 1753 ++TypeIdx) { 1754 T = NestedTypes[TypeIdx]; 1755 1756 // Whether we expect a 'template<>' header. 1757 bool NeedEmptyTemplateHeader = false; 1758 1759 // Whether we expect a template header with parameters. 1760 bool NeedNonemptyTemplateHeader = false; 1761 1762 // For a dependent type, the set of template parameters that we 1763 // expect to see. 1764 TemplateParameterList *ExpectedTemplateParams = nullptr; 1765 1766 // C++0x [temp.expl.spec]p15: 1767 // A member or a member template may be nested within many enclosing 1768 // class templates. In an explicit specialization for such a member, the 1769 // member declaration shall be preceded by a template<> for each 1770 // enclosing class template that is explicitly specialized. 1771 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) { 1772 if (ClassTemplatePartialSpecializationDecl *Partial 1773 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) { 1774 ExpectedTemplateParams = Partial->getTemplateParameters(); 1775 NeedNonemptyTemplateHeader = true; 1776 } else if (Record->isDependentType()) { 1777 if (Record->getDescribedClassTemplate()) { 1778 ExpectedTemplateParams = Record->getDescribedClassTemplate() 1779 ->getTemplateParameters(); 1780 NeedNonemptyTemplateHeader = true; 1781 } 1782 } else if (ClassTemplateSpecializationDecl *Spec 1783 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) { 1784 // C++0x [temp.expl.spec]p4: 1785 // Members of an explicitly specialized class template are defined 1786 // in the same manner as members of normal classes, and not using 1787 // the template<> syntax. 1788 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization) 1789 NeedEmptyTemplateHeader = true; 1790 else 1791 continue; 1792 } else if (Record->getTemplateSpecializationKind()) { 1793 if (Record->getTemplateSpecializationKind() 1794 != TSK_ExplicitSpecialization && 1795 TypeIdx == NumTypes - 1) 1796 IsExplicitSpecialization = true; 1797 1798 continue; 1799 } 1800 } else if (const TemplateSpecializationType *TST 1801 = T->getAs<TemplateSpecializationType>()) { 1802 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) { 1803 ExpectedTemplateParams = Template->getTemplateParameters(); 1804 NeedNonemptyTemplateHeader = true; 1805 } 1806 } else if (T->getAs<DependentTemplateSpecializationType>()) { 1807 // FIXME: We actually could/should check the template arguments here 1808 // against the corresponding template parameter list. 1809 NeedNonemptyTemplateHeader = false; 1810 } 1811 1812 // C++ [temp.expl.spec]p16: 1813 // In an explicit specialization declaration for a member of a class 1814 // template or a member template that ap- pears in namespace scope, the 1815 // member template and some of its enclosing class templates may remain 1816 // unspecialized, except that the declaration shall not explicitly 1817 // specialize a class member template if its en- closing class templates 1818 // are not explicitly specialized as well. 1819 if (ParamIdx < ParamLists.size()) { 1820 if (ParamLists[ParamIdx]->size() == 0) { 1821 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(), 1822 false)) 1823 return nullptr; 1824 } else 1825 SawNonEmptyTemplateParameterList = true; 1826 } 1827 1828 if (NeedEmptyTemplateHeader) { 1829 // If we're on the last of the types, and we need a 'template<>' header 1830 // here, then it's an explicit specialization. 1831 if (TypeIdx == NumTypes - 1) 1832 IsExplicitSpecialization = true; 1833 1834 if (ParamIdx < ParamLists.size()) { 1835 if (ParamLists[ParamIdx]->size() > 0) { 1836 // The header has template parameters when it shouldn't. Complain. 1837 Diag(ParamLists[ParamIdx]->getTemplateLoc(), 1838 diag::err_template_param_list_matches_nontemplate) 1839 << T 1840 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(), 1841 ParamLists[ParamIdx]->getRAngleLoc()) 1842 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS); 1843 Invalid = true; 1844 return nullptr; 1845 } 1846 1847 // Consume this template header. 1848 ++ParamIdx; 1849 continue; 1850 } 1851 1852 if (!IsFriend) 1853 if (DiagnoseMissingExplicitSpecialization( 1854 getRangeOfTypeInNestedNameSpecifier(Context, T, SS))) 1855 return nullptr; 1856 1857 continue; 1858 } 1859 1860 if (NeedNonemptyTemplateHeader) { 1861 // In friend declarations we can have template-ids which don't 1862 // depend on the corresponding template parameter lists. But 1863 // assume that empty parameter lists are supposed to match this 1864 // template-id. 1865 if (IsFriend && T->isDependentType()) { 1866 if (ParamIdx < ParamLists.size() && 1867 DependsOnTemplateParameters(T, ParamLists[ParamIdx])) 1868 ExpectedTemplateParams = nullptr; 1869 else 1870 continue; 1871 } 1872 1873 if (ParamIdx < ParamLists.size()) { 1874 // Check the template parameter list, if we can. 1875 if (ExpectedTemplateParams && 1876 !TemplateParameterListsAreEqual(ParamLists[ParamIdx], 1877 ExpectedTemplateParams, 1878 true, TPL_TemplateMatch)) 1879 Invalid = true; 1880 1881 if (!Invalid && 1882 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr, 1883 TPC_ClassTemplateMember)) 1884 Invalid = true; 1885 1886 ++ParamIdx; 1887 continue; 1888 } 1889 1890 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters) 1891 << T 1892 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS); 1893 Invalid = true; 1894 continue; 1895 } 1896 } 1897 1898 // If there were at least as many template-ids as there were template 1899 // parameter lists, then there are no template parameter lists remaining for 1900 // the declaration itself. 1901 if (ParamIdx >= ParamLists.size()) { 1902 if (TemplateId && !IsFriend) { 1903 // We don't have a template header for the declaration itself, but we 1904 // should. 1905 IsExplicitSpecialization = true; 1906 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc, 1907 TemplateId->RAngleLoc)); 1908 1909 // Fabricate an empty template parameter list for the invented header. 1910 return TemplateParameterList::Create(Context, SourceLocation(), 1911 SourceLocation(), nullptr, 0, 1912 SourceLocation()); 1913 } 1914 1915 return nullptr; 1916 } 1917 1918 // If there were too many template parameter lists, complain about that now. 1919 if (ParamIdx < ParamLists.size() - 1) { 1920 bool HasAnyExplicitSpecHeader = false; 1921 bool AllExplicitSpecHeaders = true; 1922 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) { 1923 if (ParamLists[I]->size() == 0) 1924 HasAnyExplicitSpecHeader = true; 1925 else 1926 AllExplicitSpecHeaders = false; 1927 } 1928 1929 Diag(ParamLists[ParamIdx]->getTemplateLoc(), 1930 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers 1931 : diag::err_template_spec_extra_headers) 1932 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(), 1933 ParamLists[ParamLists.size() - 2]->getRAngleLoc()); 1934 1935 // If there was a specialization somewhere, such that 'template<>' is 1936 // not required, and there were any 'template<>' headers, note where the 1937 // specialization occurred. 1938 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader) 1939 Diag(ExplicitSpecLoc, 1940 diag::note_explicit_template_spec_does_not_need_header) 1941 << NestedTypes.back(); 1942 1943 // We have a template parameter list with no corresponding scope, which 1944 // means that the resulting template declaration can't be instantiated 1945 // properly (we'll end up with dependent nodes when we shouldn't). 1946 if (!AllExplicitSpecHeaders) 1947 Invalid = true; 1948 } 1949 1950 // C++ [temp.expl.spec]p16: 1951 // In an explicit specialization declaration for a member of a class 1952 // template or a member template that ap- pears in namespace scope, the 1953 // member template and some of its enclosing class templates may remain 1954 // unspecialized, except that the declaration shall not explicitly 1955 // specialize a class member template if its en- closing class templates 1956 // are not explicitly specialized as well. 1957 if (ParamLists.back()->size() == 0 && 1958 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(), 1959 false)) 1960 return nullptr; 1961 1962 // Return the last template parameter list, which corresponds to the 1963 // entity being declared. 1964 return ParamLists.back(); 1965} 1966 1967void Sema::NoteAllFoundTemplates(TemplateName Name) { 1968 if (TemplateDecl *Template = Name.getAsTemplateDecl()) { 1969 Diag(Template->getLocation(), diag::note_template_declared_here) 1970 << (isa<FunctionTemplateDecl>(Template) 1971 ? 0 1972 : isa<ClassTemplateDecl>(Template) 1973 ? 1 1974 : isa<VarTemplateDecl>(Template) 1975 ? 2 1976 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4) 1977 << Template->getDeclName(); 1978 return; 1979 } 1980 1981 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) { 1982 for (OverloadedTemplateStorage::iterator I = OST->begin(), 1983 IEnd = OST->end(); 1984 I != IEnd; ++I) 1985 Diag((*I)->getLocation(), diag::note_template_declared_here) 1986 << 0 << (*I)->getDeclName(); 1987 1988 return; 1989 } 1990} 1991 1992QualType Sema::CheckTemplateIdType(TemplateName Name, 1993 SourceLocation TemplateLoc, 1994 TemplateArgumentListInfo &TemplateArgs) { 1995 DependentTemplateName *DTN 1996 = Name.getUnderlying().getAsDependentTemplateName(); 1997 if (DTN && DTN->isIdentifier()) 1998 // When building a template-id where the template-name is dependent, 1999 // assume the template is a type template. Either our assumption is 2000 // correct, or the code is ill-formed and will be diagnosed when the 2001 // dependent name is substituted. 2002 return Context.getDependentTemplateSpecializationType(ETK_None, 2003 DTN->getQualifier(), 2004 DTN->getIdentifier(), 2005 TemplateArgs); 2006 2007 TemplateDecl *Template = Name.getAsTemplateDecl(); 2008 if (!Template || isa<FunctionTemplateDecl>(Template) || 2009 isa<VarTemplateDecl>(Template)) { 2010 // We might have a substituted template template parameter pack. If so, 2011 // build a template specialization type for it. 2012 if (Name.getAsSubstTemplateTemplateParmPack()) 2013 return Context.getTemplateSpecializationType(Name, TemplateArgs); 2014 2015 Diag(TemplateLoc, diag::err_template_id_not_a_type) 2016 << Name; 2017 NoteAllFoundTemplates(Name); 2018 return QualType(); 2019 } 2020 2021 // Check that the template argument list is well-formed for this 2022 // template. 2023 SmallVector<TemplateArgument, 4> Converted; 2024 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs, 2025 false, Converted)) 2026 return QualType(); 2027 2028 QualType CanonType; 2029 2030 bool InstantiationDependent = false; 2031 if (TypeAliasTemplateDecl *AliasTemplate = 2032 dyn_cast<TypeAliasTemplateDecl>(Template)) { 2033 // Find the canonical type for this type alias template specialization. 2034 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl(); 2035 if (Pattern->isInvalidDecl()) 2036 return QualType(); 2037 2038 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, 2039 Converted.data(), Converted.size()); 2040 2041 // Only substitute for the innermost template argument list. 2042 MultiLevelTemplateArgumentList TemplateArgLists; 2043 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs); 2044 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth(); 2045 for (unsigned I = 0; I < Depth; ++I) 2046 TemplateArgLists.addOuterTemplateArguments(None); 2047 2048 LocalInstantiationScope Scope(*this); 2049 InstantiatingTemplate Inst(*this, TemplateLoc, Template); 2050 if (Inst.isInvalid()) 2051 return QualType(); 2052 2053 CanonType = SubstType(Pattern->getUnderlyingType(), 2054 TemplateArgLists, AliasTemplate->getLocation(), 2055 AliasTemplate->getDeclName()); 2056 if (CanonType.isNull()) 2057 return QualType(); 2058 } else if (Name.isDependent() || 2059 TemplateSpecializationType::anyDependentTemplateArguments( 2060 TemplateArgs, InstantiationDependent)) { 2061 // This class template specialization is a dependent 2062 // type. Therefore, its canonical type is another class template 2063 // specialization type that contains all of the converted 2064 // arguments in canonical form. This ensures that, e.g., A<T> and 2065 // A<T, T> have identical types when A is declared as: 2066 // 2067 // template<typename T, typename U = T> struct A; 2068 TemplateName CanonName = Context.getCanonicalTemplateName(Name); 2069 CanonType = Context.getTemplateSpecializationType(CanonName, 2070 Converted.data(), 2071 Converted.size()); 2072 2073 // FIXME: CanonType is not actually the canonical type, and unfortunately 2074 // it is a TemplateSpecializationType that we will never use again. 2075 // In the future, we need to teach getTemplateSpecializationType to only 2076 // build the canonical type and return that to us. 2077 CanonType = Context.getCanonicalType(CanonType); 2078 2079 // This might work out to be a current instantiation, in which 2080 // case the canonical type needs to be the InjectedClassNameType. 2081 // 2082 // TODO: in theory this could be a simple hashtable lookup; most 2083 // changes to CurContext don't change the set of current 2084 // instantiations. 2085 if (isa<ClassTemplateDecl>(Template)) { 2086 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) { 2087 // If we get out to a namespace, we're done. 2088 if (Ctx->isFileContext()) break; 2089 2090 // If this isn't a record, keep looking. 2091 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx); 2092 if (!Record) continue; 2093 2094 // Look for one of the two cases with InjectedClassNameTypes 2095 // and check whether it's the same template. 2096 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) && 2097 !Record->getDescribedClassTemplate()) 2098 continue; 2099 2100 // Fetch the injected class name type and check whether its 2101 // injected type is equal to the type we just built. 2102 QualType ICNT = Context.getTypeDeclType(Record); 2103 QualType Injected = cast<InjectedClassNameType>(ICNT) 2104 ->getInjectedSpecializationType(); 2105 2106 if (CanonType != Injected->getCanonicalTypeInternal()) 2107 continue; 2108 2109 // If so, the canonical type of this TST is the injected 2110 // class name type of the record we just found. 2111 assert(ICNT.isCanonical()); 2112 CanonType = ICNT; 2113 break; 2114 } 2115 } 2116 } else if (ClassTemplateDecl *ClassTemplate 2117 = dyn_cast<ClassTemplateDecl>(Template)) { 2118 // Find the class template specialization declaration that 2119 // corresponds to these arguments. 2120 void *InsertPos = nullptr; 2121 ClassTemplateSpecializationDecl *Decl 2122 = ClassTemplate->findSpecialization(Converted, InsertPos); 2123 if (!Decl) { 2124 // This is the first time we have referenced this class template 2125 // specialization. Create the canonical declaration and add it to 2126 // the set of specializations. 2127 Decl = ClassTemplateSpecializationDecl::Create(Context, 2128 ClassTemplate->getTemplatedDecl()->getTagKind(), 2129 ClassTemplate->getDeclContext(), 2130 ClassTemplate->getTemplatedDecl()->getLocStart(), 2131 ClassTemplate->getLocation(), 2132 ClassTemplate, 2133 Converted.data(), 2134 Converted.size(), nullptr); 2135 ClassTemplate->AddSpecialization(Decl, InsertPos); 2136 if (ClassTemplate->isOutOfLine()) 2137 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext()); 2138 } 2139 2140 // Diagnose uses of this specialization. 2141 (void)DiagnoseUseOfDecl(Decl, TemplateLoc); 2142 2143 CanonType = Context.getTypeDeclType(Decl); 2144 assert(isa<RecordType>(CanonType) && 2145 "type of non-dependent specialization is not a RecordType"); 2146 } 2147 2148 // Build the fully-sugared type for this class template 2149 // specialization, which refers back to the class template 2150 // specialization we created or found. 2151 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType); 2152} 2153 2154TypeResult 2155Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 2156 TemplateTy TemplateD, SourceLocation TemplateLoc, 2157 SourceLocation LAngleLoc, 2158 ASTTemplateArgsPtr TemplateArgsIn, 2159 SourceLocation RAngleLoc, 2160 bool IsCtorOrDtorName) { 2161 if (SS.isInvalid()) 2162 return true; 2163 2164 TemplateName Template = TemplateD.get(); 2165 2166 // Translate the parser's template argument list in our AST format. 2167 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); 2168 translateTemplateArguments(TemplateArgsIn, TemplateArgs); 2169 2170 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) { 2171 QualType T 2172 = Context.getDependentTemplateSpecializationType(ETK_None, 2173 DTN->getQualifier(), 2174 DTN->getIdentifier(), 2175 TemplateArgs); 2176 // Build type-source information. 2177 TypeLocBuilder TLB; 2178 DependentTemplateSpecializationTypeLoc SpecTL 2179 = TLB.push<DependentTemplateSpecializationTypeLoc>(T); 2180 SpecTL.setElaboratedKeywordLoc(SourceLocation()); 2181 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2182 SpecTL.setTemplateKeywordLoc(TemplateKWLoc); 2183 SpecTL.setTemplateNameLoc(TemplateLoc); 2184 SpecTL.setLAngleLoc(LAngleLoc); 2185 SpecTL.setRAngleLoc(RAngleLoc); 2186 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I) 2187 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo()); 2188 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T)); 2189 } 2190 2191 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs); 2192 2193 if (Result.isNull()) 2194 return true; 2195 2196 // Build type-source information. 2197 TypeLocBuilder TLB; 2198 TemplateSpecializationTypeLoc SpecTL 2199 = TLB.push<TemplateSpecializationTypeLoc>(Result); 2200 SpecTL.setTemplateKeywordLoc(TemplateKWLoc); 2201 SpecTL.setTemplateNameLoc(TemplateLoc); 2202 SpecTL.setLAngleLoc(LAngleLoc); 2203 SpecTL.setRAngleLoc(RAngleLoc); 2204 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i) 2205 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo()); 2206 2207 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a 2208 // constructor or destructor name (in such a case, the scope specifier 2209 // will be attached to the enclosing Decl or Expr node). 2210 if (SS.isNotEmpty() && !IsCtorOrDtorName) { 2211 // Create an elaborated-type-specifier containing the nested-name-specifier. 2212 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result); 2213 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result); 2214 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 2215 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2216 } 2217 2218 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result)); 2219} 2220 2221TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK, 2222 TypeSpecifierType TagSpec, 2223 SourceLocation TagLoc, 2224 CXXScopeSpec &SS, 2225 SourceLocation TemplateKWLoc, 2226 TemplateTy TemplateD, 2227 SourceLocation TemplateLoc, 2228 SourceLocation LAngleLoc, 2229 ASTTemplateArgsPtr TemplateArgsIn, 2230 SourceLocation RAngleLoc) { 2231 TemplateName Template = TemplateD.get(); 2232 2233 // Translate the parser's template argument list in our AST format. 2234 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); 2235 translateTemplateArguments(TemplateArgsIn, TemplateArgs); 2236 2237 // Determine the tag kind 2238 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 2239 ElaboratedTypeKeyword Keyword 2240 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind); 2241 2242 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) { 2243 QualType T = Context.getDependentTemplateSpecializationType(Keyword, 2244 DTN->getQualifier(), 2245 DTN->getIdentifier(), 2246 TemplateArgs); 2247 2248 // Build type-source information. 2249 TypeLocBuilder TLB; 2250 DependentTemplateSpecializationTypeLoc SpecTL 2251 = TLB.push<DependentTemplateSpecializationTypeLoc>(T); 2252 SpecTL.setElaboratedKeywordLoc(TagLoc); 2253 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2254 SpecTL.setTemplateKeywordLoc(TemplateKWLoc); 2255 SpecTL.setTemplateNameLoc(TemplateLoc); 2256 SpecTL.setLAngleLoc(LAngleLoc); 2257 SpecTL.setRAngleLoc(RAngleLoc); 2258 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I) 2259 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo()); 2260 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T)); 2261 } 2262 2263 if (TypeAliasTemplateDecl *TAT = 2264 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) { 2265 // C++0x [dcl.type.elab]p2: 2266 // If the identifier resolves to a typedef-name or the simple-template-id 2267 // resolves to an alias template specialization, the 2268 // elaborated-type-specifier is ill-formed. 2269 Diag(TemplateLoc, diag::err_tag_reference_non_tag) << 4; 2270 Diag(TAT->getLocation(), diag::note_declared_at); 2271 } 2272 2273 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs); 2274 if (Result.isNull()) 2275 return TypeResult(true); 2276 2277 // Check the tag kind 2278 if (const RecordType *RT = Result->getAs<RecordType>()) { 2279 RecordDecl *D = RT->getDecl(); 2280 2281 IdentifierInfo *Id = D->getIdentifier(); 2282 assert(Id && "templated class must have an identifier"); 2283 2284 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition, 2285 TagLoc, *Id)) { 2286 Diag(TagLoc, diag::err_use_with_wrong_tag) 2287 << Result 2288 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName()); 2289 Diag(D->getLocation(), diag::note_previous_use); 2290 } 2291 } 2292 2293 // Provide source-location information for the template specialization. 2294 TypeLocBuilder TLB; 2295 TemplateSpecializationTypeLoc SpecTL 2296 = TLB.push<TemplateSpecializationTypeLoc>(Result); 2297 SpecTL.setTemplateKeywordLoc(TemplateKWLoc); 2298 SpecTL.setTemplateNameLoc(TemplateLoc); 2299 SpecTL.setLAngleLoc(LAngleLoc); 2300 SpecTL.setRAngleLoc(RAngleLoc); 2301 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i) 2302 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo()); 2303 2304 // Construct an elaborated type containing the nested-name-specifier (if any) 2305 // and tag keyword. 2306 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result); 2307 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result); 2308 ElabTL.setElaboratedKeywordLoc(TagLoc); 2309 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 2310 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result)); 2311} 2312 2313static bool CheckTemplatePartialSpecializationArgs( 2314 Sema &S, SourceLocation NameLoc, TemplateParameterList *TemplateParams, 2315 unsigned ExplicitArgs, SmallVectorImpl<TemplateArgument> &TemplateArgs); 2316 2317static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized, 2318 NamedDecl *PrevDecl, 2319 SourceLocation Loc, 2320 bool IsPartialSpecialization); 2321 2322static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D); 2323 2324static bool isTemplateArgumentTemplateParameter( 2325 const TemplateArgument &Arg, unsigned Depth, unsigned Index) { 2326 switch (Arg.getKind()) { 2327 case TemplateArgument::Null: 2328 case TemplateArgument::NullPtr: 2329 case TemplateArgument::Integral: 2330 case TemplateArgument::Declaration: 2331 case TemplateArgument::Pack: 2332 case TemplateArgument::TemplateExpansion: 2333 return false; 2334 2335 case TemplateArgument::Type: { 2336 QualType Type = Arg.getAsType(); 2337 const TemplateTypeParmType *TPT = 2338 Arg.getAsType()->getAs<TemplateTypeParmType>(); 2339 return TPT && !Type.hasQualifiers() && 2340 TPT->getDepth() == Depth && TPT->getIndex() == Index; 2341 } 2342 2343 case TemplateArgument::Expression: { 2344 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr()); 2345 if (!DRE || !DRE->getDecl()) 2346 return false; 2347 const NonTypeTemplateParmDecl *NTTP = 2348 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()); 2349 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index; 2350 } 2351 2352 case TemplateArgument::Template: 2353 const TemplateTemplateParmDecl *TTP = 2354 dyn_cast_or_null<TemplateTemplateParmDecl>( 2355 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl()); 2356 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index; 2357 } 2358 llvm_unreachable("unexpected kind of template argument"); 2359} 2360 2361static bool isSameAsPrimaryTemplate(TemplateParameterList *Params, 2362 ArrayRef<TemplateArgument> Args) { 2363 if (Params->size() != Args.size()) 2364 return false; 2365 2366 unsigned Depth = Params->getDepth(); 2367 2368 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 2369 TemplateArgument Arg = Args[I]; 2370 2371 // If the parameter is a pack expansion, the argument must be a pack 2372 // whose only element is a pack expansion. 2373 if (Params->getParam(I)->isParameterPack()) { 2374 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 || 2375 !Arg.pack_begin()->isPackExpansion()) 2376 return false; 2377 Arg = Arg.pack_begin()->getPackExpansionPattern(); 2378 } 2379 2380 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I)) 2381 return false; 2382 } 2383 2384 return true; 2385} 2386 2387/// Convert the parser's template argument list representation into our form. 2388static TemplateArgumentListInfo 2389makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) { 2390 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc, 2391 TemplateId.RAngleLoc); 2392 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(), 2393 TemplateId.NumArgs); 2394 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs); 2395 return TemplateArgs; 2396} 2397 2398DeclResult Sema::ActOnVarTemplateSpecialization( 2399 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc, 2400 TemplateParameterList *TemplateParams, VarDecl::StorageClass SC, 2401 bool IsPartialSpecialization) { 2402 // D must be variable template id. 2403 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId && 2404 "Variable template specialization is declared with a template it."); 2405 2406 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 2407 TemplateArgumentListInfo TemplateArgs = 2408 makeTemplateArgumentListInfo(*this, *TemplateId); 2409 SourceLocation TemplateNameLoc = D.getIdentifierLoc(); 2410 SourceLocation LAngleLoc = TemplateId->LAngleLoc; 2411 SourceLocation RAngleLoc = TemplateId->RAngleLoc; 2412 2413 TemplateName Name = TemplateId->Template.get(); 2414 2415 // The template-id must name a variable template. 2416 VarTemplateDecl *VarTemplate = 2417 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl()); 2418 if (!VarTemplate) { 2419 NamedDecl *FnTemplate; 2420 if (auto *OTS = Name.getAsOverloadedTemplate()) 2421 FnTemplate = *OTS->begin(); 2422 else 2423 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl()); 2424 if (FnTemplate) 2425 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method) 2426 << FnTemplate->getDeclName(); 2427 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template) 2428 << IsPartialSpecialization; 2429 } 2430 2431 // Check for unexpanded parameter packs in any of the template arguments. 2432 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 2433 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I], 2434 UPPC_PartialSpecialization)) 2435 return true; 2436 2437 // Check that the template argument list is well-formed for this 2438 // template. 2439 SmallVector<TemplateArgument, 4> Converted; 2440 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs, 2441 false, Converted)) 2442 return true; 2443 2444 // Check that the type of this variable template specialization 2445 // matches the expected type. 2446 TypeSourceInfo *ExpectedDI; 2447 { 2448 // Do substitution on the type of the declaration 2449 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack, 2450 Converted.data(), Converted.size()); 2451 InstantiatingTemplate Inst(*this, TemplateKWLoc, VarTemplate); 2452 if (Inst.isInvalid()) 2453 return true; 2454 VarDecl *Templated = VarTemplate->getTemplatedDecl(); 2455 ExpectedDI = 2456 SubstType(Templated->getTypeSourceInfo(), 2457 MultiLevelTemplateArgumentList(TemplateArgList), 2458 Templated->getTypeSpecStartLoc(), Templated->getDeclName()); 2459 } 2460 if (!ExpectedDI) 2461 return true; 2462 2463 // Find the variable template (partial) specialization declaration that 2464 // corresponds to these arguments. 2465 if (IsPartialSpecialization) { 2466 if (CheckTemplatePartialSpecializationArgs( 2467 *this, TemplateNameLoc, VarTemplate->getTemplateParameters(), 2468 TemplateArgs.size(), Converted)) 2469 return true; 2470 2471 bool InstantiationDependent; 2472 if (!Name.isDependent() && 2473 !TemplateSpecializationType::anyDependentTemplateArguments( 2474 TemplateArgs.getArgumentArray(), TemplateArgs.size(), 2475 InstantiationDependent)) { 2476 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized) 2477 << VarTemplate->getDeclName(); 2478 IsPartialSpecialization = false; 2479 } 2480 2481 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(), 2482 Converted)) { 2483 // C++ [temp.class.spec]p9b3: 2484 // 2485 // -- The argument list of the specialization shall not be identical 2486 // to the implicit argument list of the primary template. 2487 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template) 2488 << /*variable template*/ 1 2489 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord()) 2490 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc)); 2491 // FIXME: Recover from this by treating the declaration as a redeclaration 2492 // of the primary template. 2493 return true; 2494 } 2495 } 2496 2497 void *InsertPos = nullptr; 2498 VarTemplateSpecializationDecl *PrevDecl = nullptr; 2499 2500 if (IsPartialSpecialization) 2501 // FIXME: Template parameter list matters too 2502 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos); 2503 else 2504 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos); 2505 2506 VarTemplateSpecializationDecl *Specialization = nullptr; 2507 2508 // Check whether we can declare a variable template specialization in 2509 // the current scope. 2510 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl, 2511 TemplateNameLoc, 2512 IsPartialSpecialization)) 2513 return true; 2514 2515 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) { 2516 // Since the only prior variable template specialization with these 2517 // arguments was referenced but not declared, reuse that 2518 // declaration node as our own, updating its source location and 2519 // the list of outer template parameters to reflect our new declaration. 2520 Specialization = PrevDecl; 2521 Specialization->setLocation(TemplateNameLoc); 2522 PrevDecl = nullptr; 2523 } else if (IsPartialSpecialization) { 2524 // Create a new class template partial specialization declaration node. 2525 VarTemplatePartialSpecializationDecl *PrevPartial = 2526 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl); 2527 VarTemplatePartialSpecializationDecl *Partial = 2528 VarTemplatePartialSpecializationDecl::Create( 2529 Context, VarTemplate->getDeclContext(), TemplateKWLoc, 2530 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC, 2531 Converted.data(), Converted.size(), TemplateArgs); 2532 2533 if (!PrevPartial) 2534 VarTemplate->AddPartialSpecialization(Partial, InsertPos); 2535 Specialization = Partial; 2536 2537 // If we are providing an explicit specialization of a member variable 2538 // template specialization, make a note of that. 2539 if (PrevPartial && PrevPartial->getInstantiatedFromMember()) 2540 PrevPartial->setMemberSpecialization(); 2541 2542 // Check that all of the template parameters of the variable template 2543 // partial specialization are deducible from the template 2544 // arguments. If not, this variable template partial specialization 2545 // will never be used. 2546 llvm::SmallBitVector DeducibleParams(TemplateParams->size()); 2547 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true, 2548 TemplateParams->getDepth(), DeducibleParams); 2549 2550 if (!DeducibleParams.all()) { 2551 unsigned NumNonDeducible = 2552 DeducibleParams.size() - DeducibleParams.count(); 2553 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible) 2554 << /*variable template*/ 1 << (NumNonDeducible > 1) 2555 << SourceRange(TemplateNameLoc, RAngleLoc); 2556 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) { 2557 if (!DeducibleParams[I]) { 2558 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I)); 2559 if (Param->getDeclName()) 2560 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter) 2561 << Param->getDeclName(); 2562 else 2563 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter) 2564 << "(anonymous)"; 2565 } 2566 } 2567 } 2568 } else { 2569 // Create a new class template specialization declaration node for 2570 // this explicit specialization or friend declaration. 2571 Specialization = VarTemplateSpecializationDecl::Create( 2572 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc, 2573 VarTemplate, DI->getType(), DI, SC, Converted.data(), Converted.size()); 2574 Specialization->setTemplateArgsInfo(TemplateArgs); 2575 2576 if (!PrevDecl) 2577 VarTemplate->AddSpecialization(Specialization, InsertPos); 2578 } 2579 2580 // C++ [temp.expl.spec]p6: 2581 // If a template, a member template or the member of a class template is 2582 // explicitly specialized then that specialization shall be declared 2583 // before the first use of that specialization that would cause an implicit 2584 // instantiation to take place, in every translation unit in which such a 2585 // use occurs; no diagnostic is required. 2586 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) { 2587 bool Okay = false; 2588 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) { 2589 // Is there any previous explicit specialization declaration? 2590 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) { 2591 Okay = true; 2592 break; 2593 } 2594 } 2595 2596 if (!Okay) { 2597 SourceRange Range(TemplateNameLoc, RAngleLoc); 2598 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation) 2599 << Name << Range; 2600 2601 Diag(PrevDecl->getPointOfInstantiation(), 2602 diag::note_instantiation_required_here) 2603 << (PrevDecl->getTemplateSpecializationKind() != 2604 TSK_ImplicitInstantiation); 2605 return true; 2606 } 2607 } 2608 2609 Specialization->setTemplateKeywordLoc(TemplateKWLoc); 2610 Specialization->setLexicalDeclContext(CurContext); 2611 2612 // Add the specialization into its lexical context, so that it can 2613 // be seen when iterating through the list of declarations in that 2614 // context. However, specializations are not found by name lookup. 2615 CurContext->addDecl(Specialization); 2616 2617 // Note that this is an explicit specialization. 2618 Specialization->setSpecializationKind(TSK_ExplicitSpecialization); 2619 2620 if (PrevDecl) { 2621 // Check that this isn't a redefinition of this specialization, 2622 // merging with previous declarations. 2623 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName, 2624 ForRedeclaration); 2625 PrevSpec.addDecl(PrevDecl); 2626 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec)); 2627 } else if (Specialization->isStaticDataMember() && 2628 Specialization->isOutOfLine()) { 2629 Specialization->setAccess(VarTemplate->getAccess()); 2630 } 2631 2632 // Link instantiations of static data members back to the template from 2633 // which they were instantiated. 2634 if (Specialization->isStaticDataMember()) 2635 Specialization->setInstantiationOfStaticDataMember( 2636 VarTemplate->getTemplatedDecl(), 2637 Specialization->getSpecializationKind()); 2638 2639 return Specialization; 2640} 2641 2642namespace { 2643/// \brief A partial specialization whose template arguments have matched 2644/// a given template-id. 2645struct PartialSpecMatchResult { 2646 VarTemplatePartialSpecializationDecl *Partial; 2647 TemplateArgumentList *Args; 2648}; 2649} 2650 2651DeclResult 2652Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc, 2653 SourceLocation TemplateNameLoc, 2654 const TemplateArgumentListInfo &TemplateArgs) { 2655 assert(Template && "A variable template id without template?"); 2656 2657 // Check that the template argument list is well-formed for this template. 2658 SmallVector<TemplateArgument, 4> Converted; 2659 if (CheckTemplateArgumentList( 2660 Template, TemplateNameLoc, 2661 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false, 2662 Converted)) 2663 return true; 2664 2665 // Find the variable template specialization declaration that 2666 // corresponds to these arguments. 2667 void *InsertPos = nullptr; 2668 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization( 2669 Converted, InsertPos)) 2670 // If we already have a variable template specialization, return it. 2671 return Spec; 2672 2673 // This is the first time we have referenced this variable template 2674 // specialization. Create the canonical declaration and add it to 2675 // the set of specializations, based on the closest partial specialization 2676 // that it represents. That is, 2677 VarDecl *InstantiationPattern = Template->getTemplatedDecl(); 2678 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack, 2679 Converted.data(), Converted.size()); 2680 TemplateArgumentList *InstantiationArgs = &TemplateArgList; 2681 bool AmbiguousPartialSpec = false; 2682 typedef PartialSpecMatchResult MatchResult; 2683 SmallVector<MatchResult, 4> Matched; 2684 SourceLocation PointOfInstantiation = TemplateNameLoc; 2685 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation); 2686 2687 // 1. Attempt to find the closest partial specialization that this 2688 // specializes, if any. 2689 // If any of the template arguments is dependent, then this is probably 2690 // a placeholder for an incomplete declarative context; which must be 2691 // complete by instantiation time. Thus, do not search through the partial 2692 // specializations yet. 2693 // TODO: Unify with InstantiateClassTemplateSpecialization()? 2694 // Perhaps better after unification of DeduceTemplateArguments() and 2695 // getMoreSpecializedPartialSpecialization(). 2696 bool InstantiationDependent = false; 2697 if (!TemplateSpecializationType::anyDependentTemplateArguments( 2698 TemplateArgs, InstantiationDependent)) { 2699 2700 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs; 2701 Template->getPartialSpecializations(PartialSpecs); 2702 2703 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) { 2704 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I]; 2705 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 2706 2707 if (TemplateDeductionResult Result = 2708 DeduceTemplateArguments(Partial, TemplateArgList, Info)) { 2709 // Store the failed-deduction information for use in diagnostics, later. 2710 // TODO: Actually use the failed-deduction info? 2711 FailedCandidates.addCandidate() 2712 .set(Partial, MakeDeductionFailureInfo(Context, Result, Info)); 2713 (void)Result; 2714 } else { 2715 Matched.push_back(PartialSpecMatchResult()); 2716 Matched.back().Partial = Partial; 2717 Matched.back().Args = Info.take(); 2718 } 2719 } 2720 2721 if (Matched.size() >= 1) { 2722 SmallVector<MatchResult, 4>::iterator Best = Matched.begin(); 2723 if (Matched.size() == 1) { 2724 // -- If exactly one matching specialization is found, the 2725 // instantiation is generated from that specialization. 2726 // We don't need to do anything for this. 2727 } else { 2728 // -- If more than one matching specialization is found, the 2729 // partial order rules (14.5.4.2) are used to determine 2730 // whether one of the specializations is more specialized 2731 // than the others. If none of the specializations is more 2732 // specialized than all of the other matching 2733 // specializations, then the use of the variable template is 2734 // ambiguous and the program is ill-formed. 2735 for (SmallVector<MatchResult, 4>::iterator P = Best + 1, 2736 PEnd = Matched.end(); 2737 P != PEnd; ++P) { 2738 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial, 2739 PointOfInstantiation) == 2740 P->Partial) 2741 Best = P; 2742 } 2743 2744 // Determine if the best partial specialization is more specialized than 2745 // the others. 2746 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(), 2747 PEnd = Matched.end(); 2748 P != PEnd; ++P) { 2749 if (P != Best && getMoreSpecializedPartialSpecialization( 2750 P->Partial, Best->Partial, 2751 PointOfInstantiation) != Best->Partial) { 2752 AmbiguousPartialSpec = true; 2753 break; 2754 } 2755 } 2756 } 2757 2758 // Instantiate using the best variable template partial specialization. 2759 InstantiationPattern = Best->Partial; 2760 InstantiationArgs = Best->Args; 2761 } else { 2762 // -- If no match is found, the instantiation is generated 2763 // from the primary template. 2764 // InstantiationPattern = Template->getTemplatedDecl(); 2765 } 2766 } 2767 2768 // 2. Create the canonical declaration. 2769 // Note that we do not instantiate the variable just yet, since 2770 // instantiation is handled in DoMarkVarDeclReferenced(). 2771 // FIXME: LateAttrs et al.? 2772 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation( 2773 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs, 2774 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/); 2775 if (!Decl) 2776 return true; 2777 2778 if (AmbiguousPartialSpec) { 2779 // Partial ordering did not produce a clear winner. Complain. 2780 Decl->setInvalidDecl(); 2781 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous) 2782 << Decl; 2783 2784 // Print the matching partial specializations. 2785 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(), 2786 PEnd = Matched.end(); 2787 P != PEnd; ++P) 2788 Diag(P->Partial->getLocation(), diag::note_partial_spec_match) 2789 << getTemplateArgumentBindingsText( 2790 P->Partial->getTemplateParameters(), *P->Args); 2791 return true; 2792 } 2793 2794 if (VarTemplatePartialSpecializationDecl *D = 2795 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern)) 2796 Decl->setInstantiationOf(D, InstantiationArgs); 2797 2798 assert(Decl && "No variable template specialization?"); 2799 return Decl; 2800} 2801 2802ExprResult 2803Sema::CheckVarTemplateId(const CXXScopeSpec &SS, 2804 const DeclarationNameInfo &NameInfo, 2805 VarTemplateDecl *Template, SourceLocation TemplateLoc, 2806 const TemplateArgumentListInfo *TemplateArgs) { 2807 2808 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(), 2809 *TemplateArgs); 2810 if (Decl.isInvalid()) 2811 return ExprError(); 2812 2813 VarDecl *Var = cast<VarDecl>(Decl.get()); 2814 if (!Var->getTemplateSpecializationKind()) 2815 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation, 2816 NameInfo.getLoc()); 2817 2818 // Build an ordinary singleton decl ref. 2819 return BuildDeclarationNameExpr(SS, NameInfo, Var, 2820 /*FoundD=*/nullptr, TemplateArgs); 2821} 2822 2823ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS, 2824 SourceLocation TemplateKWLoc, 2825 LookupResult &R, 2826 bool RequiresADL, 2827 const TemplateArgumentListInfo *TemplateArgs) { 2828 // FIXME: Can we do any checking at this point? I guess we could check the 2829 // template arguments that we have against the template name, if the template 2830 // name refers to a single template. That's not a terribly common case, 2831 // though. 2832 // foo<int> could identify a single function unambiguously 2833 // This approach does NOT work, since f<int>(1); 2834 // gets resolved prior to resorting to overload resolution 2835 // i.e., template<class T> void f(double); 2836 // vs template<class T, class U> void f(U); 2837 2838 // These should be filtered out by our callers. 2839 assert(!R.empty() && "empty lookup results when building templateid"); 2840 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid"); 2841 2842 // In C++1y, check variable template ids. 2843 bool InstantiationDependent; 2844 if (R.getAsSingle<VarTemplateDecl>() && 2845 !TemplateSpecializationType::anyDependentTemplateArguments( 2846 *TemplateArgs, InstantiationDependent)) { 2847 return CheckVarTemplateId(SS, R.getLookupNameInfo(), 2848 R.getAsSingle<VarTemplateDecl>(), 2849 TemplateKWLoc, TemplateArgs); 2850 } 2851 2852 // We don't want lookup warnings at this point. 2853 R.suppressDiagnostics(); 2854 2855 UnresolvedLookupExpr *ULE 2856 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 2857 SS.getWithLocInContext(Context), 2858 TemplateKWLoc, 2859 R.getLookupNameInfo(), 2860 RequiresADL, TemplateArgs, 2861 R.begin(), R.end()); 2862 2863 return ULE; 2864} 2865 2866// We actually only call this from template instantiation. 2867ExprResult 2868Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, 2869 SourceLocation TemplateKWLoc, 2870 const DeclarationNameInfo &NameInfo, 2871 const TemplateArgumentListInfo *TemplateArgs) { 2872 2873 assert(TemplateArgs || TemplateKWLoc.isValid()); 2874 DeclContext *DC; 2875 if (!(DC = computeDeclContext(SS, false)) || 2876 DC->isDependentContext() || 2877 RequireCompleteDeclContext(SS, DC)) 2878 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs); 2879 2880 bool MemberOfUnknownSpecialization; 2881 LookupResult R(*this, NameInfo, LookupOrdinaryName); 2882 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false, 2883 MemberOfUnknownSpecialization); 2884 2885 if (R.isAmbiguous()) 2886 return ExprError(); 2887 2888 if (R.empty()) { 2889 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template) 2890 << NameInfo.getName() << SS.getRange(); 2891 return ExprError(); 2892 } 2893 2894 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) { 2895 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template) 2896 << SS.getScopeRep() 2897 << NameInfo.getName().getAsString() << SS.getRange(); 2898 Diag(Temp->getLocation(), diag::note_referenced_class_template); 2899 return ExprError(); 2900 } 2901 2902 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs); 2903} 2904 2905/// \brief Form a dependent template name. 2906/// 2907/// This action forms a dependent template name given the template 2908/// name and its (presumably dependent) scope specifier. For 2909/// example, given "MetaFun::template apply", the scope specifier \p 2910/// SS will be "MetaFun::", \p TemplateKWLoc contains the location 2911/// of the "template" keyword, and "apply" is the \p Name. 2912TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S, 2913 CXXScopeSpec &SS, 2914 SourceLocation TemplateKWLoc, 2915 UnqualifiedId &Name, 2916 ParsedType ObjectType, 2917 bool EnteringContext, 2918 TemplateTy &Result) { 2919 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent()) 2920 Diag(TemplateKWLoc, 2921 getLangOpts().CPlusPlus11 ? 2922 diag::warn_cxx98_compat_template_outside_of_template : 2923 diag::ext_template_outside_of_template) 2924 << FixItHint::CreateRemoval(TemplateKWLoc); 2925 2926 DeclContext *LookupCtx = nullptr; 2927 if (SS.isSet()) 2928 LookupCtx = computeDeclContext(SS, EnteringContext); 2929 if (!LookupCtx && ObjectType) 2930 LookupCtx = computeDeclContext(ObjectType.get()); 2931 if (LookupCtx) { 2932 // C++0x [temp.names]p5: 2933 // If a name prefixed by the keyword template is not the name of 2934 // a template, the program is ill-formed. [Note: the keyword 2935 // template may not be applied to non-template members of class 2936 // templates. -end note ] [ Note: as is the case with the 2937 // typename prefix, the template prefix is allowed in cases 2938 // where it is not strictly necessary; i.e., when the 2939 // nested-name-specifier or the expression on the left of the -> 2940 // or . is not dependent on a template-parameter, or the use 2941 // does not appear in the scope of a template. -end note] 2942 // 2943 // Note: C++03 was more strict here, because it banned the use of 2944 // the "template" keyword prior to a template-name that was not a 2945 // dependent name. C++ DR468 relaxed this requirement (the 2946 // "template" keyword is now permitted). We follow the C++0x 2947 // rules, even in C++03 mode with a warning, retroactively applying the DR. 2948 bool MemberOfUnknownSpecialization; 2949 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name, 2950 ObjectType, EnteringContext, Result, 2951 MemberOfUnknownSpecialization); 2952 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() && 2953 isa<CXXRecordDecl>(LookupCtx) && 2954 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() || 2955 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) { 2956 // This is a dependent template. Handle it below. 2957 } else if (TNK == TNK_Non_template) { 2958 Diag(Name.getLocStart(), 2959 diag::err_template_kw_refers_to_non_template) 2960 << GetNameFromUnqualifiedId(Name).getName() 2961 << Name.getSourceRange() 2962 << TemplateKWLoc; 2963 return TNK_Non_template; 2964 } else { 2965 // We found something; return it. 2966 return TNK; 2967 } 2968 } 2969 2970 NestedNameSpecifier *Qualifier = SS.getScopeRep(); 2971 2972 switch (Name.getKind()) { 2973 case UnqualifiedId::IK_Identifier: 2974 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier, 2975 Name.Identifier)); 2976 return TNK_Dependent_template_name; 2977 2978 case UnqualifiedId::IK_OperatorFunctionId: 2979 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier, 2980 Name.OperatorFunctionId.Operator)); 2981 return TNK_Function_template; 2982 2983 case UnqualifiedId::IK_LiteralOperatorId: 2984 llvm_unreachable("literal operator id cannot have a dependent scope"); 2985 2986 default: 2987 break; 2988 } 2989 2990 Diag(Name.getLocStart(), 2991 diag::err_template_kw_refers_to_non_template) 2992 << GetNameFromUnqualifiedId(Name).getName() 2993 << Name.getSourceRange() 2994 << TemplateKWLoc; 2995 return TNK_Non_template; 2996} 2997 2998bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, 2999 TemplateArgumentLoc &AL, 3000 SmallVectorImpl<TemplateArgument> &Converted) { 3001 const TemplateArgument &Arg = AL.getArgument(); 3002 QualType ArgType; 3003 TypeSourceInfo *TSI = nullptr; 3004 3005 // Check template type parameter. 3006 switch(Arg.getKind()) { 3007 case TemplateArgument::Type: 3008 // C++ [temp.arg.type]p1: 3009 // A template-argument for a template-parameter which is a 3010 // type shall be a type-id. 3011 ArgType = Arg.getAsType(); 3012 TSI = AL.getTypeSourceInfo(); 3013 break; 3014 case TemplateArgument::Template: { 3015 // We have a template type parameter but the template argument 3016 // is a template without any arguments. 3017 SourceRange SR = AL.getSourceRange(); 3018 TemplateName Name = Arg.getAsTemplate(); 3019 Diag(SR.getBegin(), diag::err_template_missing_args) 3020 << Name << SR; 3021 if (TemplateDecl *Decl = Name.getAsTemplateDecl()) 3022 Diag(Decl->getLocation(), diag::note_template_decl_here); 3023 3024 return true; 3025 } 3026 case TemplateArgument::Expression: { 3027 // We have a template type parameter but the template argument is an 3028 // expression; see if maybe it is missing the "typename" keyword. 3029 CXXScopeSpec SS; 3030 DeclarationNameInfo NameInfo; 3031 3032 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) { 3033 SS.Adopt(ArgExpr->getQualifierLoc()); 3034 NameInfo = ArgExpr->getNameInfo(); 3035 } else if (DependentScopeDeclRefExpr *ArgExpr = 3036 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) { 3037 SS.Adopt(ArgExpr->getQualifierLoc()); 3038 NameInfo = ArgExpr->getNameInfo(); 3039 } else if (CXXDependentScopeMemberExpr *ArgExpr = 3040 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) { 3041 if (ArgExpr->isImplicitAccess()) { 3042 SS.Adopt(ArgExpr->getQualifierLoc()); 3043 NameInfo = ArgExpr->getMemberNameInfo(); 3044 } 3045 } 3046 3047 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) { 3048 LookupResult Result(*this, NameInfo, LookupOrdinaryName); 3049 LookupParsedName(Result, CurScope, &SS); 3050 3051 if (Result.getAsSingle<TypeDecl>() || 3052 Result.getResultKind() == 3053 LookupResult::NotFoundInCurrentInstantiation) { 3054 // Suggest that the user add 'typename' before the NNS. 3055 SourceLocation Loc = AL.getSourceRange().getBegin(); 3056 Diag(Loc, getLangOpts().MSVCCompat 3057 ? diag::ext_ms_template_type_arg_missing_typename 3058 : diag::err_template_arg_must_be_type_suggest) 3059 << FixItHint::CreateInsertion(Loc, "typename "); 3060 Diag(Param->getLocation(), diag::note_template_param_here); 3061 3062 // Recover by synthesizing a type using the location information that we 3063 // already have. 3064 ArgType = 3065 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II); 3066 TypeLocBuilder TLB; 3067 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType); 3068 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/)); 3069 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 3070 TL.setNameLoc(NameInfo.getLoc()); 3071 TSI = TLB.getTypeSourceInfo(Context, ArgType); 3072 3073 // Overwrite our input TemplateArgumentLoc so that we can recover 3074 // properly. 3075 AL = TemplateArgumentLoc(TemplateArgument(ArgType), 3076 TemplateArgumentLocInfo(TSI)); 3077 3078 break; 3079 } 3080 } 3081 // fallthrough 3082 } 3083 default: { 3084 // We have a template type parameter but the template argument 3085 // is not a type. 3086 SourceRange SR = AL.getSourceRange(); 3087 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR; 3088 Diag(Param->getLocation(), diag::note_template_param_here); 3089 3090 return true; 3091 } 3092 } 3093 3094 if (CheckTemplateArgument(Param, TSI)) 3095 return true; 3096 3097 // Add the converted template type argument. 3098 ArgType = Context.getCanonicalType(ArgType); 3099 3100 // Objective-C ARC: 3101 // If an explicitly-specified template argument type is a lifetime type 3102 // with no lifetime qualifier, the __strong lifetime qualifier is inferred. 3103 if (getLangOpts().ObjCAutoRefCount && 3104 ArgType->isObjCLifetimeType() && 3105 !ArgType.getObjCLifetime()) { 3106 Qualifiers Qs; 3107 Qs.setObjCLifetime(Qualifiers::OCL_Strong); 3108 ArgType = Context.getQualifiedType(ArgType, Qs); 3109 } 3110 3111 Converted.push_back(TemplateArgument(ArgType)); 3112 return false; 3113} 3114 3115/// \brief Substitute template arguments into the default template argument for 3116/// the given template type parameter. 3117/// 3118/// \param SemaRef the semantic analysis object for which we are performing 3119/// the substitution. 3120/// 3121/// \param Template the template that we are synthesizing template arguments 3122/// for. 3123/// 3124/// \param TemplateLoc the location of the template name that started the 3125/// template-id we are checking. 3126/// 3127/// \param RAngleLoc the location of the right angle bracket ('>') that 3128/// terminates the template-id. 3129/// 3130/// \param Param the template template parameter whose default we are 3131/// substituting into. 3132/// 3133/// \param Converted the list of template arguments provided for template 3134/// parameters that precede \p Param in the template parameter list. 3135/// \returns the substituted template argument, or NULL if an error occurred. 3136static TypeSourceInfo * 3137SubstDefaultTemplateArgument(Sema &SemaRef, 3138 TemplateDecl *Template, 3139 SourceLocation TemplateLoc, 3140 SourceLocation RAngleLoc, 3141 TemplateTypeParmDecl *Param, 3142 SmallVectorImpl<TemplateArgument> &Converted) { 3143 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo(); 3144 3145 // If the argument type is dependent, instantiate it now based 3146 // on the previously-computed template arguments. 3147 if (ArgType->getType()->isDependentType()) { 3148 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, 3149 Template, Converted, 3150 SourceRange(TemplateLoc, RAngleLoc)); 3151 if (Inst.isInvalid()) 3152 return nullptr; 3153 3154 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, 3155 Converted.data(), Converted.size()); 3156 3157 // Only substitute for the innermost template argument list. 3158 MultiLevelTemplateArgumentList TemplateArgLists; 3159 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs); 3160 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i) 3161 TemplateArgLists.addOuterTemplateArguments(None); 3162 3163 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext()); 3164 ArgType = 3165 SemaRef.SubstType(ArgType, TemplateArgLists, 3166 Param->getDefaultArgumentLoc(), Param->getDeclName()); 3167 } 3168 3169 return ArgType; 3170} 3171 3172/// \brief Substitute template arguments into the default template argument for 3173/// the given non-type template parameter. 3174/// 3175/// \param SemaRef the semantic analysis object for which we are performing 3176/// the substitution. 3177/// 3178/// \param Template the template that we are synthesizing template arguments 3179/// for. 3180/// 3181/// \param TemplateLoc the location of the template name that started the 3182/// template-id we are checking. 3183/// 3184/// \param RAngleLoc the location of the right angle bracket ('>') that 3185/// terminates the template-id. 3186/// 3187/// \param Param the non-type template parameter whose default we are 3188/// substituting into. 3189/// 3190/// \param Converted the list of template arguments provided for template 3191/// parameters that precede \p Param in the template parameter list. 3192/// 3193/// \returns the substituted template argument, or NULL if an error occurred. 3194static ExprResult 3195SubstDefaultTemplateArgument(Sema &SemaRef, 3196 TemplateDecl *Template, 3197 SourceLocation TemplateLoc, 3198 SourceLocation RAngleLoc, 3199 NonTypeTemplateParmDecl *Param, 3200 SmallVectorImpl<TemplateArgument> &Converted) { 3201 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, 3202 Template, Converted, 3203 SourceRange(TemplateLoc, RAngleLoc)); 3204 if (Inst.isInvalid()) 3205 return ExprError(); 3206 3207 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, 3208 Converted.data(), Converted.size()); 3209 3210 // Only substitute for the innermost template argument list. 3211 MultiLevelTemplateArgumentList TemplateArgLists; 3212 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs); 3213 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i) 3214 TemplateArgLists.addOuterTemplateArguments(None); 3215 3216 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext()); 3217 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated); 3218 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists); 3219} 3220 3221/// \brief Substitute template arguments into the default template argument for 3222/// the given template template parameter. 3223/// 3224/// \param SemaRef the semantic analysis object for which we are performing 3225/// the substitution. 3226/// 3227/// \param Template the template that we are synthesizing template arguments 3228/// for. 3229/// 3230/// \param TemplateLoc the location of the template name that started the 3231/// template-id we are checking. 3232/// 3233/// \param RAngleLoc the location of the right angle bracket ('>') that 3234/// terminates the template-id. 3235/// 3236/// \param Param the template template parameter whose default we are 3237/// substituting into. 3238/// 3239/// \param Converted the list of template arguments provided for template 3240/// parameters that precede \p Param in the template parameter list. 3241/// 3242/// \param QualifierLoc Will be set to the nested-name-specifier (with 3243/// source-location information) that precedes the template name. 3244/// 3245/// \returns the substituted template argument, or NULL if an error occurred. 3246static TemplateName 3247SubstDefaultTemplateArgument(Sema &SemaRef, 3248 TemplateDecl *Template, 3249 SourceLocation TemplateLoc, 3250 SourceLocation RAngleLoc, 3251 TemplateTemplateParmDecl *Param, 3252 SmallVectorImpl<TemplateArgument> &Converted, 3253 NestedNameSpecifierLoc &QualifierLoc) { 3254 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Template, Converted, 3255 SourceRange(TemplateLoc, RAngleLoc)); 3256 if (Inst.isInvalid()) 3257 return TemplateName(); 3258 3259 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, 3260 Converted.data(), Converted.size()); 3261 3262 // Only substitute for the innermost template argument list. 3263 MultiLevelTemplateArgumentList TemplateArgLists; 3264 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs); 3265 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i) 3266 TemplateArgLists.addOuterTemplateArguments(None); 3267 3268 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext()); 3269 // Substitute into the nested-name-specifier first, 3270 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc(); 3271 if (QualifierLoc) { 3272 QualifierLoc = 3273 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists); 3274 if (!QualifierLoc) 3275 return TemplateName(); 3276 } 3277 3278 return SemaRef.SubstTemplateName( 3279 QualifierLoc, 3280 Param->getDefaultArgument().getArgument().getAsTemplate(), 3281 Param->getDefaultArgument().getTemplateNameLoc(), 3282 TemplateArgLists); 3283} 3284 3285/// \brief If the given template parameter has a default template 3286/// argument, substitute into that default template argument and 3287/// return the corresponding template argument. 3288TemplateArgumentLoc 3289Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, 3290 SourceLocation TemplateLoc, 3291 SourceLocation RAngleLoc, 3292 Decl *Param, 3293 SmallVectorImpl<TemplateArgument> 3294 &Converted, 3295 bool &HasDefaultArg) { 3296 HasDefaultArg = false; 3297 3298 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) { 3299 if (!TypeParm->hasDefaultArgument()) 3300 return TemplateArgumentLoc(); 3301 3302 HasDefaultArg = true; 3303 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template, 3304 TemplateLoc, 3305 RAngleLoc, 3306 TypeParm, 3307 Converted); 3308 if (DI) 3309 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI); 3310 3311 return TemplateArgumentLoc(); 3312 } 3313 3314 if (NonTypeTemplateParmDecl *NonTypeParm 3315 = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 3316 if (!NonTypeParm->hasDefaultArgument()) 3317 return TemplateArgumentLoc(); 3318 3319 HasDefaultArg = true; 3320 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template, 3321 TemplateLoc, 3322 RAngleLoc, 3323 NonTypeParm, 3324 Converted); 3325 if (Arg.isInvalid()) 3326 return TemplateArgumentLoc(); 3327 3328 Expr *ArgE = Arg.getAs<Expr>(); 3329 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE); 3330 } 3331 3332 TemplateTemplateParmDecl *TempTempParm 3333 = cast<TemplateTemplateParmDecl>(Param); 3334 if (!TempTempParm->hasDefaultArgument()) 3335 return TemplateArgumentLoc(); 3336 3337 HasDefaultArg = true; 3338 NestedNameSpecifierLoc QualifierLoc; 3339 TemplateName TName = SubstDefaultTemplateArgument(*this, Template, 3340 TemplateLoc, 3341 RAngleLoc, 3342 TempTempParm, 3343 Converted, 3344 QualifierLoc); 3345 if (TName.isNull()) 3346 return TemplateArgumentLoc(); 3347 3348 return TemplateArgumentLoc(TemplateArgument(TName), 3349 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(), 3350 TempTempParm->getDefaultArgument().getTemplateNameLoc()); 3351} 3352 3353/// \brief Check that the given template argument corresponds to the given 3354/// template parameter. 3355/// 3356/// \param Param The template parameter against which the argument will be 3357/// checked. 3358/// 3359/// \param Arg The template argument. 3360/// 3361/// \param Template The template in which the template argument resides. 3362/// 3363/// \param TemplateLoc The location of the template name for the template 3364/// whose argument list we're matching. 3365/// 3366/// \param RAngleLoc The location of the right angle bracket ('>') that closes 3367/// the template argument list. 3368/// 3369/// \param ArgumentPackIndex The index into the argument pack where this 3370/// argument will be placed. Only valid if the parameter is a parameter pack. 3371/// 3372/// \param Converted The checked, converted argument will be added to the 3373/// end of this small vector. 3374/// 3375/// \param CTAK Describes how we arrived at this particular template argument: 3376/// explicitly written, deduced, etc. 3377/// 3378/// \returns true on error, false otherwise. 3379bool Sema::CheckTemplateArgument(NamedDecl *Param, 3380 TemplateArgumentLoc &Arg, 3381 NamedDecl *Template, 3382 SourceLocation TemplateLoc, 3383 SourceLocation RAngleLoc, 3384 unsigned ArgumentPackIndex, 3385 SmallVectorImpl<TemplateArgument> &Converted, 3386 CheckTemplateArgumentKind CTAK) { 3387 // Check template type parameters. 3388 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) 3389 return CheckTemplateTypeArgument(TTP, Arg, Converted); 3390 3391 // Check non-type template parameters. 3392 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) { 3393 // Do substitution on the type of the non-type template parameter 3394 // with the template arguments we've seen thus far. But if the 3395 // template has a dependent context then we cannot substitute yet. 3396 QualType NTTPType = NTTP->getType(); 3397 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack()) 3398 NTTPType = NTTP->getExpansionType(ArgumentPackIndex); 3399 3400 if (NTTPType->isDependentType() && 3401 !isa<TemplateTemplateParmDecl>(Template) && 3402 !Template->getDeclContext()->isDependentContext()) { 3403 // Do substitution on the type of the non-type template parameter. 3404 InstantiatingTemplate Inst(*this, TemplateLoc, Template, 3405 NTTP, Converted, 3406 SourceRange(TemplateLoc, RAngleLoc)); 3407 if (Inst.isInvalid()) 3408 return true; 3409 3410 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, 3411 Converted.data(), Converted.size()); 3412 NTTPType = SubstType(NTTPType, 3413 MultiLevelTemplateArgumentList(TemplateArgs), 3414 NTTP->getLocation(), 3415 NTTP->getDeclName()); 3416 // If that worked, check the non-type template parameter type 3417 // for validity. 3418 if (!NTTPType.isNull()) 3419 NTTPType = CheckNonTypeTemplateParameterType(NTTPType, 3420 NTTP->getLocation()); 3421 if (NTTPType.isNull()) 3422 return true; 3423 } 3424 3425 switch (Arg.getArgument().getKind()) { 3426 case TemplateArgument::Null: 3427 llvm_unreachable("Should never see a NULL template argument here"); 3428 3429 case TemplateArgument::Expression: { 3430 TemplateArgument Result; 3431 ExprResult Res = 3432 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(), 3433 Result, CTAK); 3434 if (Res.isInvalid()) 3435 return true; 3436 3437 Converted.push_back(Result); 3438 break; 3439 } 3440 3441 case TemplateArgument::Declaration: 3442 case TemplateArgument::Integral: 3443 case TemplateArgument::NullPtr: 3444 // We've already checked this template argument, so just copy 3445 // it to the list of converted arguments. 3446 Converted.push_back(Arg.getArgument()); 3447 break; 3448 3449 case TemplateArgument::Template: 3450 case TemplateArgument::TemplateExpansion: 3451 // We were given a template template argument. It may not be ill-formed; 3452 // see below. 3453 if (DependentTemplateName *DTN 3454 = Arg.getArgument().getAsTemplateOrTemplatePattern() 3455 .getAsDependentTemplateName()) { 3456 // We have a template argument such as \c T::template X, which we 3457 // parsed as a template template argument. However, since we now 3458 // know that we need a non-type template argument, convert this 3459 // template name into an expression. 3460 3461 DeclarationNameInfo NameInfo(DTN->getIdentifier(), 3462 Arg.getTemplateNameLoc()); 3463 3464 CXXScopeSpec SS; 3465 SS.Adopt(Arg.getTemplateQualifierLoc()); 3466 // FIXME: the template-template arg was a DependentTemplateName, 3467 // so it was provided with a template keyword. However, its source 3468 // location is not stored in the template argument structure. 3469 SourceLocation TemplateKWLoc; 3470 ExprResult E = DependentScopeDeclRefExpr::Create( 3471 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 3472 nullptr); 3473 3474 // If we parsed the template argument as a pack expansion, create a 3475 // pack expansion expression. 3476 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){ 3477 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc()); 3478 if (E.isInvalid()) 3479 return true; 3480 } 3481 3482 TemplateArgument Result; 3483 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result); 3484 if (E.isInvalid()) 3485 return true; 3486 3487 Converted.push_back(Result); 3488 break; 3489 } 3490 3491 // We have a template argument that actually does refer to a class 3492 // template, alias template, or template template parameter, and 3493 // therefore cannot be a non-type template argument. 3494 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr) 3495 << Arg.getSourceRange(); 3496 3497 Diag(Param->getLocation(), diag::note_template_param_here); 3498 return true; 3499 3500 case TemplateArgument::Type: { 3501 // We have a non-type template parameter but the template 3502 // argument is a type. 3503 3504 // C++ [temp.arg]p2: 3505 // In a template-argument, an ambiguity between a type-id and 3506 // an expression is resolved to a type-id, regardless of the 3507 // form of the corresponding template-parameter. 3508 // 3509 // We warn specifically about this case, since it can be rather 3510 // confusing for users. 3511 QualType T = Arg.getArgument().getAsType(); 3512 SourceRange SR = Arg.getSourceRange(); 3513 if (T->isFunctionType()) 3514 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T; 3515 else 3516 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR; 3517 Diag(Param->getLocation(), diag::note_template_param_here); 3518 return true; 3519 } 3520 3521 case TemplateArgument::Pack: 3522 llvm_unreachable("Caller must expand template argument packs"); 3523 } 3524 3525 return false; 3526 } 3527 3528 3529 // Check template template parameters. 3530 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param); 3531 3532 // Substitute into the template parameter list of the template 3533 // template parameter, since previously-supplied template arguments 3534 // may appear within the template template parameter. 3535 { 3536 // Set up a template instantiation context. 3537 LocalInstantiationScope Scope(*this); 3538 InstantiatingTemplate Inst(*this, TemplateLoc, Template, 3539 TempParm, Converted, 3540 SourceRange(TemplateLoc, RAngleLoc)); 3541 if (Inst.isInvalid()) 3542 return true; 3543 3544 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, 3545 Converted.data(), Converted.size()); 3546 TempParm = cast_or_null<TemplateTemplateParmDecl>( 3547 SubstDecl(TempParm, CurContext, 3548 MultiLevelTemplateArgumentList(TemplateArgs))); 3549 if (!TempParm) 3550 return true; 3551 } 3552 3553 switch (Arg.getArgument().getKind()) { 3554 case TemplateArgument::Null: 3555 llvm_unreachable("Should never see a NULL template argument here"); 3556 3557 case TemplateArgument::Template: 3558 case TemplateArgument::TemplateExpansion: 3559 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex)) 3560 return true; 3561 3562 Converted.push_back(Arg.getArgument()); 3563 break; 3564 3565 case TemplateArgument::Expression: 3566 case TemplateArgument::Type: 3567 // We have a template template parameter but the template 3568 // argument does not refer to a template. 3569 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template) 3570 << getLangOpts().CPlusPlus11; 3571 return true; 3572 3573 case TemplateArgument::Declaration: 3574 llvm_unreachable("Declaration argument with template template parameter"); 3575 case TemplateArgument::Integral: 3576 llvm_unreachable("Integral argument with template template parameter"); 3577 case TemplateArgument::NullPtr: 3578 llvm_unreachable("Null pointer argument with template template parameter"); 3579 3580 case TemplateArgument::Pack: 3581 llvm_unreachable("Caller must expand template argument packs"); 3582 } 3583 3584 return false; 3585} 3586 3587/// \brief Diagnose an arity mismatch in the 3588static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template, 3589 SourceLocation TemplateLoc, 3590 TemplateArgumentListInfo &TemplateArgs) { 3591 TemplateParameterList *Params = Template->getTemplateParameters(); 3592 unsigned NumParams = Params->size(); 3593 unsigned NumArgs = TemplateArgs.size(); 3594 3595 SourceRange Range; 3596 if (NumArgs > NumParams) 3597 Range = SourceRange(TemplateArgs[NumParams].getLocation(), 3598 TemplateArgs.getRAngleLoc()); 3599 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity) 3600 << (NumArgs > NumParams) 3601 << (isa<ClassTemplateDecl>(Template)? 0 : 3602 isa<FunctionTemplateDecl>(Template)? 1 : 3603 isa<TemplateTemplateParmDecl>(Template)? 2 : 3) 3604 << Template << Range; 3605 S.Diag(Template->getLocation(), diag::note_template_decl_here) 3606 << Params->getSourceRange(); 3607 return true; 3608} 3609 3610/// \brief Check whether the template parameter is a pack expansion, and if so, 3611/// determine the number of parameters produced by that expansion. For instance: 3612/// 3613/// \code 3614/// template<typename ...Ts> struct A { 3615/// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B; 3616/// }; 3617/// \endcode 3618/// 3619/// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us 3620/// is not a pack expansion, so returns an empty Optional. 3621static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) { 3622 if (NonTypeTemplateParmDecl *NTTP 3623 = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 3624 if (NTTP->isExpandedParameterPack()) 3625 return NTTP->getNumExpansionTypes(); 3626 } 3627 3628 if (TemplateTemplateParmDecl *TTP 3629 = dyn_cast<TemplateTemplateParmDecl>(Param)) { 3630 if (TTP->isExpandedParameterPack()) 3631 return TTP->getNumExpansionTemplateParameters(); 3632 } 3633 3634 return None; 3635} 3636 3637/// \brief Check that the given template argument list is well-formed 3638/// for specializing the given template. 3639bool Sema::CheckTemplateArgumentList(TemplateDecl *Template, 3640 SourceLocation TemplateLoc, 3641 TemplateArgumentListInfo &TemplateArgs, 3642 bool PartialTemplateArgs, 3643 SmallVectorImpl<TemplateArgument> &Converted) { 3644 TemplateParameterList *Params = Template->getTemplateParameters(); 3645 3646 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc(); 3647 3648 // C++ [temp.arg]p1: 3649 // [...] The type and form of each template-argument specified in 3650 // a template-id shall match the type and form specified for the 3651 // corresponding parameter declared by the template in its 3652 // template-parameter-list. 3653 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template); 3654 SmallVector<TemplateArgument, 2> ArgumentPack; 3655 unsigned ArgIdx = 0, NumArgs = TemplateArgs.size(); 3656 LocalInstantiationScope InstScope(*this, true); 3657 for (TemplateParameterList::iterator Param = Params->begin(), 3658 ParamEnd = Params->end(); 3659 Param != ParamEnd; /* increment in loop */) { 3660 // If we have an expanded parameter pack, make sure we don't have too 3661 // many arguments. 3662 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) { 3663 if (*Expansions == ArgumentPack.size()) { 3664 // We're done with this parameter pack. Pack up its arguments and add 3665 // them to the list. 3666 Converted.push_back( 3667 TemplateArgument::CreatePackCopy(Context, 3668 ArgumentPack.data(), 3669 ArgumentPack.size())); 3670 ArgumentPack.clear(); 3671 3672 // This argument is assigned to the next parameter. 3673 ++Param; 3674 continue; 3675 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) { 3676 // Not enough arguments for this parameter pack. 3677 Diag(TemplateLoc, diag::err_template_arg_list_different_arity) 3678 << false 3679 << (isa<ClassTemplateDecl>(Template)? 0 : 3680 isa<FunctionTemplateDecl>(Template)? 1 : 3681 isa<TemplateTemplateParmDecl>(Template)? 2 : 3) 3682 << Template; 3683 Diag(Template->getLocation(), diag::note_template_decl_here) 3684 << Params->getSourceRange(); 3685 return true; 3686 } 3687 } 3688 3689 if (ArgIdx < NumArgs) { 3690 // Check the template argument we were given. 3691 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template, 3692 TemplateLoc, RAngleLoc, 3693 ArgumentPack.size(), Converted)) 3694 return true; 3695 3696 if (TemplateArgs[ArgIdx].getArgument().isPackExpansion() && 3697 isa<TypeAliasTemplateDecl>(Template) && 3698 !(Param + 1 == ParamEnd && (*Param)->isTemplateParameterPack() && 3699 !getExpandedPackSize(*Param))) { 3700 // Core issue 1430: we have a pack expansion as an argument to an 3701 // alias template, and it's not part of a final parameter pack. This 3702 // can't be canonicalized, so reject it now. 3703 Diag(TemplateArgs[ArgIdx].getLocation(), 3704 diag::err_alias_template_expansion_into_fixed_list) 3705 << TemplateArgs[ArgIdx].getSourceRange(); 3706 Diag((*Param)->getLocation(), diag::note_template_param_here); 3707 return true; 3708 } 3709 3710 // We're now done with this argument. 3711 ++ArgIdx; 3712 3713 if ((*Param)->isTemplateParameterPack()) { 3714 // The template parameter was a template parameter pack, so take the 3715 // deduced argument and place it on the argument pack. Note that we 3716 // stay on the same template parameter so that we can deduce more 3717 // arguments. 3718 ArgumentPack.push_back(Converted.pop_back_val()); 3719 } else { 3720 // Move to the next template parameter. 3721 ++Param; 3722 } 3723 3724 // If we just saw a pack expansion, then directly convert the remaining 3725 // arguments, because we don't know what parameters they'll match up 3726 // with. 3727 if (TemplateArgs[ArgIdx-1].getArgument().isPackExpansion()) { 3728 bool InFinalParameterPack = Param != ParamEnd && 3729 Param + 1 == ParamEnd && 3730 (*Param)->isTemplateParameterPack() && 3731 !getExpandedPackSize(*Param); 3732 3733 if (!InFinalParameterPack && !ArgumentPack.empty()) { 3734 // If we were part way through filling in an expanded parameter pack, 3735 // fall back to just producing individual arguments. 3736 Converted.insert(Converted.end(), 3737 ArgumentPack.begin(), ArgumentPack.end()); 3738 ArgumentPack.clear(); 3739 } 3740 3741 while (ArgIdx < NumArgs) { 3742 if (InFinalParameterPack) 3743 ArgumentPack.push_back(TemplateArgs[ArgIdx].getArgument()); 3744 else 3745 Converted.push_back(TemplateArgs[ArgIdx].getArgument()); 3746 ++ArgIdx; 3747 } 3748 3749 // Push the argument pack onto the list of converted arguments. 3750 if (InFinalParameterPack) { 3751 Converted.push_back( 3752 TemplateArgument::CreatePackCopy(Context, 3753 ArgumentPack.data(), 3754 ArgumentPack.size())); 3755 ArgumentPack.clear(); 3756 } 3757 3758 return false; 3759 } 3760 3761 continue; 3762 } 3763 3764 // If we're checking a partial template argument list, we're done. 3765 if (PartialTemplateArgs) { 3766 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty()) 3767 Converted.push_back(TemplateArgument::CreatePackCopy(Context, 3768 ArgumentPack.data(), 3769 ArgumentPack.size())); 3770 3771 return false; 3772 } 3773 3774 // If we have a template parameter pack with no more corresponding 3775 // arguments, just break out now and we'll fill in the argument pack below. 3776 if ((*Param)->isTemplateParameterPack()) { 3777 assert(!getExpandedPackSize(*Param) && 3778 "Should have dealt with this already"); 3779 3780 // A non-expanded parameter pack before the end of the parameter list 3781 // only occurs for an ill-formed template parameter list, unless we've 3782 // got a partial argument list for a function template, so just bail out. 3783 if (Param + 1 != ParamEnd) 3784 return true; 3785 3786 Converted.push_back(TemplateArgument::CreatePackCopy(Context, 3787 ArgumentPack.data(), 3788 ArgumentPack.size())); 3789 ArgumentPack.clear(); 3790 3791 ++Param; 3792 continue; 3793 } 3794 3795 // Check whether we have a default argument. 3796 TemplateArgumentLoc Arg; 3797 3798 // Retrieve the default template argument from the template 3799 // parameter. For each kind of template parameter, we substitute the 3800 // template arguments provided thus far and any "outer" template arguments 3801 // (when the template parameter was part of a nested template) into 3802 // the default argument. 3803 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) { 3804 if (!TTP->hasDefaultArgument()) 3805 return diagnoseArityMismatch(*this, Template, TemplateLoc, 3806 TemplateArgs); 3807 3808 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this, 3809 Template, 3810 TemplateLoc, 3811 RAngleLoc, 3812 TTP, 3813 Converted); 3814 if (!ArgType) 3815 return true; 3816 3817 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()), 3818 ArgType); 3819 } else if (NonTypeTemplateParmDecl *NTTP 3820 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) { 3821 if (!NTTP->hasDefaultArgument()) 3822 return diagnoseArityMismatch(*this, Template, TemplateLoc, 3823 TemplateArgs); 3824 3825 ExprResult E = SubstDefaultTemplateArgument(*this, Template, 3826 TemplateLoc, 3827 RAngleLoc, 3828 NTTP, 3829 Converted); 3830 if (E.isInvalid()) 3831 return true; 3832 3833 Expr *Ex = E.getAs<Expr>(); 3834 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex); 3835 } else { 3836 TemplateTemplateParmDecl *TempParm 3837 = cast<TemplateTemplateParmDecl>(*Param); 3838 3839 if (!TempParm->hasDefaultArgument()) 3840 return diagnoseArityMismatch(*this, Template, TemplateLoc, 3841 TemplateArgs); 3842 3843 NestedNameSpecifierLoc QualifierLoc; 3844 TemplateName Name = SubstDefaultTemplateArgument(*this, Template, 3845 TemplateLoc, 3846 RAngleLoc, 3847 TempParm, 3848 Converted, 3849 QualifierLoc); 3850 if (Name.isNull()) 3851 return true; 3852 3853 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc, 3854 TempParm->getDefaultArgument().getTemplateNameLoc()); 3855 } 3856 3857 // Introduce an instantiation record that describes where we are using 3858 // the default template argument. 3859 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted, 3860 SourceRange(TemplateLoc, RAngleLoc)); 3861 if (Inst.isInvalid()) 3862 return true; 3863 3864 // Check the default template argument. 3865 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, 3866 RAngleLoc, 0, Converted)) 3867 return true; 3868 3869 // Core issue 150 (assumed resolution): if this is a template template 3870 // parameter, keep track of the default template arguments from the 3871 // template definition. 3872 if (isTemplateTemplateParameter) 3873 TemplateArgs.addArgument(Arg); 3874 3875 // Move to the next template parameter and argument. 3876 ++Param; 3877 ++ArgIdx; 3878 } 3879 3880 // If we're performing a partial argument substitution, allow any trailing 3881 // pack expansions; they might be empty. This can happen even if 3882 // PartialTemplateArgs is false (the list of arguments is complete but 3883 // still dependent). 3884 if (ArgIdx < NumArgs && CurrentInstantiationScope && 3885 CurrentInstantiationScope->getPartiallySubstitutedPack()) { 3886 while (ArgIdx < NumArgs && 3887 TemplateArgs[ArgIdx].getArgument().isPackExpansion()) 3888 Converted.push_back(TemplateArgs[ArgIdx++].getArgument()); 3889 } 3890 3891 // If we have any leftover arguments, then there were too many arguments. 3892 // Complain and fail. 3893 if (ArgIdx < NumArgs) 3894 return diagnoseArityMismatch(*this, Template, TemplateLoc, TemplateArgs); 3895 3896 return false; 3897} 3898 3899namespace { 3900 class UnnamedLocalNoLinkageFinder 3901 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool> 3902 { 3903 Sema &S; 3904 SourceRange SR; 3905 3906 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited; 3907 3908 public: 3909 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { } 3910 3911 bool Visit(QualType T) { 3912 return inherited::Visit(T.getTypePtr()); 3913 } 3914 3915#define TYPE(Class, Parent) \ 3916 bool Visit##Class##Type(const Class##Type *); 3917#define ABSTRACT_TYPE(Class, Parent) \ 3918 bool Visit##Class##Type(const Class##Type *) { return false; } 3919#define NON_CANONICAL_TYPE(Class, Parent) \ 3920 bool Visit##Class##Type(const Class##Type *) { return false; } 3921#include "clang/AST/TypeNodes.def" 3922 3923 bool VisitTagDecl(const TagDecl *Tag); 3924 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS); 3925 }; 3926} 3927 3928bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) { 3929 return false; 3930} 3931 3932bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) { 3933 return Visit(T->getElementType()); 3934} 3935 3936bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) { 3937 return Visit(T->getPointeeType()); 3938} 3939 3940bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType( 3941 const BlockPointerType* T) { 3942 return Visit(T->getPointeeType()); 3943} 3944 3945bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType( 3946 const LValueReferenceType* T) { 3947 return Visit(T->getPointeeType()); 3948} 3949 3950bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType( 3951 const RValueReferenceType* T) { 3952 return Visit(T->getPointeeType()); 3953} 3954 3955bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType( 3956 const MemberPointerType* T) { 3957 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0)); 3958} 3959 3960bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType( 3961 const ConstantArrayType* T) { 3962 return Visit(T->getElementType()); 3963} 3964 3965bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType( 3966 const IncompleteArrayType* T) { 3967 return Visit(T->getElementType()); 3968} 3969 3970bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType( 3971 const VariableArrayType* T) { 3972 return Visit(T->getElementType()); 3973} 3974 3975bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType( 3976 const DependentSizedArrayType* T) { 3977 return Visit(T->getElementType()); 3978} 3979 3980bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType( 3981 const DependentSizedExtVectorType* T) { 3982 return Visit(T->getElementType()); 3983} 3984 3985bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) { 3986 return Visit(T->getElementType()); 3987} 3988 3989bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) { 3990 return Visit(T->getElementType()); 3991} 3992 3993bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType( 3994 const FunctionProtoType* T) { 3995 for (const auto &A : T->param_types()) { 3996 if (Visit(A)) 3997 return true; 3998 } 3999 4000 return Visit(T->getReturnType()); 4001} 4002 4003bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType( 4004 const FunctionNoProtoType* T) { 4005 return Visit(T->getReturnType()); 4006} 4007 4008bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType( 4009 const UnresolvedUsingType*) { 4010 return false; 4011} 4012 4013bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) { 4014 return false; 4015} 4016 4017bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) { 4018 return Visit(T->getUnderlyingType()); 4019} 4020 4021bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) { 4022 return false; 4023} 4024 4025bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType( 4026 const UnaryTransformType*) { 4027 return false; 4028} 4029 4030bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) { 4031 return Visit(T->getDeducedType()); 4032} 4033 4034bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) { 4035 return VisitTagDecl(T->getDecl()); 4036} 4037 4038bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) { 4039 return VisitTagDecl(T->getDecl()); 4040} 4041 4042bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType( 4043 const TemplateTypeParmType*) { 4044 return false; 4045} 4046 4047bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType( 4048 const SubstTemplateTypeParmPackType *) { 4049 return false; 4050} 4051 4052bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType( 4053 const TemplateSpecializationType*) { 4054 return false; 4055} 4056 4057bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType( 4058 const InjectedClassNameType* T) { 4059 return VisitTagDecl(T->getDecl()); 4060} 4061 4062bool UnnamedLocalNoLinkageFinder::VisitDependentNameType( 4063 const DependentNameType* T) { 4064 return VisitNestedNameSpecifier(T->getQualifier()); 4065} 4066 4067bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType( 4068 const DependentTemplateSpecializationType* T) { 4069 return VisitNestedNameSpecifier(T->getQualifier()); 4070} 4071 4072bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType( 4073 const PackExpansionType* T) { 4074 return Visit(T->getPattern()); 4075} 4076 4077bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) { 4078 return false; 4079} 4080 4081bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType( 4082 const ObjCInterfaceType *) { 4083 return false; 4084} 4085 4086bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType( 4087 const ObjCObjectPointerType *) { 4088 return false; 4089} 4090 4091bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) { 4092 return Visit(T->getValueType()); 4093} 4094 4095bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) { 4096 if (Tag->getDeclContext()->isFunctionOrMethod()) { 4097 S.Diag(SR.getBegin(), 4098 S.getLangOpts().CPlusPlus11 ? 4099 diag::warn_cxx98_compat_template_arg_local_type : 4100 diag::ext_template_arg_local_type) 4101 << S.Context.getTypeDeclType(Tag) << SR; 4102 return true; 4103 } 4104 4105 if (!Tag->hasNameForLinkage()) { 4106 S.Diag(SR.getBegin(), 4107 S.getLangOpts().CPlusPlus11 ? 4108 diag::warn_cxx98_compat_template_arg_unnamed_type : 4109 diag::ext_template_arg_unnamed_type) << SR; 4110 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here); 4111 return true; 4112 } 4113 4114 return false; 4115} 4116 4117bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier( 4118 NestedNameSpecifier *NNS) { 4119 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix())) 4120 return true; 4121 4122 switch (NNS->getKind()) { 4123 case NestedNameSpecifier::Identifier: 4124 case NestedNameSpecifier::Namespace: 4125 case NestedNameSpecifier::NamespaceAlias: 4126 case NestedNameSpecifier::Global: 4127 return false; 4128 4129 case NestedNameSpecifier::TypeSpec: 4130 case NestedNameSpecifier::TypeSpecWithTemplate: 4131 return Visit(QualType(NNS->getAsType(), 0)); 4132 } 4133 llvm_unreachable("Invalid NestedNameSpecifier::Kind!"); 4134} 4135 4136 4137/// \brief Check a template argument against its corresponding 4138/// template type parameter. 4139/// 4140/// This routine implements the semantics of C++ [temp.arg.type]. It 4141/// returns true if an error occurred, and false otherwise. 4142bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param, 4143 TypeSourceInfo *ArgInfo) { 4144 assert(ArgInfo && "invalid TypeSourceInfo"); 4145 QualType Arg = ArgInfo->getType(); 4146 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange(); 4147 4148 if (Arg->isVariablyModifiedType()) { 4149 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg; 4150 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) { 4151 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR; 4152 } 4153 4154 // C++03 [temp.arg.type]p2: 4155 // A local type, a type with no linkage, an unnamed type or a type 4156 // compounded from any of these types shall not be used as a 4157 // template-argument for a template type-parameter. 4158 // 4159 // C++11 allows these, and even in C++03 we allow them as an extension with 4160 // a warning. 4161 bool NeedsCheck; 4162 if (LangOpts.CPlusPlus11) 4163 NeedsCheck = 4164 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_unnamed_type, 4165 SR.getBegin()) || 4166 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_local_type, 4167 SR.getBegin()); 4168 else 4169 NeedsCheck = Arg->hasUnnamedOrLocalType(); 4170 4171 if (NeedsCheck) { 4172 UnnamedLocalNoLinkageFinder Finder(*this, SR); 4173 (void)Finder.Visit(Context.getCanonicalType(Arg)); 4174 } 4175 4176 return false; 4177} 4178 4179enum NullPointerValueKind { 4180 NPV_NotNullPointer, 4181 NPV_NullPointer, 4182 NPV_Error 4183}; 4184 4185/// \brief Determine whether the given template argument is a null pointer 4186/// value of the appropriate type. 4187static NullPointerValueKind 4188isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param, 4189 QualType ParamType, Expr *Arg) { 4190 if (Arg->isValueDependent() || Arg->isTypeDependent()) 4191 return NPV_NotNullPointer; 4192 4193 if (!S.getLangOpts().CPlusPlus11 || S.getLangOpts().MSVCCompat) 4194 return NPV_NotNullPointer; 4195 4196 // Determine whether we have a constant expression. 4197 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg); 4198 if (ArgRV.isInvalid()) 4199 return NPV_Error; 4200 Arg = ArgRV.get(); 4201 4202 Expr::EvalResult EvalResult; 4203 SmallVector<PartialDiagnosticAt, 8> Notes; 4204 EvalResult.Diag = &Notes; 4205 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) || 4206 EvalResult.HasSideEffects) { 4207 SourceLocation DiagLoc = Arg->getExprLoc(); 4208 4209 // If our only note is the usual "invalid subexpression" note, just point 4210 // the caret at its location rather than producing an essentially 4211 // redundant note. 4212 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 4213 diag::note_invalid_subexpr_in_const_expr) { 4214 DiagLoc = Notes[0].first; 4215 Notes.clear(); 4216 } 4217 4218 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant) 4219 << Arg->getType() << Arg->getSourceRange(); 4220 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 4221 S.Diag(Notes[I].first, Notes[I].second); 4222 4223 S.Diag(Param->getLocation(), diag::note_template_param_here); 4224 return NPV_Error; 4225 } 4226 4227 // C++11 [temp.arg.nontype]p1: 4228 // - an address constant expression of type std::nullptr_t 4229 if (Arg->getType()->isNullPtrType()) 4230 return NPV_NullPointer; 4231 4232 // - a constant expression that evaluates to a null pointer value (4.10); or 4233 // - a constant expression that evaluates to a null member pointer value 4234 // (4.11); or 4235 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) || 4236 (EvalResult.Val.isMemberPointer() && 4237 !EvalResult.Val.getMemberPointerDecl())) { 4238 // If our expression has an appropriate type, we've succeeded. 4239 bool ObjCLifetimeConversion; 4240 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) || 4241 S.IsQualificationConversion(Arg->getType(), ParamType, false, 4242 ObjCLifetimeConversion)) 4243 return NPV_NullPointer; 4244 4245 // The types didn't match, but we know we got a null pointer; complain, 4246 // then recover as if the types were correct. 4247 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant) 4248 << Arg->getType() << ParamType << Arg->getSourceRange(); 4249 S.Diag(Param->getLocation(), diag::note_template_param_here); 4250 return NPV_NullPointer; 4251 } 4252 4253 // If we don't have a null pointer value, but we do have a NULL pointer 4254 // constant, suggest a cast to the appropriate type. 4255 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) { 4256 std::string Code = "static_cast<" + ParamType.getAsString() + ">("; 4257 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant) 4258 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code) 4259 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()), 4260 ")"); 4261 S.Diag(Param->getLocation(), diag::note_template_param_here); 4262 return NPV_NullPointer; 4263 } 4264 4265 // FIXME: If we ever want to support general, address-constant expressions 4266 // as non-type template arguments, we should return the ExprResult here to 4267 // be interpreted by the caller. 4268 return NPV_NotNullPointer; 4269} 4270 4271/// \brief Checks whether the given template argument is compatible with its 4272/// template parameter. 4273static bool CheckTemplateArgumentIsCompatibleWithParameter( 4274 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn, 4275 Expr *Arg, QualType ArgType) { 4276 bool ObjCLifetimeConversion; 4277 if (ParamType->isPointerType() && 4278 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() && 4279 S.IsQualificationConversion(ArgType, ParamType, false, 4280 ObjCLifetimeConversion)) { 4281 // For pointer-to-object types, qualification conversions are 4282 // permitted. 4283 } else { 4284 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) { 4285 if (!ParamRef->getPointeeType()->isFunctionType()) { 4286 // C++ [temp.arg.nontype]p5b3: 4287 // For a non-type template-parameter of type reference to 4288 // object, no conversions apply. The type referred to by the 4289 // reference may be more cv-qualified than the (otherwise 4290 // identical) type of the template- argument. The 4291 // template-parameter is bound directly to the 4292 // template-argument, which shall be an lvalue. 4293 4294 // FIXME: Other qualifiers? 4295 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers(); 4296 unsigned ArgQuals = ArgType.getCVRQualifiers(); 4297 4298 if ((ParamQuals | ArgQuals) != ParamQuals) { 4299 S.Diag(Arg->getLocStart(), 4300 diag::err_template_arg_ref_bind_ignores_quals) 4301 << ParamType << Arg->getType() << Arg->getSourceRange(); 4302 S.Diag(Param->getLocation(), diag::note_template_param_here); 4303 return true; 4304 } 4305 } 4306 } 4307 4308 // At this point, the template argument refers to an object or 4309 // function with external linkage. We now need to check whether the 4310 // argument and parameter types are compatible. 4311 if (!S.Context.hasSameUnqualifiedType(ArgType, 4312 ParamType.getNonReferenceType())) { 4313 // We can't perform this conversion or binding. 4314 if (ParamType->isReferenceType()) 4315 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind) 4316 << ParamType << ArgIn->getType() << Arg->getSourceRange(); 4317 else 4318 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible) 4319 << ArgIn->getType() << ParamType << Arg->getSourceRange(); 4320 S.Diag(Param->getLocation(), diag::note_template_param_here); 4321 return true; 4322 } 4323 } 4324 4325 return false; 4326} 4327 4328/// \brief Checks whether the given template argument is the address 4329/// of an object or function according to C++ [temp.arg.nontype]p1. 4330static bool 4331CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S, 4332 NonTypeTemplateParmDecl *Param, 4333 QualType ParamType, 4334 Expr *ArgIn, 4335 TemplateArgument &Converted) { 4336 bool Invalid = false; 4337 Expr *Arg = ArgIn; 4338 QualType ArgType = Arg->getType(); 4339 4340 bool AddressTaken = false; 4341 SourceLocation AddrOpLoc; 4342 if (S.getLangOpts().MicrosoftExt) { 4343 // Microsoft Visual C++ strips all casts, allows an arbitrary number of 4344 // dereference and address-of operators. 4345 Arg = Arg->IgnoreParenCasts(); 4346 4347 bool ExtWarnMSTemplateArg = false; 4348 UnaryOperatorKind FirstOpKind; 4349 SourceLocation FirstOpLoc; 4350 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) { 4351 UnaryOperatorKind UnOpKind = UnOp->getOpcode(); 4352 if (UnOpKind == UO_Deref) 4353 ExtWarnMSTemplateArg = true; 4354 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) { 4355 Arg = UnOp->getSubExpr()->IgnoreParenCasts(); 4356 if (!AddrOpLoc.isValid()) { 4357 FirstOpKind = UnOpKind; 4358 FirstOpLoc = UnOp->getOperatorLoc(); 4359 } 4360 } else 4361 break; 4362 } 4363 if (FirstOpLoc.isValid()) { 4364 if (ExtWarnMSTemplateArg) 4365 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument) 4366 << ArgIn->getSourceRange(); 4367 4368 if (FirstOpKind == UO_AddrOf) 4369 AddressTaken = true; 4370 else if (Arg->getType()->isPointerType()) { 4371 // We cannot let pointers get dereferenced here, that is obviously not a 4372 // constant expression. 4373 assert(FirstOpKind == UO_Deref); 4374 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref) 4375 << Arg->getSourceRange(); 4376 } 4377 } 4378 } else { 4379 // See through any implicit casts we added to fix the type. 4380 Arg = Arg->IgnoreImpCasts(); 4381 4382 // C++ [temp.arg.nontype]p1: 4383 // 4384 // A template-argument for a non-type, non-template 4385 // template-parameter shall be one of: [...] 4386 // 4387 // -- the address of an object or function with external 4388 // linkage, including function templates and function 4389 // template-ids but excluding non-static class members, 4390 // expressed as & id-expression where the & is optional if 4391 // the name refers to a function or array, or if the 4392 // corresponding template-parameter is a reference; or 4393 4394 // In C++98/03 mode, give an extension warning on any extra parentheses. 4395 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773 4396 bool ExtraParens = false; 4397 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) { 4398 if (!Invalid && !ExtraParens) { 4399 S.Diag(Arg->getLocStart(), 4400 S.getLangOpts().CPlusPlus11 4401 ? diag::warn_cxx98_compat_template_arg_extra_parens 4402 : diag::ext_template_arg_extra_parens) 4403 << Arg->getSourceRange(); 4404 ExtraParens = true; 4405 } 4406 4407 Arg = Parens->getSubExpr(); 4408 } 4409 4410 while (SubstNonTypeTemplateParmExpr *subst = 4411 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg)) 4412 Arg = subst->getReplacement()->IgnoreImpCasts(); 4413 4414 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) { 4415 if (UnOp->getOpcode() == UO_AddrOf) { 4416 Arg = UnOp->getSubExpr(); 4417 AddressTaken = true; 4418 AddrOpLoc = UnOp->getOperatorLoc(); 4419 } 4420 } 4421 4422 while (SubstNonTypeTemplateParmExpr *subst = 4423 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg)) 4424 Arg = subst->getReplacement()->IgnoreImpCasts(); 4425 } 4426 4427 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg); 4428 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr; 4429 4430 // If our parameter has pointer type, check for a null template value. 4431 if (ParamType->isPointerType() || ParamType->isNullPtrType()) { 4432 NullPointerValueKind NPV; 4433 // dllimport'd entities aren't constant but are available inside of template 4434 // arguments. 4435 if (Entity && Entity->hasAttr<DLLImportAttr>()) 4436 NPV = NPV_NotNullPointer; 4437 else 4438 NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn); 4439 switch (NPV) { 4440 case NPV_NullPointer: 4441 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null); 4442 Converted = TemplateArgument(ParamType, /*isNullPtr=*/true); 4443 return false; 4444 4445 case NPV_Error: 4446 return true; 4447 4448 case NPV_NotNullPointer: 4449 break; 4450 } 4451 } 4452 4453 // Stop checking the precise nature of the argument if it is value dependent, 4454 // it should be checked when instantiated. 4455 if (Arg->isValueDependent()) { 4456 Converted = TemplateArgument(ArgIn); 4457 return false; 4458 } 4459 4460 if (isa<CXXUuidofExpr>(Arg)) { 4461 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, 4462 ArgIn, Arg, ArgType)) 4463 return true; 4464 4465 Converted = TemplateArgument(ArgIn); 4466 return false; 4467 } 4468 4469 if (!DRE) { 4470 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref) 4471 << Arg->getSourceRange(); 4472 S.Diag(Param->getLocation(), diag::note_template_param_here); 4473 return true; 4474 } 4475 4476 // Cannot refer to non-static data members 4477 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) { 4478 S.Diag(Arg->getLocStart(), diag::err_template_arg_field) 4479 << Entity << Arg->getSourceRange(); 4480 S.Diag(Param->getLocation(), diag::note_template_param_here); 4481 return true; 4482 } 4483 4484 // Cannot refer to non-static member functions 4485 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) { 4486 if (!Method->isStatic()) { 4487 S.Diag(Arg->getLocStart(), diag::err_template_arg_method) 4488 << Method << Arg->getSourceRange(); 4489 S.Diag(Param->getLocation(), diag::note_template_param_here); 4490 return true; 4491 } 4492 } 4493 4494 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity); 4495 VarDecl *Var = dyn_cast<VarDecl>(Entity); 4496 4497 // A non-type template argument must refer to an object or function. 4498 if (!Func && !Var) { 4499 // We found something, but we don't know specifically what it is. 4500 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func) 4501 << Arg->getSourceRange(); 4502 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here); 4503 return true; 4504 } 4505 4506 // Address / reference template args must have external linkage in C++98. 4507 if (Entity->getFormalLinkage() == InternalLinkage) { 4508 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ? 4509 diag::warn_cxx98_compat_template_arg_object_internal : 4510 diag::ext_template_arg_object_internal) 4511 << !Func << Entity << Arg->getSourceRange(); 4512 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object) 4513 << !Func; 4514 } else if (!Entity->hasLinkage()) { 4515 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage) 4516 << !Func << Entity << Arg->getSourceRange(); 4517 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object) 4518 << !Func; 4519 return true; 4520 } 4521 4522 if (Func) { 4523 // If the template parameter has pointer type, the function decays. 4524 if (ParamType->isPointerType() && !AddressTaken) 4525 ArgType = S.Context.getPointerType(Func->getType()); 4526 else if (AddressTaken && ParamType->isReferenceType()) { 4527 // If we originally had an address-of operator, but the 4528 // parameter has reference type, complain and (if things look 4529 // like they will work) drop the address-of operator. 4530 if (!S.Context.hasSameUnqualifiedType(Func->getType(), 4531 ParamType.getNonReferenceType())) { 4532 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer) 4533 << ParamType; 4534 S.Diag(Param->getLocation(), diag::note_template_param_here); 4535 return true; 4536 } 4537 4538 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer) 4539 << ParamType 4540 << FixItHint::CreateRemoval(AddrOpLoc); 4541 S.Diag(Param->getLocation(), diag::note_template_param_here); 4542 4543 ArgType = Func->getType(); 4544 } 4545 } else { 4546 // A value of reference type is not an object. 4547 if (Var->getType()->isReferenceType()) { 4548 S.Diag(Arg->getLocStart(), 4549 diag::err_template_arg_reference_var) 4550 << Var->getType() << Arg->getSourceRange(); 4551 S.Diag(Param->getLocation(), diag::note_template_param_here); 4552 return true; 4553 } 4554 4555 // A template argument must have static storage duration. 4556 if (Var->getTLSKind()) { 4557 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local) 4558 << Arg->getSourceRange(); 4559 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here); 4560 return true; 4561 } 4562 4563 // If the template parameter has pointer type, we must have taken 4564 // the address of this object. 4565 if (ParamType->isReferenceType()) { 4566 if (AddressTaken) { 4567 // If we originally had an address-of operator, but the 4568 // parameter has reference type, complain and (if things look 4569 // like they will work) drop the address-of operator. 4570 if (!S.Context.hasSameUnqualifiedType(Var->getType(), 4571 ParamType.getNonReferenceType())) { 4572 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer) 4573 << ParamType; 4574 S.Diag(Param->getLocation(), diag::note_template_param_here); 4575 return true; 4576 } 4577 4578 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer) 4579 << ParamType 4580 << FixItHint::CreateRemoval(AddrOpLoc); 4581 S.Diag(Param->getLocation(), diag::note_template_param_here); 4582 4583 ArgType = Var->getType(); 4584 } 4585 } else if (!AddressTaken && ParamType->isPointerType()) { 4586 if (Var->getType()->isArrayType()) { 4587 // Array-to-pointer decay. 4588 ArgType = S.Context.getArrayDecayedType(Var->getType()); 4589 } else { 4590 // If the template parameter has pointer type but the address of 4591 // this object was not taken, complain and (possibly) recover by 4592 // taking the address of the entity. 4593 ArgType = S.Context.getPointerType(Var->getType()); 4594 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) { 4595 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of) 4596 << ParamType; 4597 S.Diag(Param->getLocation(), diag::note_template_param_here); 4598 return true; 4599 } 4600 4601 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of) 4602 << ParamType 4603 << FixItHint::CreateInsertion(Arg->getLocStart(), "&"); 4604 4605 S.Diag(Param->getLocation(), diag::note_template_param_here); 4606 } 4607 } 4608 } 4609 4610 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn, 4611 Arg, ArgType)) 4612 return true; 4613 4614 // Create the template argument. 4615 Converted = TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), 4616 ParamType->isReferenceType()); 4617 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false); 4618 return false; 4619} 4620 4621/// \brief Checks whether the given template argument is a pointer to 4622/// member constant according to C++ [temp.arg.nontype]p1. 4623static bool CheckTemplateArgumentPointerToMember(Sema &S, 4624 NonTypeTemplateParmDecl *Param, 4625 QualType ParamType, 4626 Expr *&ResultArg, 4627 TemplateArgument &Converted) { 4628 bool Invalid = false; 4629 4630 // Check for a null pointer value. 4631 Expr *Arg = ResultArg; 4632 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) { 4633 case NPV_Error: 4634 return true; 4635 case NPV_NullPointer: 4636 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null); 4637 Converted = TemplateArgument(ParamType, /*isNullPtr*/true); 4638 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) 4639 S.RequireCompleteType(Arg->getExprLoc(), ParamType, 0); 4640 return false; 4641 case NPV_NotNullPointer: 4642 break; 4643 } 4644 4645 bool ObjCLifetimeConversion; 4646 if (S.IsQualificationConversion(Arg->getType(), 4647 ParamType.getNonReferenceType(), 4648 false, ObjCLifetimeConversion)) { 4649 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp, 4650 Arg->getValueKind()).get(); 4651 ResultArg = Arg; 4652 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(), 4653 ParamType.getNonReferenceType())) { 4654 // We can't perform this conversion. 4655 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible) 4656 << Arg->getType() << ParamType << Arg->getSourceRange(); 4657 S.Diag(Param->getLocation(), diag::note_template_param_here); 4658 return true; 4659 } 4660 4661 // See through any implicit casts we added to fix the type. 4662 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg)) 4663 Arg = Cast->getSubExpr(); 4664 4665 // C++ [temp.arg.nontype]p1: 4666 // 4667 // A template-argument for a non-type, non-template 4668 // template-parameter shall be one of: [...] 4669 // 4670 // -- a pointer to member expressed as described in 5.3.1. 4671 DeclRefExpr *DRE = nullptr; 4672 4673 // In C++98/03 mode, give an extension warning on any extra parentheses. 4674 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773 4675 bool ExtraParens = false; 4676 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) { 4677 if (!Invalid && !ExtraParens) { 4678 S.Diag(Arg->getLocStart(), 4679 S.getLangOpts().CPlusPlus11 ? 4680 diag::warn_cxx98_compat_template_arg_extra_parens : 4681 diag::ext_template_arg_extra_parens) 4682 << Arg->getSourceRange(); 4683 ExtraParens = true; 4684 } 4685 4686 Arg = Parens->getSubExpr(); 4687 } 4688 4689 while (SubstNonTypeTemplateParmExpr *subst = 4690 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg)) 4691 Arg = subst->getReplacement()->IgnoreImpCasts(); 4692 4693 // A pointer-to-member constant written &Class::member. 4694 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) { 4695 if (UnOp->getOpcode() == UO_AddrOf) { 4696 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr()); 4697 if (DRE && !DRE->getQualifier()) 4698 DRE = nullptr; 4699 } 4700 } 4701 // A constant of pointer-to-member type. 4702 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) { 4703 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) { 4704 if (VD->getType()->isMemberPointerType()) { 4705 if (isa<NonTypeTemplateParmDecl>(VD)) { 4706 if (Arg->isTypeDependent() || Arg->isValueDependent()) { 4707 Converted = TemplateArgument(Arg); 4708 } else { 4709 VD = cast<ValueDecl>(VD->getCanonicalDecl()); 4710 Converted = TemplateArgument(VD, /*isReferenceParam*/false); 4711 } 4712 return Invalid; 4713 } 4714 } 4715 } 4716 4717 DRE = nullptr; 4718 } 4719 4720 if (!DRE) 4721 return S.Diag(Arg->getLocStart(), 4722 diag::err_template_arg_not_pointer_to_member_form) 4723 << Arg->getSourceRange(); 4724 4725 if (isa<FieldDecl>(DRE->getDecl()) || 4726 isa<IndirectFieldDecl>(DRE->getDecl()) || 4727 isa<CXXMethodDecl>(DRE->getDecl())) { 4728 assert((isa<FieldDecl>(DRE->getDecl()) || 4729 isa<IndirectFieldDecl>(DRE->getDecl()) || 4730 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) && 4731 "Only non-static member pointers can make it here"); 4732 4733 // Okay: this is the address of a non-static member, and therefore 4734 // a member pointer constant. 4735 if (Arg->isTypeDependent() || Arg->isValueDependent()) { 4736 Converted = TemplateArgument(Arg); 4737 } else { 4738 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl()); 4739 Converted = TemplateArgument(D, /*isReferenceParam*/false); 4740 } 4741 return Invalid; 4742 } 4743 4744 // We found something else, but we don't know specifically what it is. 4745 S.Diag(Arg->getLocStart(), 4746 diag::err_template_arg_not_pointer_to_member_form) 4747 << Arg->getSourceRange(); 4748 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here); 4749 return true; 4750} 4751 4752/// \brief Check a template argument against its corresponding 4753/// non-type template parameter. 4754/// 4755/// This routine implements the semantics of C++ [temp.arg.nontype]. 4756/// If an error occurred, it returns ExprError(); otherwise, it 4757/// returns the converted template argument. \p 4758/// InstantiatedParamType is the type of the non-type template 4759/// parameter after it has been instantiated. 4760ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param, 4761 QualType InstantiatedParamType, Expr *Arg, 4762 TemplateArgument &Converted, 4763 CheckTemplateArgumentKind CTAK) { 4764 SourceLocation StartLoc = Arg->getLocStart(); 4765 4766 // If either the parameter has a dependent type or the argument is 4767 // type-dependent, there's nothing we can check now. 4768 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) { 4769 // FIXME: Produce a cloned, canonical expression? 4770 Converted = TemplateArgument(Arg); 4771 return Arg; 4772 } 4773 4774 // C++ [temp.arg.nontype]p5: 4775 // The following conversions are performed on each expression used 4776 // as a non-type template-argument. If a non-type 4777 // template-argument cannot be converted to the type of the 4778 // corresponding template-parameter then the program is 4779 // ill-formed. 4780 QualType ParamType = InstantiatedParamType; 4781 if (ParamType->isIntegralOrEnumerationType()) { 4782 // C++11: 4783 // -- for a non-type template-parameter of integral or 4784 // enumeration type, conversions permitted in a converted 4785 // constant expression are applied. 4786 // 4787 // C++98: 4788 // -- for a non-type template-parameter of integral or 4789 // enumeration type, integral promotions (4.5) and integral 4790 // conversions (4.7) are applied. 4791 4792 if (CTAK == CTAK_Deduced && 4793 !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) { 4794 // C++ [temp.deduct.type]p17: 4795 // If, in the declaration of a function template with a non-type 4796 // template-parameter, the non-type template-parameter is used 4797 // in an expression in the function parameter-list and, if the 4798 // corresponding template-argument is deduced, the 4799 // template-argument type shall match the type of the 4800 // template-parameter exactly, except that a template-argument 4801 // deduced from an array bound may be of any integral type. 4802 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch) 4803 << Arg->getType().getUnqualifiedType() 4804 << ParamType.getUnqualifiedType(); 4805 Diag(Param->getLocation(), diag::note_template_param_here); 4806 return ExprError(); 4807 } 4808 4809 if (getLangOpts().CPlusPlus11) { 4810 // We can't check arbitrary value-dependent arguments. 4811 // FIXME: If there's no viable conversion to the template parameter type, 4812 // we should be able to diagnose that prior to instantiation. 4813 if (Arg->isValueDependent()) { 4814 Converted = TemplateArgument(Arg); 4815 return Arg; 4816 } 4817 4818 // C++ [temp.arg.nontype]p1: 4819 // A template-argument for a non-type, non-template template-parameter 4820 // shall be one of: 4821 // 4822 // -- for a non-type template-parameter of integral or enumeration 4823 // type, a converted constant expression of the type of the 4824 // template-parameter; or 4825 llvm::APSInt Value; 4826 ExprResult ArgResult = 4827 CheckConvertedConstantExpression(Arg, ParamType, Value, 4828 CCEK_TemplateArg); 4829 if (ArgResult.isInvalid()) 4830 return ExprError(); 4831 4832 // Widen the argument value to sizeof(parameter type). This is almost 4833 // always a no-op, except when the parameter type is bool. In 4834 // that case, this may extend the argument from 1 bit to 8 bits. 4835 QualType IntegerType = ParamType; 4836 if (const EnumType *Enum = IntegerType->getAs<EnumType>()) 4837 IntegerType = Enum->getDecl()->getIntegerType(); 4838 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType)); 4839 4840 Converted = TemplateArgument(Context, Value, 4841 Context.getCanonicalType(ParamType)); 4842 return ArgResult; 4843 } 4844 4845 ExprResult ArgResult = DefaultLvalueConversion(Arg); 4846 if (ArgResult.isInvalid()) 4847 return ExprError(); 4848 Arg = ArgResult.get(); 4849 4850 QualType ArgType = Arg->getType(); 4851 4852 // C++ [temp.arg.nontype]p1: 4853 // A template-argument for a non-type, non-template 4854 // template-parameter shall be one of: 4855 // 4856 // -- an integral constant-expression of integral or enumeration 4857 // type; or 4858 // -- the name of a non-type template-parameter; or 4859 SourceLocation NonConstantLoc; 4860 llvm::APSInt Value; 4861 if (!ArgType->isIntegralOrEnumerationType()) { 4862 Diag(Arg->getLocStart(), 4863 diag::err_template_arg_not_integral_or_enumeral) 4864 << ArgType << Arg->getSourceRange(); 4865 Diag(Param->getLocation(), diag::note_template_param_here); 4866 return ExprError(); 4867 } else if (!Arg->isValueDependent()) { 4868 class TmplArgICEDiagnoser : public VerifyICEDiagnoser { 4869 QualType T; 4870 4871 public: 4872 TmplArgICEDiagnoser(QualType T) : T(T) { } 4873 4874 void diagnoseNotICE(Sema &S, SourceLocation Loc, 4875 SourceRange SR) override { 4876 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR; 4877 } 4878 } Diagnoser(ArgType); 4879 4880 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser, 4881 false).get(); 4882 if (!Arg) 4883 return ExprError(); 4884 } 4885 4886 // From here on out, all we care about are the unqualified forms 4887 // of the parameter and argument types. 4888 ParamType = ParamType.getUnqualifiedType(); 4889 ArgType = ArgType.getUnqualifiedType(); 4890 4891 // Try to convert the argument to the parameter's type. 4892 if (Context.hasSameType(ParamType, ArgType)) { 4893 // Okay: no conversion necessary 4894 } else if (ParamType->isBooleanType()) { 4895 // This is an integral-to-boolean conversion. 4896 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get(); 4897 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) || 4898 !ParamType->isEnumeralType()) { 4899 // This is an integral promotion or conversion. 4900 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get(); 4901 } else { 4902 // We can't perform this conversion. 4903 Diag(Arg->getLocStart(), 4904 diag::err_template_arg_not_convertible) 4905 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange(); 4906 Diag(Param->getLocation(), diag::note_template_param_here); 4907 return ExprError(); 4908 } 4909 4910 // Add the value of this argument to the list of converted 4911 // arguments. We use the bitwidth and signedness of the template 4912 // parameter. 4913 if (Arg->isValueDependent()) { 4914 // The argument is value-dependent. Create a new 4915 // TemplateArgument with the converted expression. 4916 Converted = TemplateArgument(Arg); 4917 return Arg; 4918 } 4919 4920 QualType IntegerType = Context.getCanonicalType(ParamType); 4921 if (const EnumType *Enum = IntegerType->getAs<EnumType>()) 4922 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType()); 4923 4924 if (ParamType->isBooleanType()) { 4925 // Value must be zero or one. 4926 Value = Value != 0; 4927 unsigned AllowedBits = Context.getTypeSize(IntegerType); 4928 if (Value.getBitWidth() != AllowedBits) 4929 Value = Value.extOrTrunc(AllowedBits); 4930 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType()); 4931 } else { 4932 llvm::APSInt OldValue = Value; 4933 4934 // Coerce the template argument's value to the value it will have 4935 // based on the template parameter's type. 4936 unsigned AllowedBits = Context.getTypeSize(IntegerType); 4937 if (Value.getBitWidth() != AllowedBits) 4938 Value = Value.extOrTrunc(AllowedBits); 4939 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType()); 4940 4941 // Complain if an unsigned parameter received a negative value. 4942 if (IntegerType->isUnsignedIntegerOrEnumerationType() 4943 && (OldValue.isSigned() && OldValue.isNegative())) { 4944 Diag(Arg->getLocStart(), diag::warn_template_arg_negative) 4945 << OldValue.toString(10) << Value.toString(10) << Param->getType() 4946 << Arg->getSourceRange(); 4947 Diag(Param->getLocation(), diag::note_template_param_here); 4948 } 4949 4950 // Complain if we overflowed the template parameter's type. 4951 unsigned RequiredBits; 4952 if (IntegerType->isUnsignedIntegerOrEnumerationType()) 4953 RequiredBits = OldValue.getActiveBits(); 4954 else if (OldValue.isUnsigned()) 4955 RequiredBits = OldValue.getActiveBits() + 1; 4956 else 4957 RequiredBits = OldValue.getMinSignedBits(); 4958 if (RequiredBits > AllowedBits) { 4959 Diag(Arg->getLocStart(), 4960 diag::warn_template_arg_too_large) 4961 << OldValue.toString(10) << Value.toString(10) << Param->getType() 4962 << Arg->getSourceRange(); 4963 Diag(Param->getLocation(), diag::note_template_param_here); 4964 } 4965 } 4966 4967 Converted = TemplateArgument(Context, Value, 4968 ParamType->isEnumeralType() 4969 ? Context.getCanonicalType(ParamType) 4970 : IntegerType); 4971 return Arg; 4972 } 4973 4974 QualType ArgType = Arg->getType(); 4975 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction 4976 4977 // Handle pointer-to-function, reference-to-function, and 4978 // pointer-to-member-function all in (roughly) the same way. 4979 if (// -- For a non-type template-parameter of type pointer to 4980 // function, only the function-to-pointer conversion (4.3) is 4981 // applied. If the template-argument represents a set of 4982 // overloaded functions (or a pointer to such), the matching 4983 // function is selected from the set (13.4). 4984 (ParamType->isPointerType() && 4985 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) || 4986 // -- For a non-type template-parameter of type reference to 4987 // function, no conversions apply. If the template-argument 4988 // represents a set of overloaded functions, the matching 4989 // function is selected from the set (13.4). 4990 (ParamType->isReferenceType() && 4991 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) || 4992 // -- For a non-type template-parameter of type pointer to 4993 // member function, no conversions apply. If the 4994 // template-argument represents a set of overloaded member 4995 // functions, the matching member function is selected from 4996 // the set (13.4). 4997 (ParamType->isMemberPointerType() && 4998 ParamType->getAs<MemberPointerType>()->getPointeeType() 4999 ->isFunctionType())) { 5000 5001 if (Arg->getType() == Context.OverloadTy) { 5002 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType, 5003 true, 5004 FoundResult)) { 5005 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart())) 5006 return ExprError(); 5007 5008 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn); 5009 ArgType = Arg->getType(); 5010 } else 5011 return ExprError(); 5012 } 5013 5014 if (!ParamType->isMemberPointerType()) { 5015 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param, 5016 ParamType, 5017 Arg, Converted)) 5018 return ExprError(); 5019 return Arg; 5020 } 5021 5022 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg, 5023 Converted)) 5024 return ExprError(); 5025 return Arg; 5026 } 5027 5028 if (ParamType->isPointerType()) { 5029 // -- for a non-type template-parameter of type pointer to 5030 // object, qualification conversions (4.4) and the 5031 // array-to-pointer conversion (4.2) are applied. 5032 // C++0x also allows a value of std::nullptr_t. 5033 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() && 5034 "Only object pointers allowed here"); 5035 5036 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param, 5037 ParamType, 5038 Arg, Converted)) 5039 return ExprError(); 5040 return Arg; 5041 } 5042 5043 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) { 5044 // -- For a non-type template-parameter of type reference to 5045 // object, no conversions apply. The type referred to by the 5046 // reference may be more cv-qualified than the (otherwise 5047 // identical) type of the template-argument. The 5048 // template-parameter is bound directly to the 5049 // template-argument, which must be an lvalue. 5050 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() && 5051 "Only object references allowed here"); 5052 5053 if (Arg->getType() == Context.OverloadTy) { 5054 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, 5055 ParamRefType->getPointeeType(), 5056 true, 5057 FoundResult)) { 5058 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart())) 5059 return ExprError(); 5060 5061 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn); 5062 ArgType = Arg->getType(); 5063 } else 5064 return ExprError(); 5065 } 5066 5067 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param, 5068 ParamType, 5069 Arg, Converted)) 5070 return ExprError(); 5071 return Arg; 5072 } 5073 5074 // Deal with parameters of type std::nullptr_t. 5075 if (ParamType->isNullPtrType()) { 5076 if (Arg->isTypeDependent() || Arg->isValueDependent()) { 5077 Converted = TemplateArgument(Arg); 5078 return Arg; 5079 } 5080 5081 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) { 5082 case NPV_NotNullPointer: 5083 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible) 5084 << Arg->getType() << ParamType; 5085 Diag(Param->getLocation(), diag::note_template_param_here); 5086 return ExprError(); 5087 5088 case NPV_Error: 5089 return ExprError(); 5090 5091 case NPV_NullPointer: 5092 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null); 5093 Converted = TemplateArgument(ParamType, /*isNullPtr*/true); 5094 return Arg; 5095 } 5096 } 5097 5098 // -- For a non-type template-parameter of type pointer to data 5099 // member, qualification conversions (4.4) are applied. 5100 assert(ParamType->isMemberPointerType() && "Only pointers to members remain"); 5101 5102 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg, 5103 Converted)) 5104 return ExprError(); 5105 return Arg; 5106} 5107 5108/// \brief Check a template argument against its corresponding 5109/// template template parameter. 5110/// 5111/// This routine implements the semantics of C++ [temp.arg.template]. 5112/// It returns true if an error occurred, and false otherwise. 5113bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param, 5114 TemplateArgumentLoc &Arg, 5115 unsigned ArgumentPackIndex) { 5116 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern(); 5117 TemplateDecl *Template = Name.getAsTemplateDecl(); 5118 if (!Template) { 5119 // Any dependent template name is fine. 5120 assert(Name.isDependent() && "Non-dependent template isn't a declaration?"); 5121 return false; 5122 } 5123 5124 // C++0x [temp.arg.template]p1: 5125 // A template-argument for a template template-parameter shall be 5126 // the name of a class template or an alias template, expressed as an 5127 // id-expression. When the template-argument names a class template, only 5128 // primary class templates are considered when matching the 5129 // template template argument with the corresponding parameter; 5130 // partial specializations are not considered even if their 5131 // parameter lists match that of the template template parameter. 5132 // 5133 // Note that we also allow template template parameters here, which 5134 // will happen when we are dealing with, e.g., class template 5135 // partial specializations. 5136 if (!isa<ClassTemplateDecl>(Template) && 5137 !isa<TemplateTemplateParmDecl>(Template) && 5138 !isa<TypeAliasTemplateDecl>(Template)) { 5139 assert(isa<FunctionTemplateDecl>(Template) && 5140 "Only function templates are possible here"); 5141 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template); 5142 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func) 5143 << Template; 5144 } 5145 5146 TemplateParameterList *Params = Param->getTemplateParameters(); 5147 if (Param->isExpandedParameterPack()) 5148 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex); 5149 5150 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(), 5151 Params, 5152 true, 5153 TPL_TemplateTemplateArgumentMatch, 5154 Arg.getLocation()); 5155} 5156 5157/// \brief Given a non-type template argument that refers to a 5158/// declaration and the type of its corresponding non-type template 5159/// parameter, produce an expression that properly refers to that 5160/// declaration. 5161ExprResult 5162Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, 5163 QualType ParamType, 5164 SourceLocation Loc) { 5165 // C++ [temp.param]p8: 5166 // 5167 // A non-type template-parameter of type "array of T" or 5168 // "function returning T" is adjusted to be of type "pointer to 5169 // T" or "pointer to function returning T", respectively. 5170 if (ParamType->isArrayType()) 5171 ParamType = Context.getArrayDecayedType(ParamType); 5172 else if (ParamType->isFunctionType()) 5173 ParamType = Context.getPointerType(ParamType); 5174 5175 // For a NULL non-type template argument, return nullptr casted to the 5176 // parameter's type. 5177 if (Arg.getKind() == TemplateArgument::NullPtr) { 5178 return ImpCastExprToType( 5179 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc), 5180 ParamType, 5181 ParamType->getAs<MemberPointerType>() 5182 ? CK_NullToMemberPointer 5183 : CK_NullToPointer); 5184 } 5185 assert(Arg.getKind() == TemplateArgument::Declaration && 5186 "Only declaration template arguments permitted here"); 5187 5188 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl()); 5189 5190 if (VD->getDeclContext()->isRecord() && 5191 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) || 5192 isa<IndirectFieldDecl>(VD))) { 5193 // If the value is a class member, we might have a pointer-to-member. 5194 // Determine whether the non-type template template parameter is of 5195 // pointer-to-member type. If so, we need to build an appropriate 5196 // expression for a pointer-to-member, since a "normal" DeclRefExpr 5197 // would refer to the member itself. 5198 if (ParamType->isMemberPointerType()) { 5199 QualType ClassType 5200 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext())); 5201 NestedNameSpecifier *Qualifier 5202 = NestedNameSpecifier::Create(Context, nullptr, false, 5203 ClassType.getTypePtr()); 5204 CXXScopeSpec SS; 5205 SS.MakeTrivial(Context, Qualifier, Loc); 5206 5207 // The actual value-ness of this is unimportant, but for 5208 // internal consistency's sake, references to instance methods 5209 // are r-values. 5210 ExprValueKind VK = VK_LValue; 5211 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance()) 5212 VK = VK_RValue; 5213 5214 ExprResult RefExpr = BuildDeclRefExpr(VD, 5215 VD->getType().getNonReferenceType(), 5216 VK, 5217 Loc, 5218 &SS); 5219 if (RefExpr.isInvalid()) 5220 return ExprError(); 5221 5222 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get()); 5223 5224 // We might need to perform a trailing qualification conversion, since 5225 // the element type on the parameter could be more qualified than the 5226 // element type in the expression we constructed. 5227 bool ObjCLifetimeConversion; 5228 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(), 5229 ParamType.getUnqualifiedType(), false, 5230 ObjCLifetimeConversion)) 5231 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp); 5232 5233 assert(!RefExpr.isInvalid() && 5234 Context.hasSameType(((Expr*) RefExpr.get())->getType(), 5235 ParamType.getUnqualifiedType())); 5236 return RefExpr; 5237 } 5238 } 5239 5240 QualType T = VD->getType().getNonReferenceType(); 5241 5242 if (ParamType->isPointerType()) { 5243 // When the non-type template parameter is a pointer, take the 5244 // address of the declaration. 5245 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc); 5246 if (RefExpr.isInvalid()) 5247 return ExprError(); 5248 5249 if (T->isFunctionType() || T->isArrayType()) { 5250 // Decay functions and arrays. 5251 RefExpr = DefaultFunctionArrayConversion(RefExpr.get()); 5252 if (RefExpr.isInvalid()) 5253 return ExprError(); 5254 5255 return RefExpr; 5256 } 5257 5258 // Take the address of everything else 5259 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get()); 5260 } 5261 5262 ExprValueKind VK = VK_RValue; 5263 5264 // If the non-type template parameter has reference type, qualify the 5265 // resulting declaration reference with the extra qualifiers on the 5266 // type that the reference refers to. 5267 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) { 5268 VK = VK_LValue; 5269 T = Context.getQualifiedType(T, 5270 TargetRef->getPointeeType().getQualifiers()); 5271 } else if (isa<FunctionDecl>(VD)) { 5272 // References to functions are always lvalues. 5273 VK = VK_LValue; 5274 } 5275 5276 return BuildDeclRefExpr(VD, T, VK, Loc); 5277} 5278 5279/// \brief Construct a new expression that refers to the given 5280/// integral template argument with the given source-location 5281/// information. 5282/// 5283/// This routine takes care of the mapping from an integral template 5284/// argument (which may have any integral type) to the appropriate 5285/// literal value. 5286ExprResult 5287Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, 5288 SourceLocation Loc) { 5289 assert(Arg.getKind() == TemplateArgument::Integral && 5290 "Operation is only valid for integral template arguments"); 5291 QualType OrigT = Arg.getIntegralType(); 5292 5293 // If this is an enum type that we're instantiating, we need to use an integer 5294 // type the same size as the enumerator. We don't want to build an 5295 // IntegerLiteral with enum type. The integer type of an enum type can be of 5296 // any integral type with C++11 enum classes, make sure we create the right 5297 // type of literal for it. 5298 QualType T = OrigT; 5299 if (const EnumType *ET = OrigT->getAs<EnumType>()) 5300 T = ET->getDecl()->getIntegerType(); 5301 5302 Expr *E; 5303 if (T->isAnyCharacterType()) { 5304 CharacterLiteral::CharacterKind Kind; 5305 if (T->isWideCharType()) 5306 Kind = CharacterLiteral::Wide; 5307 else if (T->isChar16Type()) 5308 Kind = CharacterLiteral::UTF16; 5309 else if (T->isChar32Type()) 5310 Kind = CharacterLiteral::UTF32; 5311 else 5312 Kind = CharacterLiteral::Ascii; 5313 5314 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(), 5315 Kind, T, Loc); 5316 } else if (T->isBooleanType()) { 5317 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(), 5318 T, Loc); 5319 } else if (T->isNullPtrType()) { 5320 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc); 5321 } else { 5322 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc); 5323 } 5324 5325 if (OrigT->isEnumeralType()) { 5326 // FIXME: This is a hack. We need a better way to handle substituted 5327 // non-type template parameters. 5328 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E, 5329 nullptr, 5330 Context.getTrivialTypeSourceInfo(OrigT, Loc), 5331 Loc, Loc); 5332 } 5333 5334 return E; 5335} 5336 5337/// \brief Match two template parameters within template parameter lists. 5338static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old, 5339 bool Complain, 5340 Sema::TemplateParameterListEqualKind Kind, 5341 SourceLocation TemplateArgLoc) { 5342 // Check the actual kind (type, non-type, template). 5343 if (Old->getKind() != New->getKind()) { 5344 if (Complain) { 5345 unsigned NextDiag = diag::err_template_param_different_kind; 5346 if (TemplateArgLoc.isValid()) { 5347 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch); 5348 NextDiag = diag::note_template_param_different_kind; 5349 } 5350 S.Diag(New->getLocation(), NextDiag) 5351 << (Kind != Sema::TPL_TemplateMatch); 5352 S.Diag(Old->getLocation(), diag::note_template_prev_declaration) 5353 << (Kind != Sema::TPL_TemplateMatch); 5354 } 5355 5356 return false; 5357 } 5358 5359 // Check that both are parameter packs are neither are parameter packs. 5360 // However, if we are matching a template template argument to a 5361 // template template parameter, the template template parameter can have 5362 // a parameter pack where the template template argument does not. 5363 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() && 5364 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch && 5365 Old->isTemplateParameterPack())) { 5366 if (Complain) { 5367 unsigned NextDiag = diag::err_template_parameter_pack_non_pack; 5368 if (TemplateArgLoc.isValid()) { 5369 S.Diag(TemplateArgLoc, 5370 diag::err_template_arg_template_params_mismatch); 5371 NextDiag = diag::note_template_parameter_pack_non_pack; 5372 } 5373 5374 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0 5375 : isa<NonTypeTemplateParmDecl>(New)? 1 5376 : 2; 5377 S.Diag(New->getLocation(), NextDiag) 5378 << ParamKind << New->isParameterPack(); 5379 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here) 5380 << ParamKind << Old->isParameterPack(); 5381 } 5382 5383 return false; 5384 } 5385 5386 // For non-type template parameters, check the type of the parameter. 5387 if (NonTypeTemplateParmDecl *OldNTTP 5388 = dyn_cast<NonTypeTemplateParmDecl>(Old)) { 5389 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New); 5390 5391 // If we are matching a template template argument to a template 5392 // template parameter and one of the non-type template parameter types 5393 // is dependent, then we must wait until template instantiation time 5394 // to actually compare the arguments. 5395 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch && 5396 (OldNTTP->getType()->isDependentType() || 5397 NewNTTP->getType()->isDependentType())) 5398 return true; 5399 5400 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) { 5401 if (Complain) { 5402 unsigned NextDiag = diag::err_template_nontype_parm_different_type; 5403 if (TemplateArgLoc.isValid()) { 5404 S.Diag(TemplateArgLoc, 5405 diag::err_template_arg_template_params_mismatch); 5406 NextDiag = diag::note_template_nontype_parm_different_type; 5407 } 5408 S.Diag(NewNTTP->getLocation(), NextDiag) 5409 << NewNTTP->getType() 5410 << (Kind != Sema::TPL_TemplateMatch); 5411 S.Diag(OldNTTP->getLocation(), 5412 diag::note_template_nontype_parm_prev_declaration) 5413 << OldNTTP->getType(); 5414 } 5415 5416 return false; 5417 } 5418 5419 return true; 5420 } 5421 5422 // For template template parameters, check the template parameter types. 5423 // The template parameter lists of template template 5424 // parameters must agree. 5425 if (TemplateTemplateParmDecl *OldTTP 5426 = dyn_cast<TemplateTemplateParmDecl>(Old)) { 5427 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New); 5428 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(), 5429 OldTTP->getTemplateParameters(), 5430 Complain, 5431 (Kind == Sema::TPL_TemplateMatch 5432 ? Sema::TPL_TemplateTemplateParmMatch 5433 : Kind), 5434 TemplateArgLoc); 5435 } 5436 5437 return true; 5438} 5439 5440/// \brief Diagnose a known arity mismatch when comparing template argument 5441/// lists. 5442static 5443void DiagnoseTemplateParameterListArityMismatch(Sema &S, 5444 TemplateParameterList *New, 5445 TemplateParameterList *Old, 5446 Sema::TemplateParameterListEqualKind Kind, 5447 SourceLocation TemplateArgLoc) { 5448 unsigned NextDiag = diag::err_template_param_list_different_arity; 5449 if (TemplateArgLoc.isValid()) { 5450 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch); 5451 NextDiag = diag::note_template_param_list_different_arity; 5452 } 5453 S.Diag(New->getTemplateLoc(), NextDiag) 5454 << (New->size() > Old->size()) 5455 << (Kind != Sema::TPL_TemplateMatch) 5456 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc()); 5457 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration) 5458 << (Kind != Sema::TPL_TemplateMatch) 5459 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc()); 5460} 5461 5462/// \brief Determine whether the given template parameter lists are 5463/// equivalent. 5464/// 5465/// \param New The new template parameter list, typically written in the 5466/// source code as part of a new template declaration. 5467/// 5468/// \param Old The old template parameter list, typically found via 5469/// name lookup of the template declared with this template parameter 5470/// list. 5471/// 5472/// \param Complain If true, this routine will produce a diagnostic if 5473/// the template parameter lists are not equivalent. 5474/// 5475/// \param Kind describes how we are to match the template parameter lists. 5476/// 5477/// \param TemplateArgLoc If this source location is valid, then we 5478/// are actually checking the template parameter list of a template 5479/// argument (New) against the template parameter list of its 5480/// corresponding template template parameter (Old). We produce 5481/// slightly different diagnostics in this scenario. 5482/// 5483/// \returns True if the template parameter lists are equal, false 5484/// otherwise. 5485bool 5486Sema::TemplateParameterListsAreEqual(TemplateParameterList *New, 5487 TemplateParameterList *Old, 5488 bool Complain, 5489 TemplateParameterListEqualKind Kind, 5490 SourceLocation TemplateArgLoc) { 5491 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) { 5492 if (Complain) 5493 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind, 5494 TemplateArgLoc); 5495 5496 return false; 5497 } 5498 5499 // C++0x [temp.arg.template]p3: 5500 // A template-argument matches a template template-parameter (call it P) 5501 // when each of the template parameters in the template-parameter-list of 5502 // the template-argument's corresponding class template or alias template 5503 // (call it A) matches the corresponding template parameter in the 5504 // template-parameter-list of P. [...] 5505 TemplateParameterList::iterator NewParm = New->begin(); 5506 TemplateParameterList::iterator NewParmEnd = New->end(); 5507 for (TemplateParameterList::iterator OldParm = Old->begin(), 5508 OldParmEnd = Old->end(); 5509 OldParm != OldParmEnd; ++OldParm) { 5510 if (Kind != TPL_TemplateTemplateArgumentMatch || 5511 !(*OldParm)->isTemplateParameterPack()) { 5512 if (NewParm == NewParmEnd) { 5513 if (Complain) 5514 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind, 5515 TemplateArgLoc); 5516 5517 return false; 5518 } 5519 5520 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain, 5521 Kind, TemplateArgLoc)) 5522 return false; 5523 5524 ++NewParm; 5525 continue; 5526 } 5527 5528 // C++0x [temp.arg.template]p3: 5529 // [...] When P's template- parameter-list contains a template parameter 5530 // pack (14.5.3), the template parameter pack will match zero or more 5531 // template parameters or template parameter packs in the 5532 // template-parameter-list of A with the same type and form as the 5533 // template parameter pack in P (ignoring whether those template 5534 // parameters are template parameter packs). 5535 for (; NewParm != NewParmEnd; ++NewParm) { 5536 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain, 5537 Kind, TemplateArgLoc)) 5538 return false; 5539 } 5540 } 5541 5542 // Make sure we exhausted all of the arguments. 5543 if (NewParm != NewParmEnd) { 5544 if (Complain) 5545 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind, 5546 TemplateArgLoc); 5547 5548 return false; 5549 } 5550 5551 return true; 5552} 5553 5554/// \brief Check whether a template can be declared within this scope. 5555/// 5556/// If the template declaration is valid in this scope, returns 5557/// false. Otherwise, issues a diagnostic and returns true. 5558bool 5559Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) { 5560 if (!S) 5561 return false; 5562 5563 // Find the nearest enclosing declaration scope. 5564 while ((S->getFlags() & Scope::DeclScope) == 0 || 5565 (S->getFlags() & Scope::TemplateParamScope) != 0) 5566 S = S->getParent(); 5567 5568 // C++ [temp]p4: 5569 // A template [...] shall not have C linkage. 5570 DeclContext *Ctx = S->getEntity(); 5571 if (Ctx && Ctx->isExternCContext()) 5572 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage) 5573 << TemplateParams->getSourceRange(); 5574 5575 while (Ctx && isa<LinkageSpecDecl>(Ctx)) 5576 Ctx = Ctx->getParent(); 5577 5578 // C++ [temp]p2: 5579 // A template-declaration can appear only as a namespace scope or 5580 // class scope declaration. 5581 if (Ctx) { 5582 if (Ctx->isFileContext()) 5583 return false; 5584 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) { 5585 // C++ [temp.mem]p2: 5586 // A local class shall not have member templates. 5587 if (RD->isLocalClass()) 5588 return Diag(TemplateParams->getTemplateLoc(), 5589 diag::err_template_inside_local_class) 5590 << TemplateParams->getSourceRange(); 5591 else 5592 return false; 5593 } 5594 } 5595 5596 return Diag(TemplateParams->getTemplateLoc(), 5597 diag::err_template_outside_namespace_or_class_scope) 5598 << TemplateParams->getSourceRange(); 5599} 5600 5601/// \brief Determine what kind of template specialization the given declaration 5602/// is. 5603static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) { 5604 if (!D) 5605 return TSK_Undeclared; 5606 5607 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) 56