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