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