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