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