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