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