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