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/SemaInternal.h" 37 #include "clang/Sema/Template.h" 38 #include "clang/Sema/TemplateDeduction.h" 39 #include "llvm/ADT/SmallBitVector.h" 40 #include "llvm/ADT/SmallString.h" 41 #include "llvm/ADT/StringExtras.h" 42 43 #include <iterator> 44 #include <optional> 45 using namespace clang; 46 using namespace sema; 47 48 // Exported for use by Parser. 49 SourceRange 50 clang::getTemplateParamsRange(TemplateParameterList const * const *Ps, 51 unsigned N) { 52 if (!N) return SourceRange(); 53 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc()); 54 } 55 56 unsigned Sema::getTemplateDepth(Scope *S) const { 57 unsigned Depth = 0; 58 59 // Each template parameter scope represents one level of template parameter 60 // depth. 61 for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope; 62 TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) { 63 ++Depth; 64 } 65 66 // Note that there are template parameters with the given depth. 67 auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(Depth, D + 1); }; 68 69 // Look for parameters of an enclosing generic lambda. We don't create a 70 // template parameter scope for these. 71 for (FunctionScopeInfo *FSI : getFunctionScopes()) { 72 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FSI)) { 73 if (!LSI->TemplateParams.empty()) { 74 ParamsAtDepth(LSI->AutoTemplateParameterDepth); 75 break; 76 } 77 if (LSI->GLTemplateParameterList) { 78 ParamsAtDepth(LSI->GLTemplateParameterList->getDepth()); 79 break; 80 } 81 } 82 } 83 84 // Look for parameters of an enclosing terse function template. We don't 85 // create a template parameter scope for these either. 86 for (const InventedTemplateParameterInfo &Info : 87 getInventedParameterInfos()) { 88 if (!Info.TemplateParams.empty()) { 89 ParamsAtDepth(Info.AutoTemplateParameterDepth); 90 break; 91 } 92 } 93 94 return Depth; 95 } 96 97 /// \brief Determine whether the declaration found is acceptable as the name 98 /// of a template and, if so, return that template declaration. Otherwise, 99 /// returns null. 100 /// 101 /// Note that this may return an UnresolvedUsingValueDecl if AllowDependent 102 /// is true. In all other cases it will return a TemplateDecl (or null). 103 NamedDecl *Sema::getAsTemplateNameDecl(NamedDecl *D, 104 bool AllowFunctionTemplates, 105 bool AllowDependent) { 106 D = D->getUnderlyingDecl(); 107 108 if (isa<TemplateDecl>(D)) { 109 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D)) 110 return nullptr; 111 112 return D; 113 } 114 115 if (const auto *Record = dyn_cast<CXXRecordDecl>(D)) { 116 // C++ [temp.local]p1: 117 // Like normal (non-template) classes, class templates have an 118 // injected-class-name (Clause 9). The injected-class-name 119 // can be used with or without a template-argument-list. When 120 // it is used without a template-argument-list, it is 121 // equivalent to the injected-class-name followed by the 122 // template-parameters of the class template enclosed in 123 // <>. When it is used with a template-argument-list, it 124 // refers to the specified class template specialization, 125 // which could be the current specialization or another 126 // specialization. 127 if (Record->isInjectedClassName()) { 128 Record = cast<CXXRecordDecl>(Record->getDeclContext()); 129 if (Record->getDescribedClassTemplate()) 130 return Record->getDescribedClassTemplate(); 131 132 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Record)) 133 return Spec->getSpecializedTemplate(); 134 } 135 136 return nullptr; 137 } 138 139 // 'using Dependent::foo;' can resolve to a template name. 140 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an 141 // injected-class-name). 142 if (AllowDependent && isa<UnresolvedUsingValueDecl>(D)) 143 return D; 144 145 return nullptr; 146 } 147 148 void Sema::FilterAcceptableTemplateNames(LookupResult &R, 149 bool AllowFunctionTemplates, 150 bool AllowDependent) { 151 LookupResult::Filter filter = R.makeFilter(); 152 while (filter.hasNext()) { 153 NamedDecl *Orig = filter.next(); 154 if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent)) 155 filter.erase(); 156 } 157 filter.done(); 158 } 159 160 bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R, 161 bool AllowFunctionTemplates, 162 bool AllowDependent, 163 bool AllowNonTemplateFunctions) { 164 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 165 if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent)) 166 return true; 167 if (AllowNonTemplateFunctions && 168 isa<FunctionDecl>((*I)->getUnderlyingDecl())) 169 return true; 170 } 171 172 return false; 173 } 174 175 TemplateNameKind Sema::isTemplateName(Scope *S, 176 CXXScopeSpec &SS, 177 bool hasTemplateKeyword, 178 const UnqualifiedId &Name, 179 ParsedType ObjectTypePtr, 180 bool EnteringContext, 181 TemplateTy &TemplateResult, 182 bool &MemberOfUnknownSpecialization, 183 bool Disambiguation) { 184 assert(getLangOpts().CPlusPlus && "No template names in C!"); 185 186 DeclarationName TName; 187 MemberOfUnknownSpecialization = false; 188 189 switch (Name.getKind()) { 190 case UnqualifiedIdKind::IK_Identifier: 191 TName = DeclarationName(Name.Identifier); 192 break; 193 194 case UnqualifiedIdKind::IK_OperatorFunctionId: 195 TName = Context.DeclarationNames.getCXXOperatorName( 196 Name.OperatorFunctionId.Operator); 197 break; 198 199 case UnqualifiedIdKind::IK_LiteralOperatorId: 200 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier); 201 break; 202 203 default: 204 return TNK_Non_template; 205 } 206 207 QualType ObjectType = ObjectTypePtr.get(); 208 209 AssumedTemplateKind AssumedTemplate; 210 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName); 211 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext, 212 MemberOfUnknownSpecialization, SourceLocation(), 213 &AssumedTemplate, 214 /*AllowTypoCorrection=*/!Disambiguation)) 215 return TNK_Non_template; 216 217 if (AssumedTemplate != AssumedTemplateKind::None) { 218 TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName)); 219 // Let the parser know whether we found nothing or found functions; if we 220 // found nothing, we want to more carefully check whether this is actually 221 // a function template name versus some other kind of undeclared identifier. 222 return AssumedTemplate == AssumedTemplateKind::FoundNothing 223 ? TNK_Undeclared_template 224 : TNK_Function_template; 225 } 226 227 if (R.empty()) 228 return TNK_Non_template; 229 230 NamedDecl *D = nullptr; 231 UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(*R.begin()); 232 if (R.isAmbiguous()) { 233 // If we got an ambiguity involving a non-function template, treat this 234 // as a template name, and pick an arbitrary template for error recovery. 235 bool AnyFunctionTemplates = false; 236 for (NamedDecl *FoundD : R) { 237 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) { 238 if (isa<FunctionTemplateDecl>(FoundTemplate)) 239 AnyFunctionTemplates = true; 240 else { 241 D = FoundTemplate; 242 FoundUsingShadow = dyn_cast<UsingShadowDecl>(FoundD); 243 break; 244 } 245 } 246 } 247 248 // If we didn't find any templates at all, this isn't a template name. 249 // Leave the ambiguity for a later lookup to diagnose. 250 if (!D && !AnyFunctionTemplates) { 251 R.suppressDiagnostics(); 252 return TNK_Non_template; 253 } 254 255 // If the only templates were function templates, filter out the rest. 256 // We'll diagnose the ambiguity later. 257 if (!D) 258 FilterAcceptableTemplateNames(R); 259 } 260 261 // At this point, we have either picked a single template name declaration D 262 // or we have a non-empty set of results R containing either one template name 263 // declaration or a set of function templates. 264 265 TemplateName Template; 266 TemplateNameKind TemplateKind; 267 268 unsigned ResultCount = R.end() - R.begin(); 269 if (!D && ResultCount > 1) { 270 // We assume that we'll preserve the qualifier from a function 271 // template name in other ways. 272 Template = Context.getOverloadedTemplateName(R.begin(), R.end()); 273 TemplateKind = TNK_Function_template; 274 275 // We'll do this lookup again later. 276 R.suppressDiagnostics(); 277 } else { 278 if (!D) { 279 D = getAsTemplateNameDecl(*R.begin()); 280 assert(D && "unambiguous result is not a template name"); 281 } 282 283 if (isa<UnresolvedUsingValueDecl>(D)) { 284 // We don't yet know whether this is a template-name or not. 285 MemberOfUnknownSpecialization = true; 286 return TNK_Non_template; 287 } 288 289 TemplateDecl *TD = cast<TemplateDecl>(D); 290 Template = 291 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD); 292 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD); 293 if (SS.isSet() && !SS.isInvalid()) { 294 NestedNameSpecifier *Qualifier = SS.getScopeRep(); 295 Template = Context.getQualifiedTemplateName(Qualifier, hasTemplateKeyword, 296 Template); 297 } 298 299 if (isa<FunctionTemplateDecl>(TD)) { 300 TemplateKind = TNK_Function_template; 301 302 // We'll do this lookup again later. 303 R.suppressDiagnostics(); 304 } else { 305 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) || 306 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) || 307 isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD)); 308 TemplateKind = 309 isa<VarTemplateDecl>(TD) ? TNK_Var_template : 310 isa<ConceptDecl>(TD) ? TNK_Concept_template : 311 TNK_Type_template; 312 } 313 } 314 315 TemplateResult = TemplateTy::make(Template); 316 return TemplateKind; 317 } 318 319 bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name, 320 SourceLocation NameLoc, CXXScopeSpec &SS, 321 ParsedTemplateTy *Template /*=nullptr*/) { 322 bool MemberOfUnknownSpecialization = false; 323 324 // We could use redeclaration lookup here, but we don't need to: the 325 // syntactic form of a deduction guide is enough to identify it even 326 // if we can't look up the template name at all. 327 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName); 328 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(), 329 /*EnteringContext*/ false, 330 MemberOfUnknownSpecialization)) 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 *Template = TemplateTy::make(TemplateName(TD)); 348 return true; 349 } 350 351 bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II, 352 SourceLocation IILoc, 353 Scope *S, 354 const CXXScopeSpec *SS, 355 TemplateTy &SuggestedTemplate, 356 TemplateNameKind &SuggestedKind) { 357 // We can't recover unless there's a dependent scope specifier preceding the 358 // template name. 359 // FIXME: Typo correction? 360 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) || 361 computeDeclContext(*SS)) 362 return false; 363 364 // The code is missing a 'template' keyword prior to the dependent template 365 // name. 366 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep(); 367 Diag(IILoc, diag::err_template_kw_missing) 368 << Qualifier << II.getName() 369 << FixItHint::CreateInsertion(IILoc, "template "); 370 SuggestedTemplate 371 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II)); 372 SuggestedKind = TNK_Dependent_template_name; 373 return true; 374 } 375 376 bool Sema::LookupTemplateName(LookupResult &Found, 377 Scope *S, CXXScopeSpec &SS, 378 QualType ObjectType, 379 bool EnteringContext, 380 bool &MemberOfUnknownSpecialization, 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 MemberOfUnknownSpecialization = false; 394 DeclContext *LookupCtx = nullptr; 395 bool IsDependent = false; 396 if (!ObjectType.isNull()) { 397 // This nested-name-specifier occurs in a member access expression, e.g., 398 // x->B::f, and we are looking into the type of the object. 399 assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist"); 400 LookupCtx = computeDeclContext(ObjectType); 401 IsDependent = !LookupCtx && ObjectType->isDependentType(); 402 assert((IsDependent || !ObjectType->isIncompleteType() || 403 !ObjectType->getAs<TagType>() || 404 ObjectType->castAs<TagType>()->isBeingDefined()) && 405 "Caller should have completed object type"); 406 407 // Template names cannot appear inside an Objective-C class or object type 408 // or a vector type. 409 // 410 // FIXME: This is wrong. For example: 411 // 412 // template<typename T> using Vec = T __attribute__((ext_vector_type(4))); 413 // Vec<int> vi; 414 // vi.Vec<int>::~Vec<int>(); 415 // 416 // ... should be accepted but we will not treat 'Vec' as a template name 417 // here. The right thing to do would be to check if the name is a valid 418 // vector component name, and look up a template name if not. And similarly 419 // for lookups into Objective-C class and object types, where the same 420 // problem can arise. 421 if (ObjectType->isObjCObjectOrInterfaceType() || 422 ObjectType->isVectorType()) { 423 Found.clear(); 424 return false; 425 } 426 } else if (SS.isNotEmpty()) { 427 // This nested-name-specifier occurs after another nested-name-specifier, 428 // so long into the context associated with the prior nested-name-specifier. 429 LookupCtx = computeDeclContext(SS, EnteringContext); 430 IsDependent = !LookupCtx && isDependentScopeSpecifier(SS); 431 432 // The declaration context must be complete. 433 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx)) 434 return true; 435 } 436 437 bool ObjectTypeSearchedInScope = false; 438 bool AllowFunctionTemplatesInLookup = true; 439 if (LookupCtx) { 440 // Perform "qualified" name lookup into the declaration context we 441 // computed, which is either the type of the base of a member access 442 // expression or the declaration context associated with a prior 443 // nested-name-specifier. 444 LookupQualifiedName(Found, LookupCtx); 445 446 // FIXME: The C++ standard does not clearly specify what happens in the 447 // case where the object type is dependent, and implementations vary. In 448 // Clang, we treat a name after a . or -> as a template-name if lookup 449 // finds a non-dependent member or member of the current instantiation that 450 // is a type template, or finds no such members and lookup in the context 451 // of the postfix-expression finds a type template. In the latter case, the 452 // name is nonetheless dependent, and we may resolve it to a member of an 453 // unknown specialization when we come to instantiate the template. 454 IsDependent |= Found.wasNotFoundInCurrentInstantiation(); 455 } 456 457 if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) { 458 // C++ [basic.lookup.classref]p1: 459 // In a class member access expression (5.2.5), if the . or -> token is 460 // immediately followed by an identifier followed by a <, the 461 // identifier must be looked up to determine whether the < is the 462 // beginning of a template argument list (14.2) or a less-than operator. 463 // The identifier is first looked up in the class of the object 464 // expression. If the identifier is not found, it is then looked up in 465 // the context of the entire postfix-expression and shall name a class 466 // template. 467 if (S) 468 LookupName(Found, S); 469 470 if (!ObjectType.isNull()) { 471 // FIXME: We should filter out all non-type templates here, particularly 472 // variable templates and concepts. But the exclusion of alias templates 473 // and template template parameters is a wording defect. 474 AllowFunctionTemplatesInLookup = false; 475 ObjectTypeSearchedInScope = true; 476 } 477 478 IsDependent |= Found.wasNotFoundInCurrentInstantiation(); 479 } 480 481 if (Found.isAmbiguous()) 482 return false; 483 484 if (ATK && SS.isEmpty() && ObjectType.isNull() && 485 !RequiredTemplate.hasTemplateKeyword()) { 486 // C++2a [temp.names]p2: 487 // A name is also considered to refer to a template if it is an 488 // unqualified-id followed by a < and name lookup finds either one or more 489 // functions or finds nothing. 490 // 491 // To keep our behavior consistent, we apply the "finds nothing" part in 492 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we 493 // successfully form a call to an undeclared template-id. 494 bool AllFunctions = 495 getLangOpts().CPlusPlus20 && llvm::all_of(Found, [](NamedDecl *ND) { 496 return isa<FunctionDecl>(ND->getUnderlyingDecl()); 497 }); 498 if (AllFunctions || (Found.empty() && !IsDependent)) { 499 // If lookup found any functions, or if this is a name that can only be 500 // used for a function, then strongly assume this is a function 501 // template-id. 502 *ATK = (Found.empty() && Found.getLookupName().isIdentifier()) 503 ? AssumedTemplateKind::FoundNothing 504 : AssumedTemplateKind::FoundFunctions; 505 Found.clear(); 506 return false; 507 } 508 } 509 510 if (Found.empty() && !IsDependent && AllowTypoCorrection) { 511 // If we did not find any names, and this is not a disambiguation, attempt 512 // to correct any typos. 513 DeclarationName Name = Found.getLookupName(); 514 Found.clear(); 515 // Simple filter callback that, for keywords, only accepts the C++ *_cast 516 DefaultFilterCCC FilterCCC{}; 517 FilterCCC.WantTypeSpecifiers = false; 518 FilterCCC.WantExpressionKeywords = false; 519 FilterCCC.WantRemainingKeywords = false; 520 FilterCCC.WantCXXNamedCasts = true; 521 if (TypoCorrection Corrected = 522 CorrectTypo(Found.getLookupNameInfo(), Found.getLookupKind(), S, 523 &SS, FilterCCC, CTK_ErrorRecovery, LookupCtx)) { 524 if (auto *ND = Corrected.getFoundDecl()) 525 Found.addDecl(ND); 526 FilterAcceptableTemplateNames(Found); 527 if (Found.isAmbiguous()) { 528 Found.clear(); 529 } else if (!Found.empty()) { 530 Found.setLookupName(Corrected.getCorrection()); 531 if (LookupCtx) { 532 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 533 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 534 Name.getAsString() == CorrectedStr; 535 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest) 536 << Name << LookupCtx << DroppedSpecifier 537 << SS.getRange()); 538 } else { 539 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name); 540 } 541 } 542 } 543 } 544 545 NamedDecl *ExampleLookupResult = 546 Found.empty() ? nullptr : Found.getRepresentativeDecl(); 547 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup); 548 if (Found.empty()) { 549 if (IsDependent) { 550 MemberOfUnknownSpecialization = true; 551 return false; 552 } 553 554 // If a 'template' keyword was used, a lookup that finds only non-template 555 // names is an error. 556 if (ExampleLookupResult && RequiredTemplate) { 557 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template) 558 << Found.getLookupName() << SS.getRange() 559 << RequiredTemplate.hasTemplateKeyword() 560 << RequiredTemplate.getTemplateKeywordLoc(); 561 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(), 562 diag::note_template_kw_refers_to_non_template) 563 << Found.getLookupName(); 564 return true; 565 } 566 567 return false; 568 } 569 570 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope && 571 !getLangOpts().CPlusPlus11) { 572 // C++03 [basic.lookup.classref]p1: 573 // [...] If the lookup in the class of the object expression finds a 574 // template, the name is also looked up in the context of the entire 575 // postfix-expression and [...] 576 // 577 // Note: C++11 does not perform this second lookup. 578 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(), 579 LookupOrdinaryName); 580 FoundOuter.setTemplateNameLookup(true); 581 LookupName(FoundOuter, S); 582 // FIXME: We silently accept an ambiguous lookup here, in violation of 583 // [basic.lookup]/1. 584 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false); 585 586 NamedDecl *OuterTemplate; 587 if (FoundOuter.empty()) { 588 // - if the name is not found, the name found in the class of the 589 // object expression is used, otherwise 590 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() || 591 !(OuterTemplate = 592 getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) { 593 // - if the name is found in the context of the entire 594 // postfix-expression and does not name a class template, the name 595 // found in the class of the object expression is used, otherwise 596 FoundOuter.clear(); 597 } else if (!Found.isSuppressingAmbiguousDiagnostics()) { 598 // - if the name found is a class template, it must refer to the same 599 // entity as the one found in the class of the object expression, 600 // otherwise the program is ill-formed. 601 if (!Found.isSingleResult() || 602 getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() != 603 OuterTemplate->getCanonicalDecl()) { 604 Diag(Found.getNameLoc(), 605 diag::ext_nested_name_member_ref_lookup_ambiguous) 606 << Found.getLookupName() 607 << ObjectType; 608 Diag(Found.getRepresentativeDecl()->getLocation(), 609 diag::note_ambig_member_ref_object_type) 610 << ObjectType; 611 Diag(FoundOuter.getFoundDecl()->getLocation(), 612 diag::note_ambig_member_ref_scope); 613 614 // Recover by taking the template that we found in the object 615 // expression's type. 616 } 617 } 618 } 619 620 return false; 621 } 622 623 void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, 624 SourceLocation Less, 625 SourceLocation Greater) { 626 if (TemplateName.isInvalid()) 627 return; 628 629 DeclarationNameInfo NameInfo; 630 CXXScopeSpec SS; 631 LookupNameKind LookupKind; 632 633 DeclContext *LookupCtx = nullptr; 634 NamedDecl *Found = nullptr; 635 bool MissingTemplateKeyword = false; 636 637 // Figure out what name we looked up. 638 if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) { 639 NameInfo = DRE->getNameInfo(); 640 SS.Adopt(DRE->getQualifierLoc()); 641 LookupKind = LookupOrdinaryName; 642 Found = DRE->getFoundDecl(); 643 } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) { 644 NameInfo = ME->getMemberNameInfo(); 645 SS.Adopt(ME->getQualifierLoc()); 646 LookupKind = LookupMemberName; 647 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl(); 648 Found = ME->getMemberDecl(); 649 } else if (auto *DSDRE = 650 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) { 651 NameInfo = DSDRE->getNameInfo(); 652 SS.Adopt(DSDRE->getQualifierLoc()); 653 MissingTemplateKeyword = true; 654 } else if (auto *DSME = 655 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) { 656 NameInfo = DSME->getMemberNameInfo(); 657 SS.Adopt(DSME->getQualifierLoc()); 658 MissingTemplateKeyword = true; 659 } else { 660 llvm_unreachable("unexpected kind of potential template name"); 661 } 662 663 // If this is a dependent-scope lookup, diagnose that the 'template' keyword 664 // was missing. 665 if (MissingTemplateKeyword) { 666 Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing) 667 << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater); 668 return; 669 } 670 671 // Try to correct the name by looking for templates and C++ named casts. 672 struct TemplateCandidateFilter : CorrectionCandidateCallback { 673 Sema &S; 674 TemplateCandidateFilter(Sema &S) : S(S) { 675 WantTypeSpecifiers = false; 676 WantExpressionKeywords = false; 677 WantRemainingKeywords = false; 678 WantCXXNamedCasts = true; 679 }; 680 bool ValidateCandidate(const TypoCorrection &Candidate) override { 681 if (auto *ND = Candidate.getCorrectionDecl()) 682 return S.getAsTemplateNameDecl(ND); 683 return Candidate.isKeyword(); 684 } 685 686 std::unique_ptr<CorrectionCandidateCallback> clone() override { 687 return std::make_unique<TemplateCandidateFilter>(*this); 688 } 689 }; 690 691 DeclarationName Name = NameInfo.getName(); 692 TemplateCandidateFilter CCC(*this); 693 if (TypoCorrection Corrected = CorrectTypo(NameInfo, LookupKind, S, &SS, CCC, 694 CTK_ErrorRecovery, LookupCtx)) { 695 auto *ND = Corrected.getFoundDecl(); 696 if (ND) 697 ND = getAsTemplateNameDecl(ND); 698 if (ND || Corrected.isKeyword()) { 699 if (LookupCtx) { 700 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 701 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 702 Name.getAsString() == CorrectedStr; 703 diagnoseTypo(Corrected, 704 PDiag(diag::err_non_template_in_member_template_id_suggest) 705 << Name << LookupCtx << DroppedSpecifier 706 << SS.getRange(), false); 707 } else { 708 diagnoseTypo(Corrected, 709 PDiag(diag::err_non_template_in_template_id_suggest) 710 << Name, false); 711 } 712 if (Found) 713 Diag(Found->getLocation(), 714 diag::note_non_template_in_template_id_found); 715 return; 716 } 717 } 718 719 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id) 720 << Name << SourceRange(Less, Greater); 721 if (Found) 722 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found); 723 } 724 725 /// ActOnDependentIdExpression - Handle a dependent id-expression that 726 /// was just parsed. This is only possible with an explicit scope 727 /// specifier naming a dependent type. 728 ExprResult 729 Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS, 730 SourceLocation TemplateKWLoc, 731 const DeclarationNameInfo &NameInfo, 732 bool isAddressOfOperand, 733 const TemplateArgumentListInfo *TemplateArgs) { 734 DeclContext *DC = getFunctionLevelDeclContext(); 735 736 // C++11 [expr.prim.general]p12: 737 // An id-expression that denotes a non-static data member or non-static 738 // member function of a class can only be used: 739 // (...) 740 // - if that id-expression denotes a non-static data member and it 741 // appears in an unevaluated operand. 742 // 743 // If this might be the case, form a DependentScopeDeclRefExpr instead of a 744 // CXXDependentScopeMemberExpr. The former can instantiate to either 745 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is 746 // always a MemberExpr. 747 bool MightBeCxx11UnevalField = 748 getLangOpts().CPlusPlus11 && isUnevaluatedContext(); 749 750 // Check if the nested name specifier is an enum type. 751 bool IsEnum = false; 752 if (NestedNameSpecifier *NNS = SS.getScopeRep()) 753 IsEnum = isa_and_nonnull<EnumType>(NNS->getAsType()); 754 755 if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum && 756 isa<CXXMethodDecl>(DC) && 757 cast<CXXMethodDecl>(DC)->isImplicitObjectMemberFunction()) { 758 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType().getNonReferenceType(); 759 760 // Since the 'this' expression is synthesized, we don't need to 761 // perform the double-lookup check. 762 NamedDecl *FirstQualifierInScope = nullptr; 763 764 return CXXDependentScopeMemberExpr::Create( 765 Context, /*This=*/nullptr, ThisType, 766 /*IsArrow=*/!Context.getLangOpts().HLSL, 767 /*Op=*/SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc, 768 FirstQualifierInScope, NameInfo, TemplateArgs); 769 } 770 771 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs); 772 } 773 774 ExprResult 775 Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS, 776 SourceLocation TemplateKWLoc, 777 const DeclarationNameInfo &NameInfo, 778 const TemplateArgumentListInfo *TemplateArgs) { 779 // DependentScopeDeclRefExpr::Create requires a valid QualifierLoc 780 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 781 if (!QualifierLoc) 782 return ExprError(); 783 784 return DependentScopeDeclRefExpr::Create( 785 Context, QualifierLoc, TemplateKWLoc, NameInfo, TemplateArgs); 786 } 787 788 789 /// Determine whether we would be unable to instantiate this template (because 790 /// it either has no definition, or is in the process of being instantiated). 791 bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, 792 NamedDecl *Instantiation, 793 bool InstantiatedFromMember, 794 const NamedDecl *Pattern, 795 const NamedDecl *PatternDef, 796 TemplateSpecializationKind TSK, 797 bool Complain /*= true*/) { 798 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) || 799 isa<VarDecl>(Instantiation)); 800 801 bool IsEntityBeingDefined = false; 802 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef)) 803 IsEntityBeingDefined = TD->isBeingDefined(); 804 805 if (PatternDef && !IsEntityBeingDefined) { 806 NamedDecl *SuggestedDef = nullptr; 807 if (!hasReachableDefinition(const_cast<NamedDecl *>(PatternDef), 808 &SuggestedDef, 809 /*OnlyNeedComplete*/ false)) { 810 // If we're allowed to diagnose this and recover, do so. 811 bool Recover = Complain && !isSFINAEContext(); 812 if (Complain) 813 diagnoseMissingImport(PointOfInstantiation, SuggestedDef, 814 Sema::MissingImportKind::Definition, Recover); 815 return !Recover; 816 } 817 return false; 818 } 819 820 if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) 821 return true; 822 823 QualType InstantiationTy; 824 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation)) 825 InstantiationTy = Context.getTypeDeclType(TD); 826 if (PatternDef) { 827 Diag(PointOfInstantiation, 828 diag::err_template_instantiate_within_definition) 829 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation) 830 << InstantiationTy; 831 // Not much point in noting the template declaration here, since 832 // we're lexically inside it. 833 Instantiation->setInvalidDecl(); 834 } else if (InstantiatedFromMember) { 835 if (isa<FunctionDecl>(Instantiation)) { 836 Diag(PointOfInstantiation, 837 diag::err_explicit_instantiation_undefined_member) 838 << /*member function*/ 1 << Instantiation->getDeclName() 839 << Instantiation->getDeclContext(); 840 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here); 841 } else { 842 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!"); 843 Diag(PointOfInstantiation, 844 diag::err_implicit_instantiate_member_undefined) 845 << InstantiationTy; 846 Diag(Pattern->getLocation(), diag::note_member_declared_at); 847 } 848 } else { 849 if (isa<FunctionDecl>(Instantiation)) { 850 Diag(PointOfInstantiation, 851 diag::err_explicit_instantiation_undefined_func_template) 852 << Pattern; 853 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here); 854 } else if (isa<TagDecl>(Instantiation)) { 855 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined) 856 << (TSK != TSK_ImplicitInstantiation) 857 << InstantiationTy; 858 NoteTemplateLocation(*Pattern); 859 } else { 860 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!"); 861 if (isa<VarTemplateSpecializationDecl>(Instantiation)) { 862 Diag(PointOfInstantiation, 863 diag::err_explicit_instantiation_undefined_var_template) 864 << Instantiation; 865 Instantiation->setInvalidDecl(); 866 } else 867 Diag(PointOfInstantiation, 868 diag::err_explicit_instantiation_undefined_member) 869 << /*static data member*/ 2 << Instantiation->getDeclName() 870 << Instantiation->getDeclContext(); 871 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here); 872 } 873 } 874 875 // In general, Instantiation isn't marked invalid to get more than one 876 // error for multiple undefined instantiations. But the code that does 877 // explicit declaration -> explicit definition conversion can't handle 878 // invalid declarations, so mark as invalid in that case. 879 if (TSK == TSK_ExplicitInstantiationDeclaration) 880 Instantiation->setInvalidDecl(); 881 return true; 882 } 883 884 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining 885 /// that the template parameter 'PrevDecl' is being shadowed by a new 886 /// declaration at location Loc. Returns true to indicate that this is 887 /// an error, and false otherwise. 888 void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) { 889 assert(PrevDecl->isTemplateParameter() && "Not a template parameter"); 890 891 // C++ [temp.local]p4: 892 // A template-parameter shall not be redeclared within its 893 // scope (including nested scopes). 894 // 895 // Make this a warning when MSVC compatibility is requested. 896 unsigned DiagId = getLangOpts().MSVCCompat ? diag::ext_template_param_shadow 897 : diag::err_template_param_shadow; 898 const auto *ND = cast<NamedDecl>(PrevDecl); 899 Diag(Loc, DiagId) << ND->getDeclName(); 900 NoteTemplateParameterLocation(*ND); 901 } 902 903 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset 904 /// the parameter D to reference the templated declaration and return a pointer 905 /// to the template declaration. Otherwise, do nothing to D and return null. 906 TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) { 907 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) { 908 D = Temp->getTemplatedDecl(); 909 return Temp; 910 } 911 return nullptr; 912 } 913 914 ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion( 915 SourceLocation EllipsisLoc) const { 916 assert(Kind == Template && 917 "Only template template arguments can be pack expansions here"); 918 assert(getAsTemplate().get().containsUnexpandedParameterPack() && 919 "Template template argument pack expansion without packs"); 920 ParsedTemplateArgument Result(*this); 921 Result.EllipsisLoc = EllipsisLoc; 922 return Result; 923 } 924 925 static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef, 926 const ParsedTemplateArgument &Arg) { 927 928 switch (Arg.getKind()) { 929 case ParsedTemplateArgument::Type: { 930 TypeSourceInfo *DI; 931 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI); 932 if (!DI) 933 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation()); 934 return TemplateArgumentLoc(TemplateArgument(T), DI); 935 } 936 937 case ParsedTemplateArgument::NonType: { 938 Expr *E = static_cast<Expr *>(Arg.getAsExpr()); 939 return TemplateArgumentLoc(TemplateArgument(E), E); 940 } 941 942 case ParsedTemplateArgument::Template: { 943 TemplateName Template = Arg.getAsTemplate().get(); 944 TemplateArgument TArg; 945 if (Arg.getEllipsisLoc().isValid()) 946 TArg = TemplateArgument(Template, std::optional<unsigned int>()); 947 else 948 TArg = Template; 949 return TemplateArgumentLoc( 950 SemaRef.Context, TArg, 951 Arg.getScopeSpec().getWithLocInContext(SemaRef.Context), 952 Arg.getLocation(), Arg.getEllipsisLoc()); 953 } 954 } 955 956 llvm_unreachable("Unhandled parsed template argument"); 957 } 958 959 /// Translates template arguments as provided by the parser 960 /// into template arguments used by semantic analysis. 961 void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn, 962 TemplateArgumentListInfo &TemplateArgs) { 963 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I) 964 TemplateArgs.addArgument(translateTemplateArgument(*this, 965 TemplateArgsIn[I])); 966 } 967 968 static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S, 969 SourceLocation Loc, 970 IdentifierInfo *Name) { 971 NamedDecl *PrevDecl = SemaRef.LookupSingleName( 972 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 973 if (PrevDecl && PrevDecl->isTemplateParameter()) 974 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl); 975 } 976 977 /// Convert a parsed type into a parsed template argument. This is mostly 978 /// trivial, except that we may have parsed a C++17 deduced class template 979 /// specialization type, in which case we should form a template template 980 /// argument instead of a type template argument. 981 ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) { 982 TypeSourceInfo *TInfo; 983 QualType T = GetTypeFromParser(ParsedType.get(), &TInfo); 984 if (T.isNull()) 985 return ParsedTemplateArgument(); 986 assert(TInfo && "template argument with no location"); 987 988 // If we might have formed a deduced template specialization type, convert 989 // it to a template template argument. 990 if (getLangOpts().CPlusPlus17) { 991 TypeLoc TL = TInfo->getTypeLoc(); 992 SourceLocation EllipsisLoc; 993 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) { 994 EllipsisLoc = PET.getEllipsisLoc(); 995 TL = PET.getPatternLoc(); 996 } 997 998 CXXScopeSpec SS; 999 if (auto ET = TL.getAs<ElaboratedTypeLoc>()) { 1000 SS.Adopt(ET.getQualifierLoc()); 1001 TL = ET.getNamedTypeLoc(); 1002 } 1003 1004 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) { 1005 TemplateName Name = DTST.getTypePtr()->getTemplateName(); 1006 if (SS.isSet()) 1007 Name = Context.getQualifiedTemplateName(SS.getScopeRep(), 1008 /*HasTemplateKeyword=*/false, 1009 Name); 1010 ParsedTemplateArgument Result(SS, TemplateTy::make(Name), 1011 DTST.getTemplateNameLoc()); 1012 if (EllipsisLoc.isValid()) 1013 Result = Result.getTemplatePackExpansion(EllipsisLoc); 1014 return Result; 1015 } 1016 } 1017 1018 // This is a normal type template argument. Note, if the type template 1019 // argument is an injected-class-name for a template, it has a dual nature 1020 // and can be used as either a type or a template. We handle that in 1021 // convertTypeTemplateArgumentToTemplate. 1022 return ParsedTemplateArgument(ParsedTemplateArgument::Type, 1023 ParsedType.get().getAsOpaquePtr(), 1024 TInfo->getTypeLoc().getBeginLoc()); 1025 } 1026 1027 /// ActOnTypeParameter - Called when a C++ template type parameter 1028 /// (e.g., "typename T") has been parsed. Typename specifies whether 1029 /// the keyword "typename" was used to declare the type parameter 1030 /// (otherwise, "class" was used), and KeyLoc is the location of the 1031 /// "class" or "typename" keyword. ParamName is the name of the 1032 /// parameter (NULL indicates an unnamed template parameter) and 1033 /// ParamNameLoc is the location of the parameter name (if any). 1034 /// If the type parameter has a default argument, it will be added 1035 /// later via ActOnTypeParameterDefault. 1036 NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename, 1037 SourceLocation EllipsisLoc, 1038 SourceLocation KeyLoc, 1039 IdentifierInfo *ParamName, 1040 SourceLocation ParamNameLoc, 1041 unsigned Depth, unsigned Position, 1042 SourceLocation EqualLoc, 1043 ParsedType DefaultArg, 1044 bool HasTypeConstraint) { 1045 assert(S->isTemplateParamScope() && 1046 "Template type parameter not in template parameter scope!"); 1047 1048 bool IsParameterPack = EllipsisLoc.isValid(); 1049 TemplateTypeParmDecl *Param 1050 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(), 1051 KeyLoc, ParamNameLoc, Depth, Position, 1052 ParamName, Typename, IsParameterPack, 1053 HasTypeConstraint); 1054 Param->setAccess(AS_public); 1055 1056 if (Param->isParameterPack()) 1057 if (auto *LSI = getEnclosingLambda()) 1058 LSI->LocalPacks.push_back(Param); 1059 1060 if (ParamName) { 1061 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName); 1062 1063 // Add the template parameter into the current scope. 1064 S->AddDecl(Param); 1065 IdResolver.AddDecl(Param); 1066 } 1067 1068 // C++0x [temp.param]p9: 1069 // A default template-argument may be specified for any kind of 1070 // template-parameter that is not a template parameter pack. 1071 if (DefaultArg && IsParameterPack) { 1072 Diag(EqualLoc, diag::err_template_param_pack_default_arg); 1073 DefaultArg = nullptr; 1074 } 1075 1076 // Handle the default argument, if provided. 1077 if (DefaultArg) { 1078 TypeSourceInfo *DefaultTInfo; 1079 GetTypeFromParser(DefaultArg, &DefaultTInfo); 1080 1081 assert(DefaultTInfo && "expected source information for type"); 1082 1083 // Check for unexpanded parameter packs. 1084 if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo, 1085 UPPC_DefaultArgument)) 1086 return Param; 1087 1088 // Check the template argument itself. 1089 if (CheckTemplateArgument(DefaultTInfo)) { 1090 Param->setInvalidDecl(); 1091 return Param; 1092 } 1093 1094 Param->setDefaultArgument(DefaultTInfo); 1095 } 1096 1097 return Param; 1098 } 1099 1100 /// Convert the parser's template argument list representation into our form. 1101 static TemplateArgumentListInfo 1102 makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) { 1103 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc, 1104 TemplateId.RAngleLoc); 1105 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(), 1106 TemplateId.NumArgs); 1107 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs); 1108 return TemplateArgs; 1109 } 1110 1111 bool Sema::CheckTypeConstraint(TemplateIdAnnotation *TypeConstr) { 1112 1113 TemplateName TN = TypeConstr->Template.get(); 1114 ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl()); 1115 1116 // C++2a [temp.param]p4: 1117 // [...] The concept designated by a type-constraint shall be a type 1118 // concept ([temp.concept]). 1119 if (!CD->isTypeConcept()) { 1120 Diag(TypeConstr->TemplateNameLoc, 1121 diag::err_type_constraint_non_type_concept); 1122 return true; 1123 } 1124 1125 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid(); 1126 1127 if (!WereArgsSpecified && 1128 CD->getTemplateParameters()->getMinRequiredArguments() > 1) { 1129 Diag(TypeConstr->TemplateNameLoc, 1130 diag::err_type_constraint_missing_arguments) 1131 << CD; 1132 return true; 1133 } 1134 return false; 1135 } 1136 1137 bool Sema::ActOnTypeConstraint(const CXXScopeSpec &SS, 1138 TemplateIdAnnotation *TypeConstr, 1139 TemplateTypeParmDecl *ConstrainedParameter, 1140 SourceLocation EllipsisLoc) { 1141 return BuildTypeConstraint(SS, TypeConstr, ConstrainedParameter, EllipsisLoc, 1142 false); 1143 } 1144 1145 bool Sema::BuildTypeConstraint(const CXXScopeSpec &SS, 1146 TemplateIdAnnotation *TypeConstr, 1147 TemplateTypeParmDecl *ConstrainedParameter, 1148 SourceLocation EllipsisLoc, 1149 bool AllowUnexpandedPack) { 1150 1151 if (CheckTypeConstraint(TypeConstr)) 1152 return true; 1153 1154 TemplateName TN = TypeConstr->Template.get(); 1155 ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl()); 1156 1157 DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name), 1158 TypeConstr->TemplateNameLoc); 1159 1160 TemplateArgumentListInfo TemplateArgs; 1161 if (TypeConstr->LAngleLoc.isValid()) { 1162 TemplateArgs = 1163 makeTemplateArgumentListInfo(*this, *TypeConstr); 1164 1165 if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) { 1166 for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) { 1167 if (DiagnoseUnexpandedParameterPack(Arg, UPPC_TypeConstraint)) 1168 return true; 1169 } 1170 } 1171 } 1172 return AttachTypeConstraint( 1173 SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc(), 1174 ConceptName, CD, 1175 TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr, 1176 ConstrainedParameter, EllipsisLoc); 1177 } 1178 1179 template<typename ArgumentLocAppender> 1180 static ExprResult formImmediatelyDeclaredConstraint( 1181 Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, 1182 ConceptDecl *NamedConcept, SourceLocation LAngleLoc, 1183 SourceLocation RAngleLoc, QualType ConstrainedType, 1184 SourceLocation ParamNameLoc, ArgumentLocAppender Appender, 1185 SourceLocation EllipsisLoc) { 1186 1187 TemplateArgumentListInfo ConstraintArgs; 1188 ConstraintArgs.addArgument( 1189 S.getTrivialTemplateArgumentLoc(TemplateArgument(ConstrainedType), 1190 /*NTTPType=*/QualType(), ParamNameLoc)); 1191 1192 ConstraintArgs.setRAngleLoc(RAngleLoc); 1193 ConstraintArgs.setLAngleLoc(LAngleLoc); 1194 Appender(ConstraintArgs); 1195 1196 // C++2a [temp.param]p4: 1197 // [...] This constraint-expression E is called the immediately-declared 1198 // constraint of T. [...] 1199 CXXScopeSpec SS; 1200 SS.Adopt(NS); 1201 ExprResult ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId( 1202 SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo, 1203 /*FoundDecl=*/NamedConcept, NamedConcept, &ConstraintArgs); 1204 if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid()) 1205 return ImmediatelyDeclaredConstraint; 1206 1207 // C++2a [temp.param]p4: 1208 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...). 1209 // 1210 // We have the following case: 1211 // 1212 // template<typename T> concept C1 = true; 1213 // template<C1... T> struct s1; 1214 // 1215 // The constraint: (C1<T> && ...) 1216 // 1217 // Note that the type of C1<T> is known to be 'bool', so we don't need to do 1218 // any unqualified lookups for 'operator&&' here. 1219 return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr, 1220 /*LParenLoc=*/SourceLocation(), 1221 ImmediatelyDeclaredConstraint.get(), BO_LAnd, 1222 EllipsisLoc, /*RHS=*/nullptr, 1223 /*RParenLoc=*/SourceLocation(), 1224 /*NumExpansions=*/std::nullopt); 1225 } 1226 1227 /// Attach a type-constraint to a template parameter. 1228 /// \returns true if an error occurred. This can happen if the 1229 /// immediately-declared constraint could not be formed (e.g. incorrect number 1230 /// of arguments for the named concept). 1231 bool Sema::AttachTypeConstraint(NestedNameSpecifierLoc NS, 1232 DeclarationNameInfo NameInfo, 1233 ConceptDecl *NamedConcept, 1234 const TemplateArgumentListInfo *TemplateArgs, 1235 TemplateTypeParmDecl *ConstrainedParameter, 1236 SourceLocation EllipsisLoc) { 1237 // C++2a [temp.param]p4: 1238 // [...] If Q is of the form C<A1, ..., An>, then let E' be 1239 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...] 1240 const ASTTemplateArgumentListInfo *ArgsAsWritten = 1241 TemplateArgs ? ASTTemplateArgumentListInfo::Create(Context, 1242 *TemplateArgs) : nullptr; 1243 1244 QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0); 1245 1246 ExprResult ImmediatelyDeclaredConstraint = 1247 formImmediatelyDeclaredConstraint( 1248 *this, NS, NameInfo, NamedConcept, 1249 TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(), 1250 TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(), 1251 ParamAsArgument, ConstrainedParameter->getLocation(), 1252 [&] (TemplateArgumentListInfo &ConstraintArgs) { 1253 if (TemplateArgs) 1254 for (const auto &ArgLoc : TemplateArgs->arguments()) 1255 ConstraintArgs.addArgument(ArgLoc); 1256 }, EllipsisLoc); 1257 if (ImmediatelyDeclaredConstraint.isInvalid()) 1258 return true; 1259 1260 auto *CL = ConceptReference::Create(Context, /*NNS=*/NS, 1261 /*TemplateKWLoc=*/SourceLocation{}, 1262 /*ConceptNameInfo=*/NameInfo, 1263 /*FoundDecl=*/NamedConcept, 1264 /*NamedConcept=*/NamedConcept, 1265 /*ArgsWritten=*/ArgsAsWritten); 1266 ConstrainedParameter->setTypeConstraint(CL, 1267 ImmediatelyDeclaredConstraint.get()); 1268 return false; 1269 } 1270 1271 bool Sema::AttachTypeConstraint(AutoTypeLoc TL, 1272 NonTypeTemplateParmDecl *NewConstrainedParm, 1273 NonTypeTemplateParmDecl *OrigConstrainedParm, 1274 SourceLocation EllipsisLoc) { 1275 if (NewConstrainedParm->getType() != TL.getType() || 1276 TL.getAutoKeyword() != AutoTypeKeyword::Auto) { 1277 Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 1278 diag::err_unsupported_placeholder_constraint) 1279 << NewConstrainedParm->getTypeSourceInfo() 1280 ->getTypeLoc() 1281 .getSourceRange(); 1282 return true; 1283 } 1284 // FIXME: Concepts: This should be the type of the placeholder, but this is 1285 // unclear in the wording right now. 1286 DeclRefExpr *Ref = 1287 BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(), 1288 VK_PRValue, OrigConstrainedParm->getLocation()); 1289 if (!Ref) 1290 return true; 1291 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint( 1292 *this, TL.getNestedNameSpecifierLoc(), TL.getConceptNameInfo(), 1293 TL.getNamedConcept(), TL.getLAngleLoc(), TL.getRAngleLoc(), 1294 BuildDecltypeType(Ref), OrigConstrainedParm->getLocation(), 1295 [&](TemplateArgumentListInfo &ConstraintArgs) { 1296 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I) 1297 ConstraintArgs.addArgument(TL.getArgLoc(I)); 1298 }, 1299 EllipsisLoc); 1300 if (ImmediatelyDeclaredConstraint.isInvalid() || 1301 !ImmediatelyDeclaredConstraint.isUsable()) 1302 return true; 1303 1304 NewConstrainedParm->setPlaceholderTypeConstraint( 1305 ImmediatelyDeclaredConstraint.get()); 1306 return false; 1307 } 1308 1309 /// Check that the type of a non-type template parameter is 1310 /// well-formed. 1311 /// 1312 /// \returns the (possibly-promoted) parameter type if valid; 1313 /// otherwise, produces a diagnostic and returns a NULL type. 1314 QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, 1315 SourceLocation Loc) { 1316 if (TSI->getType()->isUndeducedType()) { 1317 // C++17 [temp.dep.expr]p3: 1318 // An id-expression is type-dependent if it contains 1319 // - an identifier associated by name lookup with a non-type 1320 // template-parameter declared with a type that contains a 1321 // placeholder type (7.1.7.4), 1322 TSI = SubstAutoTypeSourceInfoDependent(TSI); 1323 } 1324 1325 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc); 1326 } 1327 1328 /// Require the given type to be a structural type, and diagnose if it is not. 1329 /// 1330 /// \return \c true if an error was produced. 1331 bool Sema::RequireStructuralType(QualType T, SourceLocation Loc) { 1332 if (T->isDependentType()) 1333 return false; 1334 1335 if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete)) 1336 return true; 1337 1338 if (T->isStructuralType()) 1339 return false; 1340 1341 // Structural types are required to be object types or lvalue references. 1342 if (T->isRValueReferenceType()) { 1343 Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T; 1344 return true; 1345 } 1346 1347 // Don't mention structural types in our diagnostic prior to C++20. Also, 1348 // there's not much more we can say about non-scalar non-class types -- 1349 // because we can't see functions or arrays here, those can only be language 1350 // extensions. 1351 if (!getLangOpts().CPlusPlus20 || 1352 (!T->isScalarType() && !T->isRecordType())) { 1353 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T; 1354 return true; 1355 } 1356 1357 // Structural types are required to be literal types. 1358 if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal)) 1359 return true; 1360 1361 Diag(Loc, diag::err_template_nontype_parm_not_structural) << T; 1362 1363 // Drill down into the reason why the class is non-structural. 1364 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { 1365 // All members are required to be public and non-mutable, and can't be of 1366 // rvalue reference type. Check these conditions first to prefer a "local" 1367 // reason over a more distant one. 1368 for (const FieldDecl *FD : RD->fields()) { 1369 if (FD->getAccess() != AS_public) { 1370 Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0; 1371 return true; 1372 } 1373 if (FD->isMutable()) { 1374 Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T; 1375 return true; 1376 } 1377 if (FD->getType()->isRValueReferenceType()) { 1378 Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field) 1379 << T; 1380 return true; 1381 } 1382 } 1383 1384 // All bases are required to be public. 1385 for (const auto &BaseSpec : RD->bases()) { 1386 if (BaseSpec.getAccessSpecifier() != AS_public) { 1387 Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public) 1388 << T << 1; 1389 return true; 1390 } 1391 } 1392 1393 // All subobjects are required to be of structural types. 1394 SourceLocation SubLoc; 1395 QualType SubType; 1396 int Kind = -1; 1397 1398 for (const FieldDecl *FD : RD->fields()) { 1399 QualType T = Context.getBaseElementType(FD->getType()); 1400 if (!T->isStructuralType()) { 1401 SubLoc = FD->getLocation(); 1402 SubType = T; 1403 Kind = 0; 1404 break; 1405 } 1406 } 1407 1408 if (Kind == -1) { 1409 for (const auto &BaseSpec : RD->bases()) { 1410 QualType T = BaseSpec.getType(); 1411 if (!T->isStructuralType()) { 1412 SubLoc = BaseSpec.getBaseTypeLoc(); 1413 SubType = T; 1414 Kind = 1; 1415 break; 1416 } 1417 } 1418 } 1419 1420 assert(Kind != -1 && "couldn't find reason why type is not structural"); 1421 Diag(SubLoc, diag::note_not_structural_subobject) 1422 << T << Kind << SubType; 1423 T = SubType; 1424 RD = T->getAsCXXRecordDecl(); 1425 } 1426 1427 return true; 1428 } 1429 1430 QualType Sema::CheckNonTypeTemplateParameterType(QualType T, 1431 SourceLocation Loc) { 1432 // We don't allow variably-modified types as the type of non-type template 1433 // parameters. 1434 if (T->isVariablyModifiedType()) { 1435 Diag(Loc, diag::err_variably_modified_nontype_template_param) 1436 << T; 1437 return QualType(); 1438 } 1439 1440 // C++ [temp.param]p4: 1441 // 1442 // A non-type template-parameter shall have one of the following 1443 // (optionally cv-qualified) types: 1444 // 1445 // -- integral or enumeration type, 1446 if (T->isIntegralOrEnumerationType() || 1447 // -- pointer to object or pointer to function, 1448 T->isPointerType() || 1449 // -- lvalue reference to object or lvalue reference to function, 1450 T->isLValueReferenceType() || 1451 // -- pointer to member, 1452 T->isMemberPointerType() || 1453 // -- std::nullptr_t, or 1454 T->isNullPtrType() || 1455 // -- a type that contains a placeholder type. 1456 T->isUndeducedType()) { 1457 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter 1458 // are ignored when determining its type. 1459 return T.getUnqualifiedType(); 1460 } 1461 1462 // C++ [temp.param]p8: 1463 // 1464 // A non-type template-parameter of type "array of T" or 1465 // "function returning T" is adjusted to be of type "pointer to 1466 // T" or "pointer to function returning T", respectively. 1467 if (T->isArrayType() || T->isFunctionType()) 1468 return Context.getDecayedType(T); 1469 1470 // If T is a dependent type, we can't do the check now, so we 1471 // assume that it is well-formed. Note that stripping off the 1472 // qualifiers here is not really correct if T turns out to be 1473 // an array type, but we'll recompute the type everywhere it's 1474 // used during instantiation, so that should be OK. (Using the 1475 // qualified type is equally wrong.) 1476 if (T->isDependentType()) 1477 return T.getUnqualifiedType(); 1478 1479 // C++20 [temp.param]p6: 1480 // -- a structural type 1481 if (RequireStructuralType(T, Loc)) 1482 return QualType(); 1483 1484 if (!getLangOpts().CPlusPlus20) { 1485 // FIXME: Consider allowing structural types as an extension in C++17. (In 1486 // earlier language modes, the template argument evaluation rules are too 1487 // inflexible.) 1488 Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T; 1489 return QualType(); 1490 } 1491 1492 Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T; 1493 return T.getUnqualifiedType(); 1494 } 1495 1496 NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, 1497 unsigned Depth, 1498 unsigned Position, 1499 SourceLocation EqualLoc, 1500 Expr *Default) { 1501 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 1502 1503 // Check that we have valid decl-specifiers specified. 1504 auto CheckValidDeclSpecifiers = [this, &D] { 1505 // C++ [temp.param] 1506 // p1 1507 // template-parameter: 1508 // ... 1509 // parameter-declaration 1510 // p2 1511 // ... A storage class shall not be specified in a template-parameter 1512 // declaration. 1513 // [dcl.typedef]p1: 1514 // The typedef specifier [...] shall not be used in the decl-specifier-seq 1515 // of a parameter-declaration 1516 const DeclSpec &DS = D.getDeclSpec(); 1517 auto EmitDiag = [this](SourceLocation Loc) { 1518 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm) 1519 << FixItHint::CreateRemoval(Loc); 1520 }; 1521 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) 1522 EmitDiag(DS.getStorageClassSpecLoc()); 1523 1524 if (DS.getThreadStorageClassSpec() != TSCS_unspecified) 1525 EmitDiag(DS.getThreadStorageClassSpecLoc()); 1526 1527 // [dcl.inline]p1: 1528 // The inline specifier can be applied only to the declaration or 1529 // definition of a variable or function. 1530 1531 if (DS.isInlineSpecified()) 1532 EmitDiag(DS.getInlineSpecLoc()); 1533 1534 // [dcl.constexpr]p1: 1535 // The constexpr specifier shall be applied only to the definition of a 1536 // variable or variable template or the declaration of a function or 1537 // function template. 1538 1539 if (DS.hasConstexprSpecifier()) 1540 EmitDiag(DS.getConstexprSpecLoc()); 1541 1542 // [dcl.fct.spec]p1: 1543 // Function-specifiers can be used only in function declarations. 1544 1545 if (DS.isVirtualSpecified()) 1546 EmitDiag(DS.getVirtualSpecLoc()); 1547 1548 if (DS.hasExplicitSpecifier()) 1549 EmitDiag(DS.getExplicitSpecLoc()); 1550 1551 if (DS.isNoreturnSpecified()) 1552 EmitDiag(DS.getNoreturnSpecLoc()); 1553 }; 1554 1555 CheckValidDeclSpecifiers(); 1556 1557 if (const auto *T = TInfo->getType()->getContainedDeducedType()) 1558 if (isa<AutoType>(T)) 1559 Diag(D.getIdentifierLoc(), 1560 diag::warn_cxx14_compat_template_nontype_parm_auto_type) 1561 << QualType(TInfo->getType()->getContainedAutoType(), 0); 1562 1563 assert(S->isTemplateParamScope() && 1564 "Non-type template parameter not in template parameter scope!"); 1565 bool Invalid = false; 1566 1567 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc()); 1568 if (T.isNull()) { 1569 T = Context.IntTy; // Recover with an 'int' type. 1570 Invalid = true; 1571 } 1572 1573 CheckFunctionOrTemplateParamDeclarator(S, D); 1574 1575 IdentifierInfo *ParamName = D.getIdentifier(); 1576 bool IsParameterPack = D.hasEllipsis(); 1577 NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create( 1578 Context, Context.getTranslationUnitDecl(), D.getBeginLoc(), 1579 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack, 1580 TInfo); 1581 Param->setAccess(AS_public); 1582 1583 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) 1584 if (TL.isConstrained()) 1585 if (AttachTypeConstraint(TL, Param, Param, D.getEllipsisLoc())) 1586 Invalid = true; 1587 1588 if (Invalid) 1589 Param->setInvalidDecl(); 1590 1591 if (Param->isParameterPack()) 1592 if (auto *LSI = getEnclosingLambda()) 1593 LSI->LocalPacks.push_back(Param); 1594 1595 if (ParamName) { 1596 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(), 1597 ParamName); 1598 1599 // Add the template parameter into the current scope. 1600 S->AddDecl(Param); 1601 IdResolver.AddDecl(Param); 1602 } 1603 1604 // C++0x [temp.param]p9: 1605 // A default template-argument may be specified for any kind of 1606 // template-parameter that is not a template parameter pack. 1607 if (Default && IsParameterPack) { 1608 Diag(EqualLoc, diag::err_template_param_pack_default_arg); 1609 Default = nullptr; 1610 } 1611 1612 // Check the well-formedness of the default template argument, if provided. 1613 if (Default) { 1614 // Check for unexpanded parameter packs. 1615 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument)) 1616 return Param; 1617 1618 Param->setDefaultArgument(Default); 1619 } 1620 1621 return Param; 1622 } 1623 1624 /// ActOnTemplateTemplateParameter - Called when a C++ template template 1625 /// parameter (e.g. T in template <template \<typename> class T> class array) 1626 /// has been parsed. S is the current scope. 1627 NamedDecl *Sema::ActOnTemplateTemplateParameter(Scope* S, 1628 SourceLocation TmpLoc, 1629 TemplateParameterList *Params, 1630 SourceLocation EllipsisLoc, 1631 IdentifierInfo *Name, 1632 SourceLocation NameLoc, 1633 unsigned Depth, 1634 unsigned Position, 1635 SourceLocation EqualLoc, 1636 ParsedTemplateArgument Default) { 1637 assert(S->isTemplateParamScope() && 1638 "Template template parameter not in template parameter scope!"); 1639 1640 // Construct the parameter object. 1641 bool IsParameterPack = EllipsisLoc.isValid(); 1642 TemplateTemplateParmDecl *Param = 1643 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(), 1644 NameLoc.isInvalid()? TmpLoc : NameLoc, 1645 Depth, Position, IsParameterPack, 1646 Name, Params); 1647 Param->setAccess(AS_public); 1648 1649 if (Param->isParameterPack()) 1650 if (auto *LSI = getEnclosingLambda()) 1651 LSI->LocalPacks.push_back(Param); 1652 1653 // If the template template parameter has a name, then link the identifier 1654 // into the scope and lookup mechanisms. 1655 if (Name) { 1656 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name); 1657 1658 S->AddDecl(Param); 1659 IdResolver.AddDecl(Param); 1660 } 1661 1662 if (Params->size() == 0) { 1663 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms) 1664 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc()); 1665 Param->setInvalidDecl(); 1666 } 1667 1668 // C++0x [temp.param]p9: 1669 // A default template-argument may be specified for any kind of 1670 // template-parameter that is not a template parameter pack. 1671 if (IsParameterPack && !Default.isInvalid()) { 1672 Diag(EqualLoc, diag::err_template_param_pack_default_arg); 1673 Default = ParsedTemplateArgument(); 1674 } 1675 1676 if (!Default.isInvalid()) { 1677 // Check only that we have a template template argument. We don't want to 1678 // try to check well-formedness now, because our template template parameter 1679 // might have dependent types in its template parameters, which we wouldn't 1680 // be able to match now. 1681 // 1682 // If none of the template template parameter's template arguments mention 1683 // other template parameters, we could actually perform more checking here. 1684 // However, it isn't worth doing. 1685 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default); 1686 if (DefaultArg.getArgument().getAsTemplate().isNull()) { 1687 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template) 1688 << DefaultArg.getSourceRange(); 1689 return Param; 1690 } 1691 1692 // Check for unexpanded parameter packs. 1693 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(), 1694 DefaultArg.getArgument().getAsTemplate(), 1695 UPPC_DefaultArgument)) 1696 return Param; 1697 1698 Param->setDefaultArgument(Context, DefaultArg); 1699 } 1700 1701 return Param; 1702 } 1703 1704 namespace { 1705 class ConstraintRefersToContainingTemplateChecker 1706 : public TreeTransform<ConstraintRefersToContainingTemplateChecker> { 1707 bool Result = false; 1708 const FunctionDecl *Friend = nullptr; 1709 unsigned TemplateDepth = 0; 1710 1711 // Check a record-decl that we've seen to see if it is a lexical parent of the 1712 // Friend, likely because it was referred to without its template arguments. 1713 void CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) { 1714 CheckingRD = CheckingRD->getMostRecentDecl(); 1715 if (!CheckingRD->isTemplated()) 1716 return; 1717 1718 for (const DeclContext *DC = Friend->getLexicalDeclContext(); 1719 DC && !DC->isFileContext(); DC = DC->getParent()) 1720 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 1721 if (CheckingRD == RD->getMostRecentDecl()) 1722 Result = true; 1723 } 1724 1725 void CheckNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) { 1726 assert(D->getDepth() <= TemplateDepth && 1727 "Nothing should reference a value below the actual template depth, " 1728 "depth is likely wrong"); 1729 if (D->getDepth() != TemplateDepth) 1730 Result = true; 1731 1732 // Necessary because the type of the NTTP might be what refers to the parent 1733 // constriant. 1734 TransformType(D->getType()); 1735 } 1736 1737 public: 1738 using inherited = TreeTransform<ConstraintRefersToContainingTemplateChecker>; 1739 1740 ConstraintRefersToContainingTemplateChecker(Sema &SemaRef, 1741 const FunctionDecl *Friend, 1742 unsigned TemplateDepth) 1743 : inherited(SemaRef), Friend(Friend), TemplateDepth(TemplateDepth) {} 1744 bool getResult() const { return Result; } 1745 1746 // This should be the only template parm type that we have to deal with. 1747 // SubstTempalteTypeParmPack, SubstNonTypeTemplateParmPack, and 1748 // FunctionParmPackExpr are all partially substituted, which cannot happen 1749 // with concepts at this point in translation. 1750 using inherited::TransformTemplateTypeParmType; 1751 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB, 1752 TemplateTypeParmTypeLoc TL, bool) { 1753 assert(TL.getDecl()->getDepth() <= TemplateDepth && 1754 "Nothing should reference a value below the actual template depth, " 1755 "depth is likely wrong"); 1756 if (TL.getDecl()->getDepth() != TemplateDepth) 1757 Result = true; 1758 return inherited::TransformTemplateTypeParmType( 1759 TLB, TL, 1760 /*SuppressObjCLifetime=*/false); 1761 } 1762 1763 Decl *TransformDecl(SourceLocation Loc, Decl *D) { 1764 if (!D) 1765 return D; 1766 // FIXME : This is possibly an incomplete list, but it is unclear what other 1767 // Decl kinds could be used to refer to the template parameters. This is a 1768 // best guess so far based on examples currently available, but the 1769 // unreachable should catch future instances/cases. 1770 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) 1771 TransformType(TD->getUnderlyingType()); 1772 else if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(D)) 1773 CheckNonTypeTemplateParmDecl(NTTPD); 1774 else if (auto *VD = dyn_cast<ValueDecl>(D)) 1775 TransformType(VD->getType()); 1776 else if (auto *TD = dyn_cast<TemplateDecl>(D)) 1777 TransformTemplateParameterList(TD->getTemplateParameters()); 1778 else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) 1779 CheckIfContainingRecord(RD); 1780 else if (isa<NamedDecl>(D)) { 1781 // No direct types to visit here I believe. 1782 } else 1783 llvm_unreachable("Don't know how to handle this declaration type yet"); 1784 return D; 1785 } 1786 }; 1787 } // namespace 1788 1789 bool Sema::ConstraintExpressionDependsOnEnclosingTemplate( 1790 const FunctionDecl *Friend, unsigned TemplateDepth, 1791 const Expr *Constraint) { 1792 assert(Friend->getFriendObjectKind() && "Only works on a friend"); 1793 ConstraintRefersToContainingTemplateChecker Checker(*this, Friend, 1794 TemplateDepth); 1795 Checker.TransformExpr(const_cast<Expr *>(Constraint)); 1796 return Checker.getResult(); 1797 } 1798 1799 /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally 1800 /// constrained by RequiresClause, that contains the template parameters in 1801 /// Params. 1802 TemplateParameterList * 1803 Sema::ActOnTemplateParameterList(unsigned Depth, 1804 SourceLocation ExportLoc, 1805 SourceLocation TemplateLoc, 1806 SourceLocation LAngleLoc, 1807 ArrayRef<NamedDecl *> Params, 1808 SourceLocation RAngleLoc, 1809 Expr *RequiresClause) { 1810 if (ExportLoc.isValid()) 1811 Diag(ExportLoc, diag::warn_template_export_unsupported); 1812 1813 for (NamedDecl *P : Params) 1814 warnOnReservedIdentifier(P); 1815 1816 return TemplateParameterList::Create( 1817 Context, TemplateLoc, LAngleLoc, 1818 llvm::ArrayRef(Params.data(), Params.size()), RAngleLoc, RequiresClause); 1819 } 1820 1821 static void SetNestedNameSpecifier(Sema &S, TagDecl *T, 1822 const CXXScopeSpec &SS) { 1823 if (SS.isSet()) 1824 T->setQualifierInfo(SS.getWithLocInContext(S.Context)); 1825 } 1826 1827 // Returns the template parameter list with all default template argument 1828 // information. 1829 static TemplateParameterList *GetTemplateParameterList(TemplateDecl *TD) { 1830 // Make sure we get the template parameter list from the most 1831 // recent declaration, since that is the only one that is guaranteed to 1832 // have all the default template argument information. 1833 return cast<TemplateDecl>(TD->getMostRecentDecl())->getTemplateParameters(); 1834 } 1835 1836 DeclResult Sema::CheckClassTemplate( 1837 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, 1838 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, 1839 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, 1840 AccessSpecifier AS, SourceLocation ModulePrivateLoc, 1841 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, 1842 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) { 1843 assert(TemplateParams && TemplateParams->size() > 0 && 1844 "No template parameters"); 1845 assert(TUK != TUK_Reference && "Can only declare or define class templates"); 1846 bool Invalid = false; 1847 1848 // Check that we can declare a template here. 1849 if (CheckTemplateDeclScope(S, TemplateParams)) 1850 return true; 1851 1852 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 1853 assert(Kind != TagTypeKind::Enum && 1854 "can't build template of enumerated type"); 1855 1856 // There is no such thing as an unnamed class template. 1857 if (!Name) { 1858 Diag(KWLoc, diag::err_template_unnamed_class); 1859 return true; 1860 } 1861 1862 // Find any previous declaration with this name. For a friend with no 1863 // scope explicitly specified, we only look for tag declarations (per 1864 // C++11 [basic.lookup.elab]p2). 1865 DeclContext *SemanticContext; 1866 LookupResult Previous(*this, Name, NameLoc, 1867 (SS.isEmpty() && TUK == TUK_Friend) 1868 ? LookupTagName : LookupOrdinaryName, 1869 forRedeclarationInCurContext()); 1870 if (SS.isNotEmpty() && !SS.isInvalid()) { 1871 SemanticContext = computeDeclContext(SS, true); 1872 if (!SemanticContext) { 1873 // FIXME: Horrible, horrible hack! We can't currently represent this 1874 // in the AST, and historically we have just ignored such friend 1875 // class templates, so don't complain here. 1876 Diag(NameLoc, TUK == TUK_Friend 1877 ? diag::warn_template_qualified_friend_ignored 1878 : diag::err_template_qualified_declarator_no_match) 1879 << SS.getScopeRep() << SS.getRange(); 1880 return TUK != TUK_Friend; 1881 } 1882 1883 if (RequireCompleteDeclContext(SS, SemanticContext)) 1884 return true; 1885 1886 // If we're adding a template to a dependent context, we may need to 1887 // rebuilding some of the types used within the template parameter list, 1888 // now that we know what the current instantiation is. 1889 if (SemanticContext->isDependentContext()) { 1890 ContextRAII SavedContext(*this, SemanticContext); 1891 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 1892 Invalid = true; 1893 } else if (TUK != TUK_Friend && TUK != TUK_Reference) 1894 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc, false); 1895 1896 LookupQualifiedName(Previous, SemanticContext); 1897 } else { 1898 SemanticContext = CurContext; 1899 1900 // C++14 [class.mem]p14: 1901 // If T is the name of a class, then each of the following shall have a 1902 // name different from T: 1903 // -- every member template of class T 1904 if (TUK != TUK_Friend && 1905 DiagnoseClassNameShadow(SemanticContext, 1906 DeclarationNameInfo(Name, NameLoc))) 1907 return true; 1908 1909 LookupName(Previous, S); 1910 } 1911 1912 if (Previous.isAmbiguous()) 1913 return true; 1914 1915 NamedDecl *PrevDecl = nullptr; 1916 if (Previous.begin() != Previous.end()) 1917 PrevDecl = (*Previous.begin())->getUnderlyingDecl(); 1918 1919 if (PrevDecl && PrevDecl->isTemplateParameter()) { 1920 // Maybe we will complain about the shadowed template parameter. 1921 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl); 1922 // Just pretend that we didn't see the previous declaration. 1923 PrevDecl = nullptr; 1924 } 1925 1926 // If there is a previous declaration with the same name, check 1927 // whether this is a valid redeclaration. 1928 ClassTemplateDecl *PrevClassTemplate = 1929 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl); 1930 1931 // We may have found the injected-class-name of a class template, 1932 // class template partial specialization, or class template specialization. 1933 // In these cases, grab the template that is being defined or specialized. 1934 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) && 1935 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) { 1936 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext()); 1937 PrevClassTemplate 1938 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate(); 1939 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) { 1940 PrevClassTemplate 1941 = cast<ClassTemplateSpecializationDecl>(PrevDecl) 1942 ->getSpecializedTemplate(); 1943 } 1944 } 1945 1946 if (TUK == TUK_Friend) { 1947 // C++ [namespace.memdef]p3: 1948 // [...] When looking for a prior declaration of a class or a function 1949 // declared as a friend, and when the name of the friend class or 1950 // function is neither a qualified name nor a template-id, scopes outside 1951 // the innermost enclosing namespace scope are not considered. 1952 if (!SS.isSet()) { 1953 DeclContext *OutermostContext = CurContext; 1954 while (!OutermostContext->isFileContext()) 1955 OutermostContext = OutermostContext->getLookupParent(); 1956 1957 if (PrevDecl && 1958 (OutermostContext->Equals(PrevDecl->getDeclContext()) || 1959 OutermostContext->Encloses(PrevDecl->getDeclContext()))) { 1960 SemanticContext = PrevDecl->getDeclContext(); 1961 } else { 1962 // Declarations in outer scopes don't matter. However, the outermost 1963 // context we computed is the semantic context for our new 1964 // declaration. 1965 PrevDecl = PrevClassTemplate = nullptr; 1966 SemanticContext = OutermostContext; 1967 1968 // Check that the chosen semantic context doesn't already contain a 1969 // declaration of this name as a non-tag type. 1970 Previous.clear(LookupOrdinaryName); 1971 DeclContext *LookupContext = SemanticContext; 1972 while (LookupContext->isTransparentContext()) 1973 LookupContext = LookupContext->getLookupParent(); 1974 LookupQualifiedName(Previous, LookupContext); 1975 1976 if (Previous.isAmbiguous()) 1977 return true; 1978 1979 if (Previous.begin() != Previous.end()) 1980 PrevDecl = (*Previous.begin())->getUnderlyingDecl(); 1981 } 1982 } 1983 } else if (PrevDecl && 1984 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext, 1985 S, SS.isValid())) 1986 PrevDecl = PrevClassTemplate = nullptr; 1987 1988 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>( 1989 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) { 1990 if (SS.isEmpty() && 1991 !(PrevClassTemplate && 1992 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals( 1993 SemanticContext->getRedeclContext()))) { 1994 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 1995 Diag(Shadow->getTargetDecl()->getLocation(), 1996 diag::note_using_decl_target); 1997 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0; 1998 // Recover by ignoring the old declaration. 1999 PrevDecl = PrevClassTemplate = nullptr; 2000 } 2001 } 2002 2003 if (PrevClassTemplate) { 2004 // Ensure that the template parameter lists are compatible. Skip this check 2005 // for a friend in a dependent context: the template parameter list itself 2006 // could be dependent. 2007 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) && 2008 !TemplateParameterListsAreEqual( 2009 TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext 2010 : CurContext, 2011 CurContext, KWLoc), 2012 TemplateParams, PrevClassTemplate, 2013 PrevClassTemplate->getTemplateParameters(), /*Complain=*/true, 2014 TPL_TemplateMatch)) 2015 return true; 2016 2017 // C++ [temp.class]p4: 2018 // In a redeclaration, partial specialization, explicit 2019 // specialization or explicit instantiation of a class template, 2020 // the class-key shall agree in kind with the original class 2021 // template declaration (7.1.5.3). 2022 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl(); 2023 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, 2024 TUK == TUK_Definition, KWLoc, Name)) { 2025 Diag(KWLoc, diag::err_use_with_wrong_tag) 2026 << Name 2027 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName()); 2028 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use); 2029 Kind = PrevRecordDecl->getTagKind(); 2030 } 2031 2032 // Check for redefinition of this class template. 2033 if (TUK == TUK_Definition) { 2034 if (TagDecl *Def = PrevRecordDecl->getDefinition()) { 2035 // If we have a prior definition that is not visible, treat this as 2036 // simply making that previous definition visible. 2037 NamedDecl *Hidden = nullptr; 2038 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 2039 SkipBody->ShouldSkip = true; 2040 SkipBody->Previous = Def; 2041 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate(); 2042 assert(Tmpl && "original definition of a class template is not a " 2043 "class template?"); 2044 makeMergedDefinitionVisible(Hidden); 2045 makeMergedDefinitionVisible(Tmpl); 2046 } else { 2047 Diag(NameLoc, diag::err_redefinition) << Name; 2048 Diag(Def->getLocation(), diag::note_previous_definition); 2049 // FIXME: Would it make sense to try to "forget" the previous 2050 // definition, as part of error recovery? 2051 return true; 2052 } 2053 } 2054 } 2055 } else if (PrevDecl) { 2056 // C++ [temp]p5: 2057 // A class template shall not have the same name as any other 2058 // template, class, function, object, enumeration, enumerator, 2059 // namespace, or type in the same scope (3.3), except as specified 2060 // in (14.5.4). 2061 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 2062 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 2063 return true; 2064 } 2065 2066 // Check the template parameter list of this declaration, possibly 2067 // merging in the template parameter list from the previous class 2068 // template declaration. Skip this check for a friend in a dependent 2069 // context, because the template parameter list might be dependent. 2070 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) && 2071 CheckTemplateParameterList( 2072 TemplateParams, 2073 PrevClassTemplate ? GetTemplateParameterList(PrevClassTemplate) 2074 : nullptr, 2075 (SS.isSet() && SemanticContext && SemanticContext->isRecord() && 2076 SemanticContext->isDependentContext()) 2077 ? TPC_ClassTemplateMember 2078 : TUK == TUK_Friend ? TPC_FriendClassTemplate 2079 : TPC_ClassTemplate, 2080 SkipBody)) 2081 Invalid = true; 2082 2083 if (SS.isSet()) { 2084 // If the name of the template was qualified, we must be defining the 2085 // template out-of-line. 2086 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) { 2087 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match 2088 : diag::err_member_decl_does_not_match) 2089 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange(); 2090 Invalid = true; 2091 } 2092 } 2093 2094 // If this is a templated friend in a dependent context we should not put it 2095 // on the redecl chain. In some cases, the templated friend can be the most 2096 // recent declaration tricking the template instantiator to make substitutions 2097 // there. 2098 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious 2099 bool ShouldAddRedecl 2100 = !(TUK == TUK_Friend && CurContext->isDependentContext()); 2101 2102 CXXRecordDecl *NewClass = 2103 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name, 2104 PrevClassTemplate && ShouldAddRedecl ? 2105 PrevClassTemplate->getTemplatedDecl() : nullptr, 2106 /*DelayTypeCreation=*/true); 2107 SetNestedNameSpecifier(*this, NewClass, SS); 2108 if (NumOuterTemplateParamLists > 0) 2109 NewClass->setTemplateParameterListsInfo( 2110 Context, 2111 llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists)); 2112 2113 // Add alignment attributes if necessary; these attributes are checked when 2114 // the ASTContext lays out the structure. 2115 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 2116 AddAlignmentAttributesForRecord(NewClass); 2117 AddMsStructLayoutForRecord(NewClass); 2118 } 2119 2120 ClassTemplateDecl *NewTemplate 2121 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc, 2122 DeclarationName(Name), TemplateParams, 2123 NewClass); 2124 2125 if (ShouldAddRedecl) 2126 NewTemplate->setPreviousDecl(PrevClassTemplate); 2127 2128 NewClass->setDescribedClassTemplate(NewTemplate); 2129 2130 if (ModulePrivateLoc.isValid()) 2131 NewTemplate->setModulePrivate(); 2132 2133 // Build the type for the class template declaration now. 2134 QualType T = NewTemplate->getInjectedClassNameSpecialization(); 2135 T = Context.getInjectedClassNameType(NewClass, T); 2136 assert(T->isDependentType() && "Class template type is not dependent?"); 2137 (void)T; 2138 2139 // If we are providing an explicit specialization of a member that is a 2140 // class template, make a note of that. 2141 if (PrevClassTemplate && 2142 PrevClassTemplate->getInstantiatedFromMemberTemplate()) 2143 PrevClassTemplate->setMemberSpecialization(); 2144 2145 // Set the access specifier. 2146 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord()) 2147 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS); 2148 2149 // Set the lexical context of these templates 2150 NewClass->setLexicalDeclContext(CurContext); 2151 NewTemplate->setLexicalDeclContext(CurContext); 2152 2153 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 2154 NewClass->startDefinition(); 2155 2156 ProcessDeclAttributeList(S, NewClass, Attr); 2157 2158 if (PrevClassTemplate) 2159 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl()); 2160 2161 AddPushedVisibilityAttribute(NewClass); 2162 inferGslOwnerPointerAttribute(NewClass); 2163 2164 if (TUK != TUK_Friend) { 2165 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes. 2166 Scope *Outer = S; 2167 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0) 2168 Outer = Outer->getParent(); 2169 PushOnScopeChains(NewTemplate, Outer); 2170 } else { 2171 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) { 2172 NewTemplate->setAccess(PrevClassTemplate->getAccess()); 2173 NewClass->setAccess(PrevClassTemplate->getAccess()); 2174 } 2175 2176 NewTemplate->setObjectOfFriendDecl(); 2177 2178 // Friend templates are visible in fairly strange ways. 2179 if (!CurContext->isDependentContext()) { 2180 DeclContext *DC = SemanticContext->getRedeclContext(); 2181 DC->makeDeclVisibleInContext(NewTemplate); 2182 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 2183 PushOnScopeChains(NewTemplate, EnclosingScope, 2184 /* AddToContext = */ false); 2185 } 2186 2187 FriendDecl *Friend = FriendDecl::Create( 2188 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc); 2189 Friend->setAccess(AS_public); 2190 CurContext->addDecl(Friend); 2191 } 2192 2193 if (PrevClassTemplate) 2194 CheckRedeclarationInModule(NewTemplate, PrevClassTemplate); 2195 2196 if (Invalid) { 2197 NewTemplate->setInvalidDecl(); 2198 NewClass->setInvalidDecl(); 2199 } 2200 2201 ActOnDocumentableDecl(NewTemplate); 2202 2203 if (SkipBody && SkipBody->ShouldSkip) 2204 return SkipBody->Previous; 2205 2206 return NewTemplate; 2207 } 2208 2209 namespace { 2210 /// Tree transform to "extract" a transformed type from a class template's 2211 /// constructor to a deduction guide. 2212 class ExtractTypeForDeductionGuide 2213 : public TreeTransform<ExtractTypeForDeductionGuide> { 2214 llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs; 2215 2216 public: 2217 typedef TreeTransform<ExtractTypeForDeductionGuide> Base; 2218 ExtractTypeForDeductionGuide( 2219 Sema &SemaRef, 2220 llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) 2221 : Base(SemaRef), MaterializedTypedefs(MaterializedTypedefs) {} 2222 2223 TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); } 2224 2225 QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) { 2226 ASTContext &Context = SemaRef.getASTContext(); 2227 TypedefNameDecl *OrigDecl = TL.getTypedefNameDecl(); 2228 TypedefNameDecl *Decl = OrigDecl; 2229 // Transform the underlying type of the typedef and clone the Decl only if 2230 // the typedef has a dependent context. 2231 if (OrigDecl->getDeclContext()->isDependentContext()) { 2232 TypeLocBuilder InnerTLB; 2233 QualType Transformed = 2234 TransformType(InnerTLB, OrigDecl->getTypeSourceInfo()->getTypeLoc()); 2235 TypeSourceInfo *TSI = InnerTLB.getTypeSourceInfo(Context, Transformed); 2236 if (isa<TypeAliasDecl>(OrigDecl)) 2237 Decl = TypeAliasDecl::Create( 2238 Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(), 2239 OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI); 2240 else { 2241 assert(isa<TypedefDecl>(OrigDecl) && "Not a Type alias or typedef"); 2242 Decl = TypedefDecl::Create( 2243 Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(), 2244 OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI); 2245 } 2246 MaterializedTypedefs.push_back(Decl); 2247 } 2248 2249 QualType TDTy = Context.getTypedefType(Decl); 2250 TypedefTypeLoc TypedefTL = TLB.push<TypedefTypeLoc>(TDTy); 2251 TypedefTL.setNameLoc(TL.getNameLoc()); 2252 2253 return TDTy; 2254 } 2255 }; 2256 2257 /// Transform to convert portions of a constructor declaration into the 2258 /// corresponding deduction guide, per C++1z [over.match.class.deduct]p1. 2259 struct ConvertConstructorToDeductionGuideTransform { 2260 ConvertConstructorToDeductionGuideTransform(Sema &S, 2261 ClassTemplateDecl *Template) 2262 : SemaRef(S), Template(Template) { 2263 // If the template is nested, then we need to use the original 2264 // pattern to iterate over the constructors. 2265 ClassTemplateDecl *Pattern = Template; 2266 while (Pattern->getInstantiatedFromMemberTemplate()) { 2267 if (Pattern->isMemberSpecialization()) 2268 break; 2269 Pattern = Pattern->getInstantiatedFromMemberTemplate(); 2270 NestedPattern = Pattern; 2271 } 2272 2273 if (NestedPattern) 2274 OuterInstantiationArgs = SemaRef.getTemplateInstantiationArgs(Template); 2275 } 2276 2277 Sema &SemaRef; 2278 ClassTemplateDecl *Template; 2279 ClassTemplateDecl *NestedPattern = nullptr; 2280 2281 DeclContext *DC = Template->getDeclContext(); 2282 CXXRecordDecl *Primary = Template->getTemplatedDecl(); 2283 DeclarationName DeductionGuideName = 2284 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template); 2285 2286 QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary); 2287 2288 // Index adjustment to apply to convert depth-1 template parameters into 2289 // depth-0 template parameters. 2290 unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size(); 2291 2292 // Instantiation arguments for the outermost depth-1 templates 2293 // when the template is nested 2294 MultiLevelTemplateArgumentList OuterInstantiationArgs; 2295 2296 /// Transform a constructor declaration into a deduction guide. 2297 NamedDecl *transformConstructor(FunctionTemplateDecl *FTD, 2298 CXXConstructorDecl *CD) { 2299 SmallVector<TemplateArgument, 16> SubstArgs; 2300 2301 LocalInstantiationScope Scope(SemaRef); 2302 2303 // C++ [over.match.class.deduct]p1: 2304 // -- For each constructor of the class template designated by the 2305 // template-name, a function template with the following properties: 2306 2307 // -- The template parameters are the template parameters of the class 2308 // template followed by the template parameters (including default 2309 // template arguments) of the constructor, if any. 2310 TemplateParameterList *TemplateParams = GetTemplateParameterList(Template); 2311 if (FTD) { 2312 TemplateParameterList *InnerParams = FTD->getTemplateParameters(); 2313 SmallVector<NamedDecl *, 16> AllParams; 2314 SmallVector<TemplateArgument, 16> Depth1Args; 2315 AllParams.reserve(TemplateParams->size() + InnerParams->size()); 2316 AllParams.insert(AllParams.begin(), 2317 TemplateParams->begin(), TemplateParams->end()); 2318 SubstArgs.reserve(InnerParams->size()); 2319 Depth1Args.reserve(InnerParams->size()); 2320 2321 // Later template parameters could refer to earlier ones, so build up 2322 // a list of substituted template arguments as we go. 2323 for (NamedDecl *Param : *InnerParams) { 2324 MultiLevelTemplateArgumentList Args; 2325 Args.setKind(TemplateSubstitutionKind::Rewrite); 2326 Args.addOuterTemplateArguments(Depth1Args); 2327 Args.addOuterRetainedLevel(); 2328 if (NestedPattern) 2329 Args.addOuterRetainedLevels(NestedPattern->getTemplateDepth()); 2330 NamedDecl *NewParam = transformTemplateParameter(Param, Args); 2331 if (!NewParam) 2332 return nullptr; 2333 2334 // Constraints require that we substitute depth-1 arguments 2335 // to match depths when substituted for evaluation later 2336 Depth1Args.push_back(SemaRef.Context.getCanonicalTemplateArgument( 2337 SemaRef.Context.getInjectedTemplateArg(NewParam))); 2338 2339 if (NestedPattern) { 2340 TemplateDeclInstantiator Instantiator(SemaRef, DC, 2341 OuterInstantiationArgs); 2342 Instantiator.setEvaluateConstraints(false); 2343 SemaRef.runWithSufficientStackSpace(NewParam->getLocation(), [&] { 2344 NewParam = cast<NamedDecl>(Instantiator.Visit(NewParam)); 2345 }); 2346 } 2347 2348 assert(NewParam->getTemplateDepth() == 0 && 2349 "Unexpected template parameter depth"); 2350 2351 AllParams.push_back(NewParam); 2352 SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument( 2353 SemaRef.Context.getInjectedTemplateArg(NewParam))); 2354 } 2355 2356 // Substitute new template parameters into requires-clause if present. 2357 Expr *RequiresClause = nullptr; 2358 if (Expr *InnerRC = InnerParams->getRequiresClause()) { 2359 MultiLevelTemplateArgumentList Args; 2360 Args.setKind(TemplateSubstitutionKind::Rewrite); 2361 Args.addOuterTemplateArguments(Depth1Args); 2362 Args.addOuterRetainedLevel(); 2363 if (NestedPattern) 2364 Args.addOuterRetainedLevels(NestedPattern->getTemplateDepth()); 2365 ExprResult E = SemaRef.SubstExpr(InnerRC, Args); 2366 if (E.isInvalid()) 2367 return nullptr; 2368 RequiresClause = E.getAs<Expr>(); 2369 } 2370 2371 TemplateParams = TemplateParameterList::Create( 2372 SemaRef.Context, InnerParams->getTemplateLoc(), 2373 InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(), 2374 RequiresClause); 2375 } 2376 2377 // If we built a new template-parameter-list, track that we need to 2378 // substitute references to the old parameters into references to the 2379 // new ones. 2380 MultiLevelTemplateArgumentList Args; 2381 Args.setKind(TemplateSubstitutionKind::Rewrite); 2382 if (FTD) { 2383 Args.addOuterTemplateArguments(SubstArgs); 2384 Args.addOuterRetainedLevel(); 2385 } 2386 2387 if (NestedPattern) 2388 Args.addOuterRetainedLevels(NestedPattern->getTemplateDepth()); 2389 2390 FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc() 2391 .getAsAdjusted<FunctionProtoTypeLoc>(); 2392 assert(FPTL && "no prototype for constructor declaration"); 2393 2394 // Transform the type of the function, adjusting the return type and 2395 // replacing references to the old parameters with references to the 2396 // new ones. 2397 TypeLocBuilder TLB; 2398 SmallVector<ParmVarDecl*, 8> Params; 2399 SmallVector<TypedefNameDecl *, 4> MaterializedTypedefs; 2400 QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args, 2401 MaterializedTypedefs); 2402 if (NewType.isNull()) 2403 return nullptr; 2404 TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType); 2405 2406 return buildDeductionGuide(TemplateParams, CD, CD->getExplicitSpecifier(), 2407 NewTInfo, CD->getBeginLoc(), CD->getLocation(), 2408 CD->getEndLoc(), MaterializedTypedefs); 2409 } 2410 2411 /// Build a deduction guide with the specified parameter types. 2412 NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) { 2413 SourceLocation Loc = Template->getLocation(); 2414 2415 // Build the requested type. 2416 FunctionProtoType::ExtProtoInfo EPI; 2417 EPI.HasTrailingReturn = true; 2418 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc, 2419 DeductionGuideName, EPI); 2420 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc); 2421 2422 FunctionProtoTypeLoc FPTL = 2423 TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>(); 2424 2425 // Build the parameters, needed during deduction / substitution. 2426 SmallVector<ParmVarDecl*, 4> Params; 2427 for (auto T : ParamTypes) { 2428 ParmVarDecl *NewParam = ParmVarDecl::Create( 2429 SemaRef.Context, DC, Loc, Loc, nullptr, T, 2430 SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr); 2431 NewParam->setScopeInfo(0, Params.size()); 2432 FPTL.setParam(Params.size(), NewParam); 2433 Params.push_back(NewParam); 2434 } 2435 2436 return buildDeductionGuide(GetTemplateParameterList(Template), nullptr, 2437 ExplicitSpecifier(), TSI, Loc, Loc, Loc); 2438 } 2439 2440 private: 2441 /// Transform a constructor template parameter into a deduction guide template 2442 /// parameter, rebuilding any internal references to earlier parameters and 2443 /// renumbering as we go. 2444 NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam, 2445 MultiLevelTemplateArgumentList &Args) { 2446 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) { 2447 // TemplateTypeParmDecl's index cannot be changed after creation, so 2448 // substitute it directly. 2449 auto *NewTTP = TemplateTypeParmDecl::Create( 2450 SemaRef.Context, DC, TTP->getBeginLoc(), TTP->getLocation(), 2451 TTP->getDepth() - 1, Depth1IndexAdjustment + TTP->getIndex(), 2452 TTP->getIdentifier(), TTP->wasDeclaredWithTypename(), 2453 TTP->isParameterPack(), TTP->hasTypeConstraint(), 2454 TTP->isExpandedParameterPack() 2455 ? std::optional<unsigned>(TTP->getNumExpansionParameters()) 2456 : std::nullopt); 2457 if (const auto *TC = TTP->getTypeConstraint()) 2458 SemaRef.SubstTypeConstraint(NewTTP, TC, Args, 2459 /*EvaluateConstraint*/ true); 2460 if (TTP->hasDefaultArgument()) { 2461 TypeSourceInfo *InstantiatedDefaultArg = 2462 SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args, 2463 TTP->getDefaultArgumentLoc(), TTP->getDeclName()); 2464 if (InstantiatedDefaultArg) 2465 NewTTP->setDefaultArgument(InstantiatedDefaultArg); 2466 } 2467 SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam, 2468 NewTTP); 2469 return NewTTP; 2470 } 2471 2472 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam)) 2473 return transformTemplateParameterImpl(TTP, Args); 2474 2475 return transformTemplateParameterImpl( 2476 cast<NonTypeTemplateParmDecl>(TemplateParam), Args); 2477 } 2478 template<typename TemplateParmDecl> 2479 TemplateParmDecl * 2480 transformTemplateParameterImpl(TemplateParmDecl *OldParam, 2481 MultiLevelTemplateArgumentList &Args) { 2482 // Ask the template instantiator to do the heavy lifting for us, then adjust 2483 // the index of the parameter once it's done. 2484 auto *NewParam = 2485 cast<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args)); 2486 assert(NewParam->getDepth() == OldParam->getDepth() - 1 && 2487 "unexpected template param depth"); 2488 NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment); 2489 return NewParam; 2490 } 2491 2492 QualType transformFunctionProtoType( 2493 TypeLocBuilder &TLB, FunctionProtoTypeLoc TL, 2494 SmallVectorImpl<ParmVarDecl *> &Params, 2495 MultiLevelTemplateArgumentList &Args, 2496 SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) { 2497 SmallVector<QualType, 4> ParamTypes; 2498 const FunctionProtoType *T = TL.getTypePtr(); 2499 2500 // -- The types of the function parameters are those of the constructor. 2501 for (auto *OldParam : TL.getParams()) { 2502 ParmVarDecl *NewParam = 2503 transformFunctionTypeParam(OldParam, Args, MaterializedTypedefs); 2504 if (NestedPattern && NewParam) 2505 NewParam = transformFunctionTypeParam(NewParam, OuterInstantiationArgs, 2506 MaterializedTypedefs); 2507 if (!NewParam) 2508 return QualType(); 2509 ParamTypes.push_back(NewParam->getType()); 2510 Params.push_back(NewParam); 2511 } 2512 2513 // -- The return type is the class template specialization designated by 2514 // the template-name and template arguments corresponding to the 2515 // template parameters obtained from the class template. 2516 // 2517 // We use the injected-class-name type of the primary template instead. 2518 // This has the convenient property that it is different from any type that 2519 // the user can write in a deduction-guide (because they cannot enter the 2520 // context of the template), so implicit deduction guides can never collide 2521 // with explicit ones. 2522 QualType ReturnType = DeducedType; 2523 TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation()); 2524 2525 // Resolving a wording defect, we also inherit the variadicness of the 2526 // constructor. 2527 FunctionProtoType::ExtProtoInfo EPI; 2528 EPI.Variadic = T->isVariadic(); 2529 EPI.HasTrailingReturn = true; 2530 2531 QualType Result = SemaRef.BuildFunctionType( 2532 ReturnType, ParamTypes, TL.getBeginLoc(), DeductionGuideName, EPI); 2533 if (Result.isNull()) 2534 return QualType(); 2535 2536 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result); 2537 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin()); 2538 NewTL.setLParenLoc(TL.getLParenLoc()); 2539 NewTL.setRParenLoc(TL.getRParenLoc()); 2540 NewTL.setExceptionSpecRange(SourceRange()); 2541 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd()); 2542 for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I) 2543 NewTL.setParam(I, Params[I]); 2544 2545 return Result; 2546 } 2547 2548 ParmVarDecl *transformFunctionTypeParam( 2549 ParmVarDecl *OldParam, MultiLevelTemplateArgumentList &Args, 2550 llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) { 2551 TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo(); 2552 TypeSourceInfo *NewDI; 2553 if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) { 2554 // Expand out the one and only element in each inner pack. 2555 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0); 2556 NewDI = 2557 SemaRef.SubstType(PackTL.getPatternLoc(), Args, 2558 OldParam->getLocation(), OldParam->getDeclName()); 2559 if (!NewDI) return nullptr; 2560 NewDI = 2561 SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(), 2562 PackTL.getTypePtr()->getNumExpansions()); 2563 } else 2564 NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(), 2565 OldParam->getDeclName()); 2566 if (!NewDI) 2567 return nullptr; 2568 2569 // Extract the type. This (for instance) replaces references to typedef 2570 // members of the current instantiations with the definitions of those 2571 // typedefs, avoiding triggering instantiation of the deduced type during 2572 // deduction. 2573 NewDI = ExtractTypeForDeductionGuide(SemaRef, MaterializedTypedefs) 2574 .transform(NewDI); 2575 2576 // Resolving a wording defect, we also inherit default arguments from the 2577 // constructor. 2578 ExprResult NewDefArg; 2579 if (OldParam->hasDefaultArg()) { 2580 // We don't care what the value is (we won't use it); just create a 2581 // placeholder to indicate there is a default argument. 2582 QualType ParamTy = NewDI->getType(); 2583 NewDefArg = new (SemaRef.Context) 2584 OpaqueValueExpr(OldParam->getDefaultArg()->getBeginLoc(), 2585 ParamTy.getNonLValueExprType(SemaRef.Context), 2586 ParamTy->isLValueReferenceType() ? VK_LValue 2587 : ParamTy->isRValueReferenceType() ? VK_XValue 2588 : VK_PRValue); 2589 } 2590 2591 ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC, 2592 OldParam->getInnerLocStart(), 2593 OldParam->getLocation(), 2594 OldParam->getIdentifier(), 2595 NewDI->getType(), 2596 NewDI, 2597 OldParam->getStorageClass(), 2598 NewDefArg.get()); 2599 NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(), 2600 OldParam->getFunctionScopeIndex()); 2601 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam); 2602 return NewParam; 2603 } 2604 2605 FunctionTemplateDecl *buildDeductionGuide( 2606 TemplateParameterList *TemplateParams, CXXConstructorDecl *Ctor, 2607 ExplicitSpecifier ES, TypeSourceInfo *TInfo, SourceLocation LocStart, 2608 SourceLocation Loc, SourceLocation LocEnd, 2609 llvm::ArrayRef<TypedefNameDecl *> MaterializedTypedefs = {}) { 2610 DeclarationNameInfo Name(DeductionGuideName, Loc); 2611 ArrayRef<ParmVarDecl *> Params = 2612 TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams(); 2613 2614 // Build the implicit deduction guide template. 2615 auto *Guide = 2616 CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, ES, Name, 2617 TInfo->getType(), TInfo, LocEnd, Ctor); 2618 Guide->setImplicit(); 2619 Guide->setParams(Params); 2620 2621 for (auto *Param : Params) 2622 Param->setDeclContext(Guide); 2623 for (auto *TD : MaterializedTypedefs) 2624 TD->setDeclContext(Guide); 2625 2626 auto *GuideTemplate = FunctionTemplateDecl::Create( 2627 SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide); 2628 GuideTemplate->setImplicit(); 2629 Guide->setDescribedFunctionTemplate(GuideTemplate); 2630 2631 if (isa<CXXRecordDecl>(DC)) { 2632 Guide->setAccess(AS_public); 2633 GuideTemplate->setAccess(AS_public); 2634 } 2635 2636 DC->addDecl(GuideTemplate); 2637 return GuideTemplate; 2638 } 2639 }; 2640 } 2641 2642 FunctionTemplateDecl *Sema::DeclareImplicitDeductionGuideFromInitList( 2643 TemplateDecl *Template, MutableArrayRef<QualType> ParamTypes, 2644 SourceLocation Loc) { 2645 if (CXXRecordDecl *DefRecord = 2646 cast<CXXRecordDecl>(Template->getTemplatedDecl())->getDefinition()) { 2647 if (TemplateDecl *DescribedTemplate = 2648 DefRecord->getDescribedClassTemplate()) 2649 Template = DescribedTemplate; 2650 } 2651 2652 DeclContext *DC = Template->getDeclContext(); 2653 if (DC->isDependentContext()) 2654 return nullptr; 2655 2656 ConvertConstructorToDeductionGuideTransform Transform( 2657 *this, cast<ClassTemplateDecl>(Template)); 2658 if (!isCompleteType(Loc, Transform.DeducedType)) 2659 return nullptr; 2660 2661 // In case we were expanding a pack when we attempted to declare deduction 2662 // guides, turn off pack expansion for everything we're about to do. 2663 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, 2664 /*NewSubstitutionIndex=*/-1); 2665 // Create a template instantiation record to track the "instantiation" of 2666 // constructors into deduction guides. 2667 InstantiatingTemplate BuildingDeductionGuides( 2668 *this, Loc, Template, 2669 Sema::InstantiatingTemplate::BuildingDeductionGuidesTag{}); 2670 if (BuildingDeductionGuides.isInvalid()) 2671 return nullptr; 2672 2673 return cast<FunctionTemplateDecl>( 2674 Transform.buildSimpleDeductionGuide(ParamTypes)); 2675 } 2676 2677 void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template, 2678 SourceLocation Loc) { 2679 if (CXXRecordDecl *DefRecord = 2680 cast<CXXRecordDecl>(Template->getTemplatedDecl())->getDefinition()) { 2681 if (TemplateDecl *DescribedTemplate = DefRecord->getDescribedClassTemplate()) 2682 Template = DescribedTemplate; 2683 } 2684 2685 DeclContext *DC = Template->getDeclContext(); 2686 if (DC->isDependentContext()) 2687 return; 2688 2689 ConvertConstructorToDeductionGuideTransform Transform( 2690 *this, cast<ClassTemplateDecl>(Template)); 2691 if (!isCompleteType(Loc, Transform.DeducedType)) 2692 return; 2693 2694 // Check whether we've already declared deduction guides for this template. 2695 // FIXME: Consider storing a flag on the template to indicate this. 2696 auto Existing = DC->lookup(Transform.DeductionGuideName); 2697 for (auto *D : Existing) 2698 if (D->isImplicit()) 2699 return; 2700 2701 // In case we were expanding a pack when we attempted to declare deduction 2702 // guides, turn off pack expansion for everything we're about to do. 2703 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1); 2704 // Create a template instantiation record to track the "instantiation" of 2705 // constructors into deduction guides. 2706 InstantiatingTemplate BuildingDeductionGuides( 2707 *this, Loc, Template, 2708 Sema::InstantiatingTemplate::BuildingDeductionGuidesTag{}); 2709 if (BuildingDeductionGuides.isInvalid()) 2710 return; 2711 2712 // Convert declared constructors into deduction guide templates. 2713 // FIXME: Skip constructors for which deduction must necessarily fail (those 2714 // for which some class template parameter without a default argument never 2715 // appears in a deduced context). 2716 ClassTemplateDecl *Pattern = 2717 Transform.NestedPattern ? Transform.NestedPattern : Transform.Template; 2718 ContextRAII SavedContext(*this, Pattern->getTemplatedDecl()); 2719 llvm::SmallPtrSet<NamedDecl *, 8> ProcessedCtors; 2720 bool AddedAny = false; 2721 for (NamedDecl *D : LookupConstructors(Pattern->getTemplatedDecl())) { 2722 D = D->getUnderlyingDecl(); 2723 if (D->isInvalidDecl() || D->isImplicit()) 2724 continue; 2725 2726 D = cast<NamedDecl>(D->getCanonicalDecl()); 2727 2728 // Within C++20 modules, we may have multiple same constructors in 2729 // multiple same RecordDecls. And it doesn't make sense to create 2730 // duplicated deduction guides for the duplicated constructors. 2731 if (ProcessedCtors.count(D)) 2732 continue; 2733 2734 auto *FTD = dyn_cast<FunctionTemplateDecl>(D); 2735 auto *CD = 2736 dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D); 2737 // Class-scope explicit specializations (MS extension) do not result in 2738 // deduction guides. 2739 if (!CD || (!FTD && CD->isFunctionTemplateSpecialization())) 2740 continue; 2741 2742 // Cannot make a deduction guide when unparsed arguments are present. 2743 if (llvm::any_of(CD->parameters(), [](ParmVarDecl *P) { 2744 return !P || P->hasUnparsedDefaultArg(); 2745 })) 2746 continue; 2747 2748 ProcessedCtors.insert(D); 2749 Transform.transformConstructor(FTD, CD); 2750 AddedAny = true; 2751 } 2752 2753 // C++17 [over.match.class.deduct] 2754 // -- If C is not defined or does not declare any constructors, an 2755 // additional function template derived as above from a hypothetical 2756 // constructor C(). 2757 if (!AddedAny) 2758 Transform.buildSimpleDeductionGuide(std::nullopt); 2759 2760 // -- An additional function template derived as above from a hypothetical 2761 // constructor C(C), called the copy deduction candidate. 2762 cast<CXXDeductionGuideDecl>( 2763 cast<FunctionTemplateDecl>( 2764 Transform.buildSimpleDeductionGuide(Transform.DeducedType)) 2765 ->getTemplatedDecl()) 2766 ->setDeductionCandidateKind(DeductionCandidate::Copy); 2767 2768 SavedContext.pop(); 2769 } 2770 2771 /// Diagnose the presence of a default template argument on a 2772 /// template parameter, which is ill-formed in certain contexts. 2773 /// 2774 /// \returns true if the default template argument should be dropped. 2775 static bool DiagnoseDefaultTemplateArgument(Sema &S, 2776 Sema::TemplateParamListContext TPC, 2777 SourceLocation ParamLoc, 2778 SourceRange DefArgRange) { 2779 switch (TPC) { 2780 case Sema::TPC_ClassTemplate: 2781 case Sema::TPC_VarTemplate: 2782 case Sema::TPC_TypeAliasTemplate: 2783 return false; 2784 2785 case Sema::TPC_FunctionTemplate: 2786 case Sema::TPC_FriendFunctionTemplateDefinition: 2787 // C++ [temp.param]p9: 2788 // A default template-argument shall not be specified in a 2789 // function template declaration or a function template 2790 // definition [...] 2791 // If a friend function template declaration specifies a default 2792 // template-argument, that declaration shall be a definition and shall be 2793 // the only declaration of the function template in the translation unit. 2794 // (C++98/03 doesn't have this wording; see DR226). 2795 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ? 2796 diag::warn_cxx98_compat_template_parameter_default_in_function_template 2797 : diag::ext_template_parameter_default_in_function_template) 2798 << DefArgRange; 2799 return false; 2800 2801 case Sema::TPC_ClassTemplateMember: 2802 // C++0x [temp.param]p9: 2803 // A default template-argument shall not be specified in the 2804 // template-parameter-lists of the definition of a member of a 2805 // class template that appears outside of the member's class. 2806 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member) 2807 << DefArgRange; 2808 return true; 2809 2810 case Sema::TPC_FriendClassTemplate: 2811 case Sema::TPC_FriendFunctionTemplate: 2812 // C++ [temp.param]p9: 2813 // A default template-argument shall not be specified in a 2814 // friend template declaration. 2815 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template) 2816 << DefArgRange; 2817 return true; 2818 2819 // FIXME: C++0x [temp.param]p9 allows default template-arguments 2820 // for friend function templates if there is only a single 2821 // declaration (and it is a definition). Strange! 2822 } 2823 2824 llvm_unreachable("Invalid TemplateParamListContext!"); 2825 } 2826 2827 /// Check for unexpanded parameter packs within the template parameters 2828 /// of a template template parameter, recursively. 2829 static bool DiagnoseUnexpandedParameterPacks(Sema &S, 2830 TemplateTemplateParmDecl *TTP) { 2831 // A template template parameter which is a parameter pack is also a pack 2832 // expansion. 2833 if (TTP->isParameterPack()) 2834 return false; 2835 2836 TemplateParameterList *Params = TTP->getTemplateParameters(); 2837 for (unsigned I = 0, N = Params->size(); I != N; ++I) { 2838 NamedDecl *P = Params->getParam(I); 2839 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) { 2840 if (!TTP->isParameterPack()) 2841 if (const TypeConstraint *TC = TTP->getTypeConstraint()) 2842 if (TC->hasExplicitTemplateArgs()) 2843 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments()) 2844 if (S.DiagnoseUnexpandedParameterPack(ArgLoc, 2845 Sema::UPPC_TypeConstraint)) 2846 return true; 2847 continue; 2848 } 2849 2850 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) { 2851 if (!NTTP->isParameterPack() && 2852 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(), 2853 NTTP->getTypeSourceInfo(), 2854 Sema::UPPC_NonTypeTemplateParameterType)) 2855 return true; 2856 2857 continue; 2858 } 2859 2860 if (TemplateTemplateParmDecl *InnerTTP 2861 = dyn_cast<TemplateTemplateParmDecl>(P)) 2862 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP)) 2863 return true; 2864 } 2865 2866 return false; 2867 } 2868 2869 /// Checks the validity of a template parameter list, possibly 2870 /// considering the template parameter list from a previous 2871 /// declaration. 2872 /// 2873 /// If an "old" template parameter list is provided, it must be 2874 /// equivalent (per TemplateParameterListsAreEqual) to the "new" 2875 /// template parameter list. 2876 /// 2877 /// \param NewParams Template parameter list for a new template 2878 /// declaration. This template parameter list will be updated with any 2879 /// default arguments that are carried through from the previous 2880 /// template parameter list. 2881 /// 2882 /// \param OldParams If provided, template parameter list from a 2883 /// previous declaration of the same template. Default template 2884 /// arguments will be merged from the old template parameter list to 2885 /// the new template parameter list. 2886 /// 2887 /// \param TPC Describes the context in which we are checking the given 2888 /// template parameter list. 2889 /// 2890 /// \param SkipBody If we might have already made a prior merged definition 2891 /// of this template visible, the corresponding body-skipping information. 2892 /// Default argument redefinition is not an error when skipping such a body, 2893 /// because (under the ODR) we can assume the default arguments are the same 2894 /// as the prior merged definition. 2895 /// 2896 /// \returns true if an error occurred, false otherwise. 2897 bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams, 2898 TemplateParameterList *OldParams, 2899 TemplateParamListContext TPC, 2900 SkipBodyInfo *SkipBody) { 2901 bool Invalid = false; 2902 2903 // C++ [temp.param]p10: 2904 // The set of default template-arguments available for use with a 2905 // template declaration or definition is obtained by merging the 2906 // default arguments from the definition (if in scope) and all 2907 // declarations in scope in the same way default function 2908 // arguments are (8.3.6). 2909 bool SawDefaultArgument = false; 2910 SourceLocation PreviousDefaultArgLoc; 2911 2912 // Dummy initialization to avoid warnings. 2913 TemplateParameterList::iterator OldParam = NewParams->end(); 2914 if (OldParams) 2915 OldParam = OldParams->begin(); 2916 2917 bool RemoveDefaultArguments = false; 2918 for (TemplateParameterList::iterator NewParam = NewParams->begin(), 2919 NewParamEnd = NewParams->end(); 2920 NewParam != NewParamEnd; ++NewParam) { 2921 // Whether we've seen a duplicate default argument in the same translation 2922 // unit. 2923 bool RedundantDefaultArg = false; 2924 // Whether we've found inconsis inconsitent default arguments in different 2925 // translation unit. 2926 bool InconsistentDefaultArg = false; 2927 // The name of the module which contains the inconsistent default argument. 2928 std::string PrevModuleName; 2929 2930 SourceLocation OldDefaultLoc; 2931 SourceLocation NewDefaultLoc; 2932 2933 // Variable used to diagnose missing default arguments 2934 bool MissingDefaultArg = false; 2935 2936 // Variable used to diagnose non-final parameter packs 2937 bool SawParameterPack = false; 2938 2939 if (TemplateTypeParmDecl *NewTypeParm 2940 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) { 2941 // Check the presence of a default argument here. 2942 if (NewTypeParm->hasDefaultArgument() && 2943 DiagnoseDefaultTemplateArgument(*this, TPC, 2944 NewTypeParm->getLocation(), 2945 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc() 2946 .getSourceRange())) 2947 NewTypeParm->removeDefaultArgument(); 2948 2949 // Merge default arguments for template type parameters. 2950 TemplateTypeParmDecl *OldTypeParm 2951 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr; 2952 if (NewTypeParm->isParameterPack()) { 2953 assert(!NewTypeParm->hasDefaultArgument() && 2954 "Parameter packs can't have a default argument!"); 2955 SawParameterPack = true; 2956 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) && 2957 NewTypeParm->hasDefaultArgument() && 2958 (!SkipBody || !SkipBody->ShouldSkip)) { 2959 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc(); 2960 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc(); 2961 SawDefaultArgument = true; 2962 2963 if (!OldTypeParm->getOwningModule()) 2964 RedundantDefaultArg = true; 2965 else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm, 2966 NewTypeParm)) { 2967 InconsistentDefaultArg = true; 2968 PrevModuleName = 2969 OldTypeParm->getImportedOwningModule()->getFullModuleName(); 2970 } 2971 PreviousDefaultArgLoc = NewDefaultLoc; 2972 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) { 2973 // Merge the default argument from the old declaration to the 2974 // new declaration. 2975 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm); 2976 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc(); 2977 } else if (NewTypeParm->hasDefaultArgument()) { 2978 SawDefaultArgument = true; 2979 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc(); 2980 } else if (SawDefaultArgument) 2981 MissingDefaultArg = true; 2982 } else if (NonTypeTemplateParmDecl *NewNonTypeParm 2983 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) { 2984 // Check for unexpanded parameter packs. 2985 if (!NewNonTypeParm->isParameterPack() && 2986 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(), 2987 NewNonTypeParm->getTypeSourceInfo(), 2988 UPPC_NonTypeTemplateParameterType)) { 2989 Invalid = true; 2990 continue; 2991 } 2992 2993 // Check the presence of a default argument here. 2994 if (NewNonTypeParm->hasDefaultArgument() && 2995 DiagnoseDefaultTemplateArgument(*this, TPC, 2996 NewNonTypeParm->getLocation(), 2997 NewNonTypeParm->getDefaultArgument()->getSourceRange())) { 2998 NewNonTypeParm->removeDefaultArgument(); 2999 } 3000 3001 // Merge default arguments for non-type template parameters 3002 NonTypeTemplateParmDecl *OldNonTypeParm 3003 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr; 3004 if (NewNonTypeParm->isParameterPack()) { 3005 assert(!NewNonTypeParm->hasDefaultArgument() && 3006 "Parameter packs can't have a default argument!"); 3007 if (!NewNonTypeParm->isPackExpansion()) 3008 SawParameterPack = true; 3009 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) && 3010 NewNonTypeParm->hasDefaultArgument() && 3011 (!SkipBody || !SkipBody->ShouldSkip)) { 3012 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc(); 3013 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc(); 3014 SawDefaultArgument = true; 3015 if (!OldNonTypeParm->getOwningModule()) 3016 RedundantDefaultArg = true; 3017 else if (!getASTContext().isSameDefaultTemplateArgument( 3018 OldNonTypeParm, NewNonTypeParm)) { 3019 InconsistentDefaultArg = true; 3020 PrevModuleName = 3021 OldNonTypeParm->getImportedOwningModule()->getFullModuleName(); 3022 } 3023 PreviousDefaultArgLoc = NewDefaultLoc; 3024 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) { 3025 // Merge the default argument from the old declaration to the 3026 // new declaration. 3027 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm); 3028 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc(); 3029 } else if (NewNonTypeParm->hasDefaultArgument()) { 3030 SawDefaultArgument = true; 3031 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc(); 3032 } else if (SawDefaultArgument) 3033 MissingDefaultArg = true; 3034 } else { 3035 TemplateTemplateParmDecl *NewTemplateParm 3036 = cast<TemplateTemplateParmDecl>(*NewParam); 3037 3038 // Check for unexpanded parameter packs, recursively. 3039 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) { 3040 Invalid = true; 3041 continue; 3042 } 3043 3044 // Check the presence of a default argument here. 3045 if (NewTemplateParm->hasDefaultArgument() && 3046 DiagnoseDefaultTemplateArgument(*this, TPC, 3047 NewTemplateParm->getLocation(), 3048 NewTemplateParm->getDefaultArgument().getSourceRange())) 3049 NewTemplateParm->removeDefaultArgument(); 3050 3051 // Merge default arguments for template template parameters 3052 TemplateTemplateParmDecl *OldTemplateParm 3053 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr; 3054 if (NewTemplateParm->isParameterPack()) { 3055 assert(!NewTemplateParm->hasDefaultArgument() && 3056 "Parameter packs can't have a default argument!"); 3057 if (!NewTemplateParm->isPackExpansion()) 3058 SawParameterPack = true; 3059 } else if (OldTemplateParm && 3060 hasVisibleDefaultArgument(OldTemplateParm) && 3061 NewTemplateParm->hasDefaultArgument() && 3062 (!SkipBody || !SkipBody->ShouldSkip)) { 3063 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation(); 3064 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation(); 3065 SawDefaultArgument = true; 3066 if (!OldTemplateParm->getOwningModule()) 3067 RedundantDefaultArg = true; 3068 else if (!getASTContext().isSameDefaultTemplateArgument( 3069 OldTemplateParm, NewTemplateParm)) { 3070 InconsistentDefaultArg = true; 3071 PrevModuleName = 3072 OldTemplateParm->getImportedOwningModule()->getFullModuleName(); 3073 } 3074 PreviousDefaultArgLoc = NewDefaultLoc; 3075 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) { 3076 // Merge the default argument from the old declaration to the 3077 // new declaration. 3078 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm); 3079 PreviousDefaultArgLoc 3080 = OldTemplateParm->getDefaultArgument().getLocation(); 3081 } else if (NewTemplateParm->hasDefaultArgument()) { 3082 SawDefaultArgument = true; 3083 PreviousDefaultArgLoc 3084 = NewTemplateParm->getDefaultArgument().getLocation(); 3085 } else if (SawDefaultArgument) 3086 MissingDefaultArg = true; 3087 } 3088 3089 // C++11 [temp.param]p11: 3090 // If a template parameter of a primary class template or alias template 3091 // is a template parameter pack, it shall be the last template parameter. 3092 if (SawParameterPack && (NewParam + 1) != NewParamEnd && 3093 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate || 3094 TPC == TPC_TypeAliasTemplate)) { 3095 Diag((*NewParam)->getLocation(), 3096 diag::err_template_param_pack_must_be_last_template_parameter); 3097 Invalid = true; 3098 } 3099 3100 // [basic.def.odr]/13: 3101 // There can be more than one definition of a 3102 // ... 3103 // default template argument 3104 // ... 3105 // in a program provided that each definition appears in a different 3106 // translation unit and the definitions satisfy the [same-meaning 3107 // criteria of the ODR]. 3108 // 3109 // Simply, the design of modules allows the definition of template default 3110 // argument to be repeated across translation unit. Note that the ODR is 3111 // checked elsewhere. But it is still not allowed to repeat template default 3112 // argument in the same translation unit. 3113 if (RedundantDefaultArg) { 3114 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition); 3115 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg); 3116 Invalid = true; 3117 } else if (InconsistentDefaultArg) { 3118 // We could only diagnose about the case that the OldParam is imported. 3119 // The case NewParam is imported should be handled in ASTReader. 3120 Diag(NewDefaultLoc, 3121 diag::err_template_param_default_arg_inconsistent_redefinition); 3122 Diag(OldDefaultLoc, 3123 diag::note_template_param_prev_default_arg_in_other_module) 3124 << PrevModuleName; 3125 Invalid = true; 3126 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) { 3127 // C++ [temp.param]p11: 3128 // If a template-parameter of a class template has a default 3129 // template-argument, each subsequent template-parameter shall either 3130 // have a default template-argument supplied or be a template parameter 3131 // pack. 3132 Diag((*NewParam)->getLocation(), 3133 diag::err_template_param_default_arg_missing); 3134 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg); 3135 Invalid = true; 3136 RemoveDefaultArguments = true; 3137 } 3138 3139 // If we have an old template parameter list that we're merging 3140 // in, move on to the next parameter. 3141 if (OldParams) 3142 ++OldParam; 3143 } 3144 3145 // We were missing some default arguments at the end of the list, so remove 3146 // all of the default arguments. 3147 if (RemoveDefaultArguments) { 3148 for (TemplateParameterList::iterator NewParam = NewParams->begin(), 3149 NewParamEnd = NewParams->end(); 3150 NewParam != NewParamEnd; ++NewParam) { 3151 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam)) 3152 TTP->removeDefaultArgument(); 3153 else if (NonTypeTemplateParmDecl *NTTP 3154 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) 3155 NTTP->removeDefaultArgument(); 3156 else 3157 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument(); 3158 } 3159 } 3160 3161 return Invalid; 3162 } 3163 3164 namespace { 3165 3166 /// A class which looks for a use of a certain level of template 3167 /// parameter. 3168 struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> { 3169 typedef RecursiveASTVisitor<DependencyChecker> super; 3170 3171 unsigned Depth; 3172 3173 // Whether we're looking for a use of a template parameter that makes the 3174 // overall construct type-dependent / a dependent type. This is strictly 3175 // best-effort for now; we may fail to match at all for a dependent type 3176 // in some cases if this is set. 3177 bool IgnoreNonTypeDependent; 3178 3179 bool Match; 3180 SourceLocation MatchLoc; 3181 3182 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent) 3183 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent), 3184 Match(false) {} 3185 3186 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent) 3187 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) { 3188 NamedDecl *ND = Params->getParam(0); 3189 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) { 3190 Depth = PD->getDepth(); 3191 } else if (NonTypeTemplateParmDecl *PD = 3192 dyn_cast<NonTypeTemplateParmDecl>(ND)) { 3193 Depth = PD->getDepth(); 3194 } else { 3195 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth(); 3196 } 3197 } 3198 3199 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) { 3200 if (ParmDepth >= Depth) { 3201 Match = true; 3202 MatchLoc = Loc; 3203 return true; 3204 } 3205 return false; 3206 } 3207 3208 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) { 3209 // Prune out non-type-dependent expressions if requested. This can 3210 // sometimes result in us failing to find a template parameter reference 3211 // (if a value-dependent expression creates a dependent type), but this 3212 // mode is best-effort only. 3213 if (auto *E = dyn_cast_or_null<Expr>(S)) 3214 if (IgnoreNonTypeDependent && !E->isTypeDependent()) 3215 return true; 3216 return super::TraverseStmt(S, Q); 3217 } 3218 3219 bool TraverseTypeLoc(TypeLoc TL) { 3220 if (IgnoreNonTypeDependent && !TL.isNull() && 3221 !TL.getType()->isDependentType()) 3222 return true; 3223 return super::TraverseTypeLoc(TL); 3224 } 3225 3226 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) { 3227 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc()); 3228 } 3229 3230 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) { 3231 // For a best-effort search, keep looking until we find a location. 3232 return IgnoreNonTypeDependent || !Matches(T->getDepth()); 3233 } 3234 3235 bool TraverseTemplateName(TemplateName N) { 3236 if (TemplateTemplateParmDecl *PD = 3237 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl())) 3238 if (Matches(PD->getDepth())) 3239 return false; 3240 return super::TraverseTemplateName(N); 3241 } 3242 3243 bool VisitDeclRefExpr(DeclRefExpr *E) { 3244 if (NonTypeTemplateParmDecl *PD = 3245 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl())) 3246 if (Matches(PD->getDepth(), E->getExprLoc())) 3247 return false; 3248 return super::VisitDeclRefExpr(E); 3249 } 3250 3251 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) { 3252 return TraverseType(T->getReplacementType()); 3253 } 3254 3255 bool 3256 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) { 3257 return TraverseTemplateArgument(T->getArgumentPack()); 3258 } 3259 3260 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) { 3261 return TraverseType(T->getInjectedSpecializationType()); 3262 } 3263 }; 3264 } // end anonymous namespace 3265 3266 /// Determines whether a given type depends on the given parameter 3267 /// list. 3268 static bool 3269 DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) { 3270 if (!Params->size()) 3271 return false; 3272 3273 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false); 3274 Checker.TraverseType(T); 3275 return Checker.Match; 3276 } 3277 3278 // Find the source range corresponding to the named type in the given 3279 // nested-name-specifier, if any. 3280 static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context, 3281 QualType T, 3282 const CXXScopeSpec &SS) { 3283 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data()); 3284 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) { 3285 if (const Type *CurType = NNS->getAsType()) { 3286 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0))) 3287 return NNSLoc.getTypeLoc().getSourceRange(); 3288 } else 3289 break; 3290 3291 NNSLoc = NNSLoc.getPrefix(); 3292 } 3293 3294 return SourceRange(); 3295 } 3296 3297 /// Match the given template parameter lists to the given scope 3298 /// specifier, returning the template parameter list that applies to the 3299 /// name. 3300 /// 3301 /// \param DeclStartLoc the start of the declaration that has a scope 3302 /// specifier or a template parameter list. 3303 /// 3304 /// \param DeclLoc The location of the declaration itself. 3305 /// 3306 /// \param SS the scope specifier that will be matched to the given template 3307 /// parameter lists. This scope specifier precedes a qualified name that is 3308 /// being declared. 3309 /// 3310 /// \param TemplateId The template-id following the scope specifier, if there 3311 /// is one. Used to check for a missing 'template<>'. 3312 /// 3313 /// \param ParamLists the template parameter lists, from the outermost to the 3314 /// innermost template parameter lists. 3315 /// 3316 /// \param IsFriend Whether to apply the slightly different rules for 3317 /// matching template parameters to scope specifiers in friend 3318 /// declarations. 3319 /// 3320 /// \param IsMemberSpecialization will be set true if the scope specifier 3321 /// denotes a fully-specialized type, and therefore this is a declaration of 3322 /// a member specialization. 3323 /// 3324 /// \returns the template parameter list, if any, that corresponds to the 3325 /// name that is preceded by the scope specifier @p SS. This template 3326 /// parameter list may have template parameters (if we're declaring a 3327 /// template) or may have no template parameters (if we're declaring a 3328 /// template specialization), or may be NULL (if what we're declaring isn't 3329 /// itself a template). 3330 TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier( 3331 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, 3332 TemplateIdAnnotation *TemplateId, 3333 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend, 3334 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) { 3335 IsMemberSpecialization = false; 3336 Invalid = false; 3337 3338 // The sequence of nested types to which we will match up the template 3339 // parameter lists. We first build this list by starting with the type named 3340 // by the nested-name-specifier and walking out until we run out of types. 3341 SmallVector<QualType, 4> NestedTypes; 3342 QualType T; 3343 if (SS.getScopeRep()) { 3344 if (CXXRecordDecl *Record 3345 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true))) 3346 T = Context.getTypeDeclType(Record); 3347 else 3348 T = QualType(SS.getScopeRep()->getAsType(), 0); 3349 } 3350 3351 // If we found an explicit specialization that prevents us from needing 3352 // 'template<>' headers, this will be set to the location of that 3353 // explicit specialization. 3354 SourceLocation ExplicitSpecLoc; 3355 3356 while (!T.isNull()) { 3357 NestedTypes.push_back(T); 3358 3359 // Retrieve the parent of a record type. 3360 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) { 3361 // If this type is an explicit specialization, we're done. 3362 if (ClassTemplateSpecializationDecl *Spec 3363 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) { 3364 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) && 3365 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) { 3366 ExplicitSpecLoc = Spec->getLocation(); 3367 break; 3368 } 3369 } else if (Record->getTemplateSpecializationKind() 3370 == TSK_ExplicitSpecialization) { 3371 ExplicitSpecLoc = Record->getLocation(); 3372 break; 3373 } 3374 3375 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent())) 3376 T = Context.getTypeDeclType(Parent); 3377 else 3378 T = QualType(); 3379 continue; 3380 } 3381 3382 if (const TemplateSpecializationType *TST 3383 = T->getAs<TemplateSpecializationType>()) { 3384 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) { 3385 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext())) 3386 T = Context.getTypeDeclType(Parent); 3387 else 3388 T = QualType(); 3389 continue; 3390 } 3391 } 3392 3393 // Look one step prior in a dependent template specialization type. 3394 if (const DependentTemplateSpecializationType *DependentTST 3395 = T->getAs<DependentTemplateSpecializationType>()) { 3396 if (NestedNameSpecifier *NNS = DependentTST->getQualifier()) 3397 T = QualType(NNS->getAsType(), 0); 3398 else 3399 T = QualType(); 3400 continue; 3401 } 3402 3403 // Look one step prior in a dependent name type. 3404 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){ 3405 if (NestedNameSpecifier *NNS = DependentName->getQualifier()) 3406 T = QualType(NNS->getAsType(), 0); 3407 else 3408 T = QualType(); 3409 continue; 3410 } 3411 3412 // Retrieve the parent of an enumeration type. 3413 if (const EnumType *EnumT = T->getAs<EnumType>()) { 3414 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization 3415 // check here. 3416 EnumDecl *Enum = EnumT->getDecl(); 3417 3418 // Get to the parent type. 3419 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent())) 3420 T = Context.getTypeDeclType(Parent); 3421 else 3422 T = QualType(); 3423 continue; 3424 } 3425 3426 T = QualType(); 3427 } 3428 // Reverse the nested types list, since we want to traverse from the outermost 3429 // to the innermost while checking template-parameter-lists. 3430 std::reverse(NestedTypes.begin(), NestedTypes.end()); 3431 3432 // C++0x [temp.expl.spec]p17: 3433 // A member or a member template may be nested within many 3434 // enclosing class templates. In an explicit specialization for 3435 // such a member, the member declaration shall be preceded by a 3436 // template<> for each enclosing class template that is 3437 // explicitly specialized. 3438 bool SawNonEmptyTemplateParameterList = false; 3439 3440 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) { 3441 if (SawNonEmptyTemplateParameterList) { 3442 if (!SuppressDiagnostic) 3443 Diag(DeclLoc, diag::err_specialize_member_of_template) 3444 << !Recovery << Range; 3445 Invalid = true; 3446 IsMemberSpecialization = false; 3447 return true; 3448 } 3449 3450 return false; 3451 }; 3452 3453 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) { 3454 // Check that we can have an explicit specialization here. 3455 if (CheckExplicitSpecialization(Range, true)) 3456 return true; 3457 3458 // We don't have a template header, but we should. 3459 SourceLocation ExpectedTemplateLoc; 3460 if (!ParamLists.empty()) 3461 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc(); 3462 else 3463 ExpectedTemplateLoc = DeclStartLoc; 3464 3465 if (!SuppressDiagnostic) 3466 Diag(DeclLoc, diag::err_template_spec_needs_header) 3467 << Range 3468 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> "); 3469 return false; 3470 }; 3471 3472 unsigned ParamIdx = 0; 3473 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes; 3474 ++TypeIdx) { 3475 T = NestedTypes[TypeIdx]; 3476 3477 // Whether we expect a 'template<>' header. 3478 bool NeedEmptyTemplateHeader = false; 3479 3480 // Whether we expect a template header with parameters. 3481 bool NeedNonemptyTemplateHeader = false; 3482 3483 // For a dependent type, the set of template parameters that we 3484 // expect to see. 3485 TemplateParameterList *ExpectedTemplateParams = nullptr; 3486 3487 // C++0x [temp.expl.spec]p15: 3488 // A member or a member template may be nested within many enclosing 3489 // class templates. In an explicit specialization for such a member, the 3490 // member declaration shall be preceded by a template<> for each 3491 // enclosing class template that is explicitly specialized. 3492 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) { 3493 if (ClassTemplatePartialSpecializationDecl *Partial 3494 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) { 3495 ExpectedTemplateParams = Partial->getTemplateParameters(); 3496 NeedNonemptyTemplateHeader = true; 3497 } else if (Record->isDependentType()) { 3498 if (Record->getDescribedClassTemplate()) { 3499 ExpectedTemplateParams = Record->getDescribedClassTemplate() 3500 ->getTemplateParameters(); 3501 NeedNonemptyTemplateHeader = true; 3502 } 3503 } else if (ClassTemplateSpecializationDecl *Spec 3504 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) { 3505 // C++0x [temp.expl.spec]p4: 3506 // Members of an explicitly specialized class template are defined 3507 // in the same manner as members of normal classes, and not using 3508 // the template<> syntax. 3509 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization) 3510 NeedEmptyTemplateHeader = true; 3511 else 3512 continue; 3513 } else if (Record->getTemplateSpecializationKind()) { 3514 if (Record->getTemplateSpecializationKind() 3515 != TSK_ExplicitSpecialization && 3516 TypeIdx == NumTypes - 1) 3517 IsMemberSpecialization = true; 3518 3519 continue; 3520 } 3521 } else if (const TemplateSpecializationType *TST 3522 = T->getAs<TemplateSpecializationType>()) { 3523 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) { 3524 ExpectedTemplateParams = Template->getTemplateParameters(); 3525 NeedNonemptyTemplateHeader = true; 3526 } 3527 } else if (T->getAs<DependentTemplateSpecializationType>()) { 3528 // FIXME: We actually could/should check the template arguments here 3529 // against the corresponding template parameter list. 3530 NeedNonemptyTemplateHeader = false; 3531 } 3532 3533 // C++ [temp.expl.spec]p16: 3534 // In an explicit specialization declaration for a member of a class 3535 // template or a member template that ap- pears in namespace scope, the 3536 // member template and some of its enclosing class templates may remain 3537 // unspecialized, except that the declaration shall not explicitly 3538 // specialize a class member template if its en- closing class templates 3539 // are not explicitly specialized as well. 3540 if (ParamIdx < ParamLists.size()) { 3541 if (ParamLists[ParamIdx]->size() == 0) { 3542 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(), 3543 false)) 3544 return nullptr; 3545 } else 3546 SawNonEmptyTemplateParameterList = true; 3547 } 3548 3549 if (NeedEmptyTemplateHeader) { 3550 // If we're on the last of the types, and we need a 'template<>' header 3551 // here, then it's a member specialization. 3552 if (TypeIdx == NumTypes - 1) 3553 IsMemberSpecialization = true; 3554 3555 if (ParamIdx < ParamLists.size()) { 3556 if (ParamLists[ParamIdx]->size() > 0) { 3557 // The header has template parameters when it shouldn't. Complain. 3558 if (!SuppressDiagnostic) 3559 Diag(ParamLists[ParamIdx]->getTemplateLoc(), 3560 diag::err_template_param_list_matches_nontemplate) 3561 << T 3562 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(), 3563 ParamLists[ParamIdx]->getRAngleLoc()) 3564 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS); 3565 Invalid = true; 3566 return nullptr; 3567 } 3568 3569 // Consume this template header. 3570 ++ParamIdx; 3571 continue; 3572 } 3573 3574 if (!IsFriend) 3575 if (DiagnoseMissingExplicitSpecialization( 3576 getRangeOfTypeInNestedNameSpecifier(Context, T, SS))) 3577 return nullptr; 3578 3579 continue; 3580 } 3581 3582 if (NeedNonemptyTemplateHeader) { 3583 // In friend declarations we can have template-ids which don't 3584 // depend on the corresponding template parameter lists. But 3585 // assume that empty parameter lists are supposed to match this 3586 // template-id. 3587 if (IsFriend && T->isDependentType()) { 3588 if (ParamIdx < ParamLists.size() && 3589 DependsOnTemplateParameters(T, ParamLists[ParamIdx])) 3590 ExpectedTemplateParams = nullptr; 3591 else 3592 continue; 3593 } 3594 3595 if (ParamIdx < ParamLists.size()) { 3596 // Check the template parameter list, if we can. 3597 if (ExpectedTemplateParams && 3598 !TemplateParameterListsAreEqual(ParamLists[ParamIdx], 3599 ExpectedTemplateParams, 3600 !SuppressDiagnostic, TPL_TemplateMatch)) 3601 Invalid = true; 3602 3603 if (!Invalid && 3604 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr, 3605 TPC_ClassTemplateMember)) 3606 Invalid = true; 3607 3608 ++ParamIdx; 3609 continue; 3610 } 3611 3612 if (!SuppressDiagnostic) 3613 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters) 3614 << T 3615 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS); 3616 Invalid = true; 3617 continue; 3618 } 3619 } 3620 3621 // If there were at least as many template-ids as there were template 3622 // parameter lists, then there are no template parameter lists remaining for 3623 // the declaration itself. 3624 if (ParamIdx >= ParamLists.size()) { 3625 if (TemplateId && !IsFriend) { 3626 // We don't have a template header for the declaration itself, but we 3627 // should. 3628 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc, 3629 TemplateId->RAngleLoc)); 3630 3631 // Fabricate an empty template parameter list for the invented header. 3632 return TemplateParameterList::Create(Context, SourceLocation(), 3633 SourceLocation(), std::nullopt, 3634 SourceLocation(), nullptr); 3635 } 3636 3637 return nullptr; 3638 } 3639 3640 // If there were too many template parameter lists, complain about that now. 3641 if (ParamIdx < ParamLists.size() - 1) { 3642 bool HasAnyExplicitSpecHeader = false; 3643 bool AllExplicitSpecHeaders = true; 3644 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) { 3645 if (ParamLists[I]->size() == 0) 3646 HasAnyExplicitSpecHeader = true; 3647 else 3648 AllExplicitSpecHeaders = false; 3649 } 3650 3651 if (!SuppressDiagnostic) 3652 Diag(ParamLists[ParamIdx]->getTemplateLoc(), 3653 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers 3654 : diag::err_template_spec_extra_headers) 3655 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(), 3656 ParamLists[ParamLists.size() - 2]->getRAngleLoc()); 3657 3658 // If there was a specialization somewhere, such that 'template<>' is 3659 // not required, and there were any 'template<>' headers, note where the 3660 // specialization occurred. 3661 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader && 3662 !SuppressDiagnostic) 3663 Diag(ExplicitSpecLoc, 3664 diag::note_explicit_template_spec_does_not_need_header) 3665 << NestedTypes.back(); 3666 3667 // We have a template parameter list with no corresponding scope, which 3668 // means that the resulting template declaration can't be instantiated 3669 // properly (we'll end up with dependent nodes when we shouldn't). 3670 if (!AllExplicitSpecHeaders) 3671 Invalid = true; 3672 } 3673 3674 // C++ [temp.expl.spec]p16: 3675 // In an explicit specialization declaration for a member of a class 3676 // template or a member template that ap- pears in namespace scope, the 3677 // member template and some of its enclosing class templates may remain 3678 // unspecialized, except that the declaration shall not explicitly 3679 // specialize a class member template if its en- closing class templates 3680 // are not explicitly specialized as well. 3681 if (ParamLists.back()->size() == 0 && 3682 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(), 3683 false)) 3684 return nullptr; 3685 3686 // Return the last template parameter list, which corresponds to the 3687 // entity being declared. 3688 return ParamLists.back(); 3689 } 3690 3691 void Sema::NoteAllFoundTemplates(TemplateName Name) { 3692 if (TemplateDecl *Template = Name.getAsTemplateDecl()) { 3693 Diag(Template->getLocation(), diag::note_template_declared_here) 3694 << (isa<FunctionTemplateDecl>(Template) 3695 ? 0 3696 : isa<ClassTemplateDecl>(Template) 3697 ? 1 3698 : isa<VarTemplateDecl>(Template) 3699 ? 2 3700 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4) 3701 << Template->getDeclName(); 3702 return; 3703 } 3704 3705 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) { 3706 for (OverloadedTemplateStorage::iterator I = OST->begin(), 3707 IEnd = OST->end(); 3708 I != IEnd; ++I) 3709 Diag((*I)->getLocation(), diag::note_template_declared_here) 3710 << 0 << (*I)->getDeclName(); 3711 3712 return; 3713 } 3714 } 3715 3716 static QualType 3717 checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD, 3718 ArrayRef<TemplateArgument> Converted, 3719 SourceLocation TemplateLoc, 3720 TemplateArgumentListInfo &TemplateArgs) { 3721 ASTContext &Context = SemaRef.getASTContext(); 3722 3723 switch (BTD->getBuiltinTemplateKind()) { 3724 case BTK__make_integer_seq: { 3725 // Specializations of __make_integer_seq<S, T, N> are treated like 3726 // S<T, 0, ..., N-1>. 3727 3728 QualType OrigType = Converted[1].getAsType(); 3729 // C++14 [inteseq.intseq]p1: 3730 // T shall be an integer type. 3731 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) { 3732 SemaRef.Diag(TemplateArgs[1].getLocation(), 3733 diag::err_integer_sequence_integral_element_type); 3734 return QualType(); 3735 } 3736 3737 TemplateArgument NumArgsArg = Converted[2]; 3738 if (NumArgsArg.isDependent()) 3739 return Context.getCanonicalTemplateSpecializationType(TemplateName(BTD), 3740 Converted); 3741 3742 TemplateArgumentListInfo SyntheticTemplateArgs; 3743 // The type argument, wrapped in substitution sugar, gets reused as the 3744 // first template argument in the synthetic template argument list. 3745 SyntheticTemplateArgs.addArgument( 3746 TemplateArgumentLoc(TemplateArgument(OrigType), 3747 SemaRef.Context.getTrivialTypeSourceInfo( 3748 OrigType, TemplateArgs[1].getLocation()))); 3749 3750 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) { 3751 // Expand N into 0 ... N-1. 3752 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned()); 3753 I < NumArgs; ++I) { 3754 TemplateArgument TA(Context, I, OrigType); 3755 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc( 3756 TA, OrigType, TemplateArgs[2].getLocation())); 3757 } 3758 } else { 3759 // C++14 [inteseq.make]p1: 3760 // If N is negative the program is ill-formed. 3761 SemaRef.Diag(TemplateArgs[2].getLocation(), 3762 diag::err_integer_sequence_negative_length); 3763 return QualType(); 3764 } 3765 3766 // The first template argument will be reused as the template decl that 3767 // our synthetic template arguments will be applied to. 3768 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(), 3769 TemplateLoc, SyntheticTemplateArgs); 3770 } 3771 3772 case BTK__type_pack_element: 3773 // Specializations of 3774 // __type_pack_element<Index, T_1, ..., T_N> 3775 // are treated like T_Index. 3776 assert(Converted.size() == 2 && 3777 "__type_pack_element should be given an index and a parameter pack"); 3778 3779 TemplateArgument IndexArg = Converted[0], Ts = Converted[1]; 3780 if (IndexArg.isDependent() || Ts.isDependent()) 3781 return Context.getCanonicalTemplateSpecializationType(TemplateName(BTD), 3782 Converted); 3783 3784 llvm::APSInt Index = IndexArg.getAsIntegral(); 3785 assert(Index >= 0 && "the index used with __type_pack_element should be of " 3786 "type std::size_t, and hence be non-negative"); 3787 // If the Index is out of bounds, the program is ill-formed. 3788 if (Index >= Ts.pack_size()) { 3789 SemaRef.Diag(TemplateArgs[0].getLocation(), 3790 diag::err_type_pack_element_out_of_bounds); 3791 return QualType(); 3792 } 3793 3794 // We simply return the type at index `Index`. 3795 int64_t N = Index.getExtValue(); 3796 return Ts.getPackAsArray()[N].getAsType(); 3797 } 3798 llvm_unreachable("unexpected BuiltinTemplateDecl!"); 3799 } 3800 3801 /// Determine whether this alias template is "enable_if_t". 3802 /// libc++ >=14 uses "__enable_if_t" in C++11 mode. 3803 static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) { 3804 return AliasTemplate->getName().equals("enable_if_t") || 3805 AliasTemplate->getName().equals("__enable_if_t"); 3806 } 3807 3808 /// Collect all of the separable terms in the given condition, which 3809 /// might be a conjunction. 3810 /// 3811 /// FIXME: The right answer is to convert the logical expression into 3812 /// disjunctive normal form, so we can find the first failed term 3813 /// within each possible clause. 3814 static void collectConjunctionTerms(Expr *Clause, 3815 SmallVectorImpl<Expr *> &Terms) { 3816 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) { 3817 if (BinOp->getOpcode() == BO_LAnd) { 3818 collectConjunctionTerms(BinOp->getLHS(), Terms); 3819 collectConjunctionTerms(BinOp->getRHS(), Terms); 3820 return; 3821 } 3822 } 3823 3824 Terms.push_back(Clause); 3825 } 3826 3827 // The ranges-v3 library uses an odd pattern of a top-level "||" with 3828 // a left-hand side that is value-dependent but never true. Identify 3829 // the idiom and ignore that term. 3830 static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) { 3831 // Top-level '||'. 3832 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts()); 3833 if (!BinOp) return Cond; 3834 3835 if (BinOp->getOpcode() != BO_LOr) return Cond; 3836 3837 // With an inner '==' that has a literal on the right-hand side. 3838 Expr *LHS = BinOp->getLHS(); 3839 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts()); 3840 if (!InnerBinOp) return Cond; 3841 3842 if (InnerBinOp->getOpcode() != BO_EQ || 3843 !isa<IntegerLiteral>(InnerBinOp->getRHS())) 3844 return Cond; 3845 3846 // If the inner binary operation came from a macro expansion named 3847 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side 3848 // of the '||', which is the real, user-provided condition. 3849 SourceLocation Loc = InnerBinOp->getExprLoc(); 3850 if (!Loc.isMacroID()) return Cond; 3851 3852 StringRef MacroName = PP.getImmediateMacroName(Loc); 3853 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_") 3854 return BinOp->getRHS(); 3855 3856 return Cond; 3857 } 3858 3859 namespace { 3860 3861 // A PrinterHelper that prints more helpful diagnostics for some sub-expressions 3862 // within failing boolean expression, such as substituting template parameters 3863 // for actual types. 3864 class FailedBooleanConditionPrinterHelper : public PrinterHelper { 3865 public: 3866 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P) 3867 : Policy(P) {} 3868 3869 bool handledStmt(Stmt *E, raw_ostream &OS) override { 3870 const auto *DR = dyn_cast<DeclRefExpr>(E); 3871 if (DR && DR->getQualifier()) { 3872 // If this is a qualified name, expand the template arguments in nested 3873 // qualifiers. 3874 DR->getQualifier()->print(OS, Policy, true); 3875 // Then print the decl itself. 3876 const ValueDecl *VD = DR->getDecl(); 3877 OS << VD->getName(); 3878 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) { 3879 // This is a template variable, print the expanded template arguments. 3880 printTemplateArgumentList( 3881 OS, IV->getTemplateArgs().asArray(), Policy, 3882 IV->getSpecializedTemplate()->getTemplateParameters()); 3883 } 3884 return true; 3885 } 3886 return false; 3887 } 3888 3889 private: 3890 const PrintingPolicy Policy; 3891 }; 3892 3893 } // end anonymous namespace 3894 3895 std::pair<Expr *, std::string> 3896 Sema::findFailedBooleanCondition(Expr *Cond) { 3897 Cond = lookThroughRangesV3Condition(PP, Cond); 3898 3899 // Separate out all of the terms in a conjunction. 3900 SmallVector<Expr *, 4> Terms; 3901 collectConjunctionTerms(Cond, Terms); 3902 3903 // Determine which term failed. 3904 Expr *FailedCond = nullptr; 3905 for (Expr *Term : Terms) { 3906 Expr *TermAsWritten = Term->IgnoreParenImpCasts(); 3907 3908 // Literals are uninteresting. 3909 if (isa<CXXBoolLiteralExpr>(TermAsWritten) || 3910 isa<IntegerLiteral>(TermAsWritten)) 3911 continue; 3912 3913 // The initialization of the parameter from the argument is 3914 // a constant-evaluated context. 3915 EnterExpressionEvaluationContext ConstantEvaluated( 3916 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated); 3917 3918 bool Succeeded; 3919 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) && 3920 !Succeeded) { 3921 FailedCond = TermAsWritten; 3922 break; 3923 } 3924 } 3925 if (!FailedCond) 3926 FailedCond = Cond->IgnoreParenImpCasts(); 3927 3928 std::string Description; 3929 { 3930 llvm::raw_string_ostream Out(Description); 3931 PrintingPolicy Policy = getPrintingPolicy(); 3932 Policy.PrintCanonicalTypes = true; 3933 FailedBooleanConditionPrinterHelper Helper(Policy); 3934 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr); 3935 } 3936 return { FailedCond, Description }; 3937 } 3938 3939 QualType Sema::CheckTemplateIdType(TemplateName Name, 3940 SourceLocation TemplateLoc, 3941 TemplateArgumentListInfo &TemplateArgs) { 3942 DependentTemplateName *DTN 3943 = Name.getUnderlying().getAsDependentTemplateName(); 3944 if (DTN && DTN->isIdentifier()) 3945 // When building a template-id where the template-name is dependent, 3946 // assume the template is a type template. Either our assumption is 3947 // correct, or the code is ill-formed and will be diagnosed when the 3948 // dependent name is substituted. 3949 return Context.getDependentTemplateSpecializationType( 3950 ElaboratedTypeKeyword::None, DTN->getQualifier(), DTN->getIdentifier(), 3951 TemplateArgs.arguments()); 3952 3953 if (Name.getAsAssumedTemplateName() && 3954 resolveAssumedTemplateNameAsType(/*Scope*/nullptr, Name, TemplateLoc)) 3955 return QualType(); 3956 3957 TemplateDecl *Template = Name.getAsTemplateDecl(); 3958 if (!Template || isa<FunctionTemplateDecl>(Template) || 3959 isa<VarTemplateDecl>(Template) || isa<ConceptDecl>(Template)) { 3960 // We might have a substituted template template parameter pack. If so, 3961 // build a template specialization type for it. 3962 if (Name.getAsSubstTemplateTemplateParmPack()) 3963 return Context.getTemplateSpecializationType(Name, 3964 TemplateArgs.arguments()); 3965 3966 Diag(TemplateLoc, diag::err_template_id_not_a_type) 3967 << Name; 3968 NoteAllFoundTemplates(Name); 3969 return QualType(); 3970 } 3971 3972 // Check that the template argument list is well-formed for this 3973 // template. 3974 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted; 3975 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs, false, 3976 SugaredConverted, CanonicalConverted, 3977 /*UpdateArgsWithConversions=*/true)) 3978 return QualType(); 3979 3980 QualType CanonType; 3981 3982 if (TypeAliasTemplateDecl *AliasTemplate = 3983 dyn_cast<TypeAliasTemplateDecl>(Template)) { 3984 3985 // Find the canonical type for this type alias template specialization. 3986 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl(); 3987 if (Pattern->isInvalidDecl()) 3988 return QualType(); 3989 3990 // Only substitute for the innermost template argument list. 3991 MultiLevelTemplateArgumentList TemplateArgLists; 3992 TemplateArgLists.addOuterTemplateArguments(Template, CanonicalConverted, 3993 /*Final=*/false); 3994 TemplateArgLists.addOuterRetainedLevels( 3995 AliasTemplate->getTemplateParameters()->getDepth()); 3996 3997 LocalInstantiationScope Scope(*this); 3998 InstantiatingTemplate Inst(*this, TemplateLoc, Template); 3999 if (Inst.isInvalid()) 4000 return QualType(); 4001 4002 CanonType = SubstType(Pattern->getUnderlyingType(), 4003 TemplateArgLists, AliasTemplate->getLocation(), 4004 AliasTemplate->getDeclName()); 4005 if (CanonType.isNull()) { 4006 // If this was enable_if and we failed to find the nested type 4007 // within enable_if in a SFINAE context, dig out the specific 4008 // enable_if condition that failed and present that instead. 4009 if (isEnableIfAliasTemplate(AliasTemplate)) { 4010 if (auto DeductionInfo = isSFINAEContext()) { 4011 if (*DeductionInfo && 4012 (*DeductionInfo)->hasSFINAEDiagnostic() && 4013 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() == 4014 diag::err_typename_nested_not_found_enable_if && 4015 TemplateArgs[0].getArgument().getKind() 4016 == TemplateArgument::Expression) { 4017 Expr *FailedCond; 4018 std::string FailedDescription; 4019 std::tie(FailedCond, FailedDescription) = 4020 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression()); 4021 4022 // Remove the old SFINAE diagnostic. 4023 PartialDiagnosticAt OldDiag = 4024 {SourceLocation(), PartialDiagnostic::NullDiagnostic()}; 4025 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag); 4026 4027 // Add a new SFINAE diagnostic specifying which condition 4028 // failed. 4029 (*DeductionInfo)->addSFINAEDiagnostic( 4030 OldDiag.first, 4031 PDiag(diag::err_typename_nested_not_found_requirement) 4032 << FailedDescription 4033 << FailedCond->getSourceRange()); 4034 } 4035 } 4036 } 4037 4038 return QualType(); 4039 } 4040 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) { 4041 CanonType = checkBuiltinTemplateIdType(*this, BTD, SugaredConverted, 4042 TemplateLoc, TemplateArgs); 4043 } else if (Name.isDependent() || 4044 TemplateSpecializationType::anyDependentTemplateArguments( 4045 TemplateArgs, CanonicalConverted)) { 4046 // This class template specialization is a dependent 4047 // type. Therefore, its canonical type is another class template 4048 // specialization type that contains all of the converted 4049 // arguments in canonical form. This ensures that, e.g., A<T> and 4050 // A<T, T> have identical types when A is declared as: 4051 // 4052 // template<typename T, typename U = T> struct A; 4053 CanonType = Context.getCanonicalTemplateSpecializationType( 4054 Name, CanonicalConverted); 4055 4056 // This might work out to be a current instantiation, in which 4057 // case the canonical type needs to be the InjectedClassNameType. 4058 // 4059 // TODO: in theory this could be a simple hashtable lookup; most 4060 // changes to CurContext don't change the set of current 4061 // instantiations. 4062 if (isa<ClassTemplateDecl>(Template)) { 4063 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) { 4064 // If we get out to a namespace, we're done. 4065 if (Ctx->isFileContext()) break; 4066 4067 // If this isn't a record, keep looking. 4068 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx); 4069 if (!Record) continue; 4070 4071 // Look for one of the two cases with InjectedClassNameTypes 4072 // and check whether it's the same template. 4073 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) && 4074 !Record->getDescribedClassTemplate()) 4075 continue; 4076 4077 // Fetch the injected class name type and check whether its 4078 // injected type is equal to the type we just built. 4079 QualType ICNT = Context.getTypeDeclType(Record); 4080 QualType Injected = cast<InjectedClassNameType>(ICNT) 4081 ->getInjectedSpecializationType(); 4082 4083 if (CanonType != Injected->getCanonicalTypeInternal()) 4084 continue; 4085 4086 // If so, the canonical type of this TST is the injected 4087 // class name type of the record we just found. 4088 assert(ICNT.isCanonical()); 4089 CanonType = ICNT; 4090 break; 4091 } 4092 } 4093 } else if (ClassTemplateDecl *ClassTemplate = 4094 dyn_cast<ClassTemplateDecl>(Template)) { 4095 // Find the class template specialization declaration that 4096 // corresponds to these arguments. 4097 void *InsertPos = nullptr; 4098 ClassTemplateSpecializationDecl *Decl = 4099 ClassTemplate->findSpecialization(CanonicalConverted, InsertPos); 4100 if (!Decl) { 4101 // This is the first time we have referenced this class template 4102 // specialization. Create the canonical declaration and add it to 4103 // the set of specializations. 4104 Decl = ClassTemplateSpecializationDecl::Create( 4105 Context, ClassTemplate->getTemplatedDecl()->getTagKind(), 4106 ClassTemplate->getDeclContext(), 4107 ClassTemplate->getTemplatedDecl()->getBeginLoc(), 4108 ClassTemplate->getLocation(), ClassTemplate, CanonicalConverted, 4109 nullptr); 4110 ClassTemplate->AddSpecialization(Decl, InsertPos); 4111 if (ClassTemplate->isOutOfLine()) 4112 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext()); 4113 } 4114 4115 if (Decl->getSpecializationKind() == TSK_Undeclared && 4116 ClassTemplate->getTemplatedDecl()->hasAttrs()) { 4117 InstantiatingTemplate Inst(*this, TemplateLoc, Decl); 4118 if (!Inst.isInvalid()) { 4119 MultiLevelTemplateArgumentList TemplateArgLists(Template, 4120 CanonicalConverted, 4121 /*Final=*/false); 4122 InstantiateAttrsForDecl(TemplateArgLists, 4123 ClassTemplate->getTemplatedDecl(), Decl); 4124 } 4125 } 4126 4127 // Diagnose uses of this specialization. 4128 (void)DiagnoseUseOfDecl(Decl, TemplateLoc); 4129 4130 CanonType = Context.getTypeDeclType(Decl); 4131 assert(isa<RecordType>(CanonType) && 4132 "type of non-dependent specialization is not a RecordType"); 4133 } else { 4134 llvm_unreachable("Unhandled template kind"); 4135 } 4136 4137 // Build the fully-sugared type for this class template 4138 // specialization, which refers back to the class template 4139 // specialization we created or found. 4140 return Context.getTemplateSpecializationType(Name, TemplateArgs.arguments(), 4141 CanonType); 4142 } 4143 4144 void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName, 4145 TemplateNameKind &TNK, 4146 SourceLocation NameLoc, 4147 IdentifierInfo *&II) { 4148 assert(TNK == TNK_Undeclared_template && "not an undeclared template name"); 4149 4150 TemplateName Name = ParsedName.get(); 4151 auto *ATN = Name.getAsAssumedTemplateName(); 4152 assert(ATN && "not an assumed template name"); 4153 II = ATN->getDeclName().getAsIdentifierInfo(); 4154 4155 if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) { 4156 // Resolved to a type template name. 4157 ParsedName = TemplateTy::make(Name); 4158 TNK = TNK_Type_template; 4159 } 4160 } 4161 4162 bool Sema::resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name, 4163 SourceLocation NameLoc, 4164 bool Diagnose) { 4165 // We assumed this undeclared identifier to be an (ADL-only) function 4166 // template name, but it was used in a context where a type was required. 4167 // Try to typo-correct it now. 4168 AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName(); 4169 assert(ATN && "not an assumed template name"); 4170 4171 LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName); 4172 struct CandidateCallback : CorrectionCandidateCallback { 4173 bool ValidateCandidate(const TypoCorrection &TC) override { 4174 return TC.getCorrectionDecl() && 4175 getAsTypeTemplateDecl(TC.getCorrectionDecl()); 4176 } 4177 std::unique_ptr<CorrectionCandidateCallback> clone() override { 4178 return std::make_unique<CandidateCallback>(*this); 4179 } 4180 } FilterCCC; 4181 4182 TypoCorrection Corrected = 4183 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr, 4184 FilterCCC, CTK_ErrorRecovery); 4185 if (Corrected && Corrected.getFoundDecl()) { 4186 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) 4187 << ATN->getDeclName()); 4188 Name = TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>()); 4189 return false; 4190 } 4191 4192 if (Diagnose) 4193 Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName(); 4194 return true; 4195 } 4196 4197 TypeResult Sema::ActOnTemplateIdType( 4198 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 4199 TemplateTy TemplateD, IdentifierInfo *TemplateII, 4200 SourceLocation TemplateIILoc, SourceLocation LAngleLoc, 4201 ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc, 4202 bool IsCtorOrDtorName, bool IsClassName, 4203 ImplicitTypenameContext AllowImplicitTypename) { 4204 if (SS.isInvalid()) 4205 return true; 4206 4207 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) { 4208 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false); 4209 4210 // C++ [temp.res]p3: 4211 // A qualified-id that refers to a type and in which the 4212 // nested-name-specifier depends on a template-parameter (14.6.2) 4213 // shall be prefixed by the keyword typename to indicate that the 4214 // qualified-id denotes a type, forming an 4215 // elaborated-type-specifier (7.1.5.3). 4216 if (!LookupCtx && isDependentScopeSpecifier(SS)) { 4217 // C++2a relaxes some of those restrictions in [temp.res]p5. 4218 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) { 4219 if (getLangOpts().CPlusPlus20) 4220 Diag(SS.getBeginLoc(), diag::warn_cxx17_compat_implicit_typename); 4221 else 4222 Diag(SS.getBeginLoc(), diag::ext_implicit_typename) 4223 << SS.getScopeRep() << TemplateII->getName() 4224 << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename "); 4225 } else 4226 Diag(SS.getBeginLoc(), diag::err_typename_missing_template) 4227 << SS.getScopeRep() << TemplateII->getName(); 4228 4229 // FIXME: This is not quite correct recovery as we don't transform SS 4230 // into the corresponding dependent form (and we don't diagnose missing 4231 // 'template' keywords within SS as a result). 4232 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc, 4233 TemplateD, TemplateII, TemplateIILoc, LAngleLoc, 4234 TemplateArgsIn, RAngleLoc); 4235 } 4236 4237 // Per C++ [class.qual]p2, if the template-id was an injected-class-name, 4238 // it's not actually allowed to be used as a type in most cases. Because 4239 // we annotate it before we know whether it's valid, we have to check for 4240 // this case here. 4241 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 4242 if (LookupRD && LookupRD->getIdentifier() == TemplateII) { 4243 Diag(TemplateIILoc, 4244 TemplateKWLoc.isInvalid() 4245 ? diag::err_out_of_line_qualified_id_type_names_constructor 4246 : diag::ext_out_of_line_qualified_id_type_names_constructor) 4247 << TemplateII << 0 /*injected-class-name used as template name*/ 4248 << 1 /*if any keyword was present, it was 'template'*/; 4249 } 4250 } 4251 4252 TemplateName Template = TemplateD.get(); 4253 if (Template.getAsAssumedTemplateName() && 4254 resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc)) 4255 return true; 4256 4257 // Translate the parser's template argument list in our AST format. 4258 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); 4259 translateTemplateArguments(TemplateArgsIn, TemplateArgs); 4260 4261 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) { 4262 assert(SS.getScopeRep() == DTN->getQualifier()); 4263 QualType T = Context.getDependentTemplateSpecializationType( 4264 ElaboratedTypeKeyword::None, DTN->getQualifier(), DTN->getIdentifier(), 4265 TemplateArgs.arguments()); 4266 // Build type-source information. 4267 TypeLocBuilder TLB; 4268 DependentTemplateSpecializationTypeLoc SpecTL 4269 = TLB.push<DependentTemplateSpecializationTypeLoc>(T); 4270 SpecTL.setElaboratedKeywordLoc(SourceLocation()); 4271 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context)); 4272 SpecTL.setTemplateKeywordLoc(TemplateKWLoc); 4273 SpecTL.setTemplateNameLoc(TemplateIILoc); 4274 SpecTL.setLAngleLoc(LAngleLoc); 4275 SpecTL.setRAngleLoc(RAngleLoc); 4276 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I) 4277 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo()); 4278 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T)); 4279 } 4280 4281 QualType SpecTy = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs); 4282 if (SpecTy.isNull()) 4283 return true; 4284 4285 // Build type-source information. 4286 TypeLocBuilder TLB; 4287 TemplateSpecializationTypeLoc SpecTL = 4288 TLB.push<TemplateSpecializationTypeLoc>(SpecTy); 4289 SpecTL.setTemplateKeywordLoc(TemplateKWLoc); 4290 SpecTL.setTemplateNameLoc(TemplateIILoc); 4291 SpecTL.setLAngleLoc(LAngleLoc); 4292 SpecTL.setRAngleLoc(RAngleLoc); 4293 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i) 4294 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo()); 4295 4296 // Create an elaborated-type-specifier containing the nested-name-specifier. 4297 QualType ElTy = 4298 getElaboratedType(ElaboratedTypeKeyword::None, 4299 !IsCtorOrDtorName ? SS : CXXScopeSpec(), SpecTy); 4300 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(ElTy); 4301 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 4302 if (!ElabTL.isEmpty()) 4303 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 4304 return CreateParsedType(ElTy, TLB.getTypeSourceInfo(Context, ElTy)); 4305 } 4306 4307 TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK, 4308 TypeSpecifierType TagSpec, 4309 SourceLocation TagLoc, 4310 CXXScopeSpec &SS, 4311 SourceLocation TemplateKWLoc, 4312 TemplateTy TemplateD, 4313 SourceLocation TemplateLoc, 4314 SourceLocation LAngleLoc, 4315 ASTTemplateArgsPtr TemplateArgsIn, 4316 SourceLocation RAngleLoc) { 4317 if (SS.isInvalid()) 4318 return TypeResult(true); 4319 4320 TemplateName Template = TemplateD.get(); 4321 4322 // Translate the parser's template argument list in our AST format. 4323 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); 4324 translateTemplateArguments(TemplateArgsIn, TemplateArgs); 4325 4326 // Determine the tag kind 4327 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 4328 ElaboratedTypeKeyword Keyword 4329 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind); 4330 4331 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) { 4332 assert(SS.getScopeRep() == DTN->getQualifier()); 4333 QualType T = Context.getDependentTemplateSpecializationType( 4334 Keyword, DTN->getQualifier(), DTN->getIdentifier(), 4335 TemplateArgs.arguments()); 4336 4337 // Build type-source information. 4338 TypeLocBuilder TLB; 4339 DependentTemplateSpecializationTypeLoc SpecTL 4340 = TLB.push<DependentTemplateSpecializationTypeLoc>(T); 4341 SpecTL.setElaboratedKeywordLoc(TagLoc); 4342 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context)); 4343 SpecTL.setTemplateKeywordLoc(TemplateKWLoc); 4344 SpecTL.setTemplateNameLoc(TemplateLoc); 4345 SpecTL.setLAngleLoc(LAngleLoc); 4346 SpecTL.setRAngleLoc(RAngleLoc); 4347 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I) 4348 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo()); 4349 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T)); 4350 } 4351 4352 if (TypeAliasTemplateDecl *TAT = 4353 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) { 4354 // C++0x [dcl.type.elab]p2: 4355 // If the identifier resolves to a typedef-name or the simple-template-id 4356 // resolves to an alias template specialization, the 4357 // elaborated-type-specifier is ill-formed. 4358 Diag(TemplateLoc, diag::err_tag_reference_non_tag) 4359 << TAT << NTK_TypeAliasTemplate << llvm::to_underlying(TagKind); 4360 Diag(TAT->getLocation(), diag::note_declared_at); 4361 } 4362 4363 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs); 4364 if (Result.isNull()) 4365 return TypeResult(true); 4366 4367 // Check the tag kind 4368 if (const RecordType *RT = Result->getAs<RecordType>()) { 4369 RecordDecl *D = RT->getDecl(); 4370 4371 IdentifierInfo *Id = D->getIdentifier(); 4372 assert(Id && "templated class must have an identifier"); 4373 4374 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition, 4375 TagLoc, Id)) { 4376 Diag(TagLoc, diag::err_use_with_wrong_tag) 4377 << Result 4378 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName()); 4379 Diag(D->getLocation(), diag::note_previous_use); 4380 } 4381 } 4382 4383 // Provide source-location information for the template specialization. 4384 TypeLocBuilder TLB; 4385 TemplateSpecializationTypeLoc SpecTL 4386 = TLB.push<TemplateSpecializationTypeLoc>(Result); 4387 SpecTL.setTemplateKeywordLoc(TemplateKWLoc); 4388 SpecTL.setTemplateNameLoc(TemplateLoc); 4389 SpecTL.setLAngleLoc(LAngleLoc); 4390 SpecTL.setRAngleLoc(RAngleLoc); 4391 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i) 4392 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo()); 4393 4394 // Construct an elaborated type containing the nested-name-specifier (if any) 4395 // and tag keyword. 4396 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result); 4397 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result); 4398 ElabTL.setElaboratedKeywordLoc(TagLoc); 4399 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 4400 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result)); 4401 } 4402 4403 static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized, 4404 NamedDecl *PrevDecl, 4405 SourceLocation Loc, 4406 bool IsPartialSpecialization); 4407 4408 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D); 4409 4410 static bool isTemplateArgumentTemplateParameter( 4411 const TemplateArgument &Arg, unsigned Depth, unsigned Index) { 4412 switch (Arg.getKind()) { 4413 case TemplateArgument::Null: 4414 case TemplateArgument::NullPtr: 4415 case TemplateArgument::Integral: 4416 case TemplateArgument::Declaration: 4417 case TemplateArgument::Pack: 4418 case TemplateArgument::TemplateExpansion: 4419 return false; 4420 4421 case TemplateArgument::Type: { 4422 QualType Type = Arg.getAsType(); 4423 const TemplateTypeParmType *TPT = 4424 Arg.getAsType()->getAs<TemplateTypeParmType>(); 4425 return TPT && !Type.hasQualifiers() && 4426 TPT->getDepth() == Depth && TPT->getIndex() == Index; 4427 } 4428 4429 case TemplateArgument::Expression: { 4430 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr()); 4431 if (!DRE || !DRE->getDecl()) 4432 return false; 4433 const NonTypeTemplateParmDecl *NTTP = 4434 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()); 4435 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index; 4436 } 4437 4438 case TemplateArgument::Template: 4439 const TemplateTemplateParmDecl *TTP = 4440 dyn_cast_or_null<TemplateTemplateParmDecl>( 4441 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl()); 4442 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index; 4443 } 4444 llvm_unreachable("unexpected kind of template argument"); 4445 } 4446 4447 static bool isSameAsPrimaryTemplate(TemplateParameterList *Params, 4448 ArrayRef<TemplateArgument> Args) { 4449 if (Params->size() != Args.size()) 4450 return false; 4451 4452 unsigned Depth = Params->getDepth(); 4453 4454 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 4455 TemplateArgument Arg = Args[I]; 4456 4457 // If the parameter is a pack expansion, the argument must be a pack 4458 // whose only element is a pack expansion. 4459 if (Params->getParam(I)->isParameterPack()) { 4460 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 || 4461 !Arg.pack_begin()->isPackExpansion()) 4462 return false; 4463 Arg = Arg.pack_begin()->getPackExpansionPattern(); 4464 } 4465 4466 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I)) 4467 return false; 4468 } 4469 4470 return true; 4471 } 4472 4473 template<typename PartialSpecDecl> 4474 static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) { 4475 if (Partial->getDeclContext()->isDependentContext()) 4476 return; 4477 4478 // FIXME: Get the TDK from deduction in order to provide better diagnostics 4479 // for non-substitution-failure issues? 4480 TemplateDeductionInfo Info(Partial->getLocation()); 4481 if (S.isMoreSpecializedThanPrimary(Partial, Info)) 4482 return; 4483 4484 auto *Template = Partial->getSpecializedTemplate(); 4485 S.Diag(Partial->getLocation(), 4486 diag::ext_partial_spec_not_more_specialized_than_primary) 4487 << isa<VarTemplateDecl>(Template); 4488 4489 if (Info.hasSFINAEDiagnostic()) { 4490 PartialDiagnosticAt Diag = {SourceLocation(), 4491 PartialDiagnostic::NullDiagnostic()}; 4492 Info.takeSFINAEDiagnostic(Diag); 4493 SmallString<128> SFINAEArgString; 4494 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString); 4495 S.Diag(Diag.first, 4496 diag::note_partial_spec_not_more_specialized_than_primary) 4497 << SFINAEArgString; 4498 } 4499 4500 S.NoteTemplateLocation(*Template); 4501 SmallVector<const Expr *, 3> PartialAC, TemplateAC; 4502 Template->getAssociatedConstraints(TemplateAC); 4503 Partial->getAssociatedConstraints(PartialAC); 4504 S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Partial, PartialAC, Template, 4505 TemplateAC); 4506 } 4507 4508 static void 4509 noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams, 4510 const llvm::SmallBitVector &DeducibleParams) { 4511 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) { 4512 if (!DeducibleParams[I]) { 4513 NamedDecl *Param = TemplateParams->getParam(I); 4514 if (Param->getDeclName()) 4515 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter) 4516 << Param->getDeclName(); 4517 else 4518 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter) 4519 << "(anonymous)"; 4520 } 4521 } 4522 } 4523 4524 4525 template<typename PartialSpecDecl> 4526 static void checkTemplatePartialSpecialization(Sema &S, 4527 PartialSpecDecl *Partial) { 4528 // C++1z [temp.class.spec]p8: (DR1495) 4529 // - The specialization shall be more specialized than the primary 4530 // template (14.5.5.2). 4531 checkMoreSpecializedThanPrimary(S, Partial); 4532 4533 // C++ [temp.class.spec]p8: (DR1315) 4534 // - Each template-parameter shall appear at least once in the 4535 // template-id outside a non-deduced context. 4536 // C++1z [temp.class.spec.match]p3 (P0127R2) 4537 // If the template arguments of a partial specialization cannot be 4538 // deduced because of the structure of its template-parameter-list 4539 // and the template-id, the program is ill-formed. 4540 auto *TemplateParams = Partial->getTemplateParameters(); 4541 llvm::SmallBitVector DeducibleParams(TemplateParams->size()); 4542 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true, 4543 TemplateParams->getDepth(), DeducibleParams); 4544 4545 if (!DeducibleParams.all()) { 4546 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count(); 4547 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible) 4548 << isa<VarTemplatePartialSpecializationDecl>(Partial) 4549 << (NumNonDeducible > 1) 4550 << SourceRange(Partial->getLocation(), 4551 Partial->getTemplateArgsAsWritten()->RAngleLoc); 4552 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams); 4553 } 4554 } 4555 4556 void Sema::CheckTemplatePartialSpecialization( 4557 ClassTemplatePartialSpecializationDecl *Partial) { 4558 checkTemplatePartialSpecialization(*this, Partial); 4559 } 4560 4561 void Sema::CheckTemplatePartialSpecialization( 4562 VarTemplatePartialSpecializationDecl *Partial) { 4563 checkTemplatePartialSpecialization(*this, Partial); 4564 } 4565 4566 void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) { 4567 // C++1z [temp.param]p11: 4568 // A template parameter of a deduction guide template that does not have a 4569 // default-argument shall be deducible from the parameter-type-list of the 4570 // deduction guide template. 4571 auto *TemplateParams = TD->getTemplateParameters(); 4572 llvm::SmallBitVector DeducibleParams(TemplateParams->size()); 4573 MarkDeducedTemplateParameters(TD, DeducibleParams); 4574 for (unsigned I = 0; I != TemplateParams->size(); ++I) { 4575 // A parameter pack is deducible (to an empty pack). 4576 auto *Param = TemplateParams->getParam(I); 4577 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param)) 4578 DeducibleParams[I] = true; 4579 } 4580 4581 if (!DeducibleParams.all()) { 4582 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count(); 4583 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible) 4584 << (NumNonDeducible > 1); 4585 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams); 4586 } 4587 } 4588 4589 DeclResult Sema::ActOnVarTemplateSpecialization( 4590 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc, 4591 TemplateParameterList *TemplateParams, StorageClass SC, 4592 bool IsPartialSpecialization) { 4593 // D must be variable template id. 4594 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId && 4595 "Variable template specialization is declared with a template id."); 4596 4597 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 4598 TemplateArgumentListInfo TemplateArgs = 4599 makeTemplateArgumentListInfo(*this, *TemplateId); 4600 SourceLocation TemplateNameLoc = D.getIdentifierLoc(); 4601 SourceLocation LAngleLoc = TemplateId->LAngleLoc; 4602 SourceLocation RAngleLoc = TemplateId->RAngleLoc; 4603 4604 TemplateName Name = TemplateId->Template.get(); 4605 4606 // The template-id must name a variable template. 4607 VarTemplateDecl *VarTemplate = 4608 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl()); 4609 if (!VarTemplate) { 4610 NamedDecl *FnTemplate; 4611 if (auto *OTS = Name.getAsOverloadedTemplate()) 4612 FnTemplate = *OTS->begin(); 4613 else 4614 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl()); 4615 if (FnTemplate) 4616 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method) 4617 << FnTemplate->getDeclName(); 4618 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template) 4619 << IsPartialSpecialization; 4620 } 4621 4622 // Check for unexpanded parameter packs in any of the template arguments. 4623 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 4624 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I], 4625 IsPartialSpecialization 4626 ? UPPC_PartialSpecialization 4627 : UPPC_ExplicitSpecialization)) 4628 return true; 4629 4630 // Check that the template argument list is well-formed for this 4631 // template. 4632 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted; 4633 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs, 4634 false, SugaredConverted, CanonicalConverted, 4635 /*UpdateArgsWithConversions=*/true)) 4636 return true; 4637 4638 // Find the variable template (partial) specialization declaration that 4639 // corresponds to these arguments. 4640 if (IsPartialSpecialization) { 4641 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate, 4642 TemplateArgs.size(), 4643 CanonicalConverted)) 4644 return true; 4645 4646 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we 4647 // also do them during instantiation. 4648 if (!Name.isDependent() && 4649 !TemplateSpecializationType::anyDependentTemplateArguments( 4650 TemplateArgs, CanonicalConverted)) { 4651 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized) 4652 << VarTemplate->getDeclName(); 4653 IsPartialSpecialization = false; 4654 } 4655 4656 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(), 4657 CanonicalConverted) && 4658 (!Context.getLangOpts().CPlusPlus20 || 4659 !TemplateParams->hasAssociatedConstraints())) { 4660 // C++ [temp.class.spec]p9b3: 4661 // 4662 // -- The argument list of the specialization shall not be identical 4663 // to the implicit argument list of the primary template. 4664 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template) 4665 << /*variable template*/ 1 4666 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord()) 4667 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc)); 4668 // FIXME: Recover from this by treating the declaration as a redeclaration 4669 // of the primary template. 4670 return true; 4671 } 4672 } 4673 4674 void *InsertPos = nullptr; 4675 VarTemplateSpecializationDecl *PrevDecl = nullptr; 4676 4677 if (IsPartialSpecialization) 4678 PrevDecl = VarTemplate->findPartialSpecialization( 4679 CanonicalConverted, TemplateParams, InsertPos); 4680 else 4681 PrevDecl = VarTemplate->findSpecialization(CanonicalConverted, InsertPos); 4682 4683 VarTemplateSpecializationDecl *Specialization = nullptr; 4684 4685 // Check whether we can declare a variable template specialization in 4686 // the current scope. 4687 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl, 4688 TemplateNameLoc, 4689 IsPartialSpecialization)) 4690 return true; 4691 4692 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) { 4693 // Since the only prior variable template specialization with these 4694 // arguments was referenced but not declared, reuse that 4695 // declaration node as our own, updating its source location and 4696 // the list of outer template parameters to reflect our new declaration. 4697 Specialization = PrevDecl; 4698 Specialization->setLocation(TemplateNameLoc); 4699 PrevDecl = nullptr; 4700 } else if (IsPartialSpecialization) { 4701 // Create a new class template partial specialization declaration node. 4702 VarTemplatePartialSpecializationDecl *PrevPartial = 4703 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl); 4704 VarTemplatePartialSpecializationDecl *Partial = 4705 VarTemplatePartialSpecializationDecl::Create( 4706 Context, VarTemplate->getDeclContext(), TemplateKWLoc, 4707 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC, 4708 CanonicalConverted, TemplateArgs); 4709 4710 if (!PrevPartial) 4711 VarTemplate->AddPartialSpecialization(Partial, InsertPos); 4712 Specialization = Partial; 4713 4714 // If we are providing an explicit specialization of a member variable 4715 // template specialization, make a note of that. 4716 if (PrevPartial && PrevPartial->getInstantiatedFromMember()) 4717 PrevPartial->setMemberSpecialization(); 4718 4719 CheckTemplatePartialSpecialization(Partial); 4720 } else { 4721 // Create a new class template specialization declaration node for 4722 // this explicit specialization or friend declaration. 4723 Specialization = VarTemplateSpecializationDecl::Create( 4724 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc, 4725 VarTemplate, DI->getType(), DI, SC, CanonicalConverted); 4726 Specialization->setTemplateArgsInfo(TemplateArgs); 4727 4728 if (!PrevDecl) 4729 VarTemplate->AddSpecialization(Specialization, InsertPos); 4730 } 4731 4732 // C++ [temp.expl.spec]p6: 4733 // If a template, a member template or the member of a class template is 4734 // explicitly specialized then that specialization shall be declared 4735 // before the first use of that specialization that would cause an implicit 4736 // instantiation to take place, in every translation unit in which such a 4737 // use occurs; no diagnostic is required. 4738 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) { 4739 bool Okay = false; 4740 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) { 4741 // Is there any previous explicit specialization declaration? 4742 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) { 4743 Okay = true; 4744 break; 4745 } 4746 } 4747 4748 if (!Okay) { 4749 SourceRange Range(TemplateNameLoc, RAngleLoc); 4750 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation) 4751 << Name << Range; 4752 4753 Diag(PrevDecl->getPointOfInstantiation(), 4754 diag::note_instantiation_required_here) 4755 << (PrevDecl->getTemplateSpecializationKind() != 4756 TSK_ImplicitInstantiation); 4757 return true; 4758 } 4759 } 4760 4761 Specialization->setTemplateKeywordLoc(TemplateKWLoc); 4762 Specialization->setLexicalDeclContext(CurContext); 4763 4764 // Add the specialization into its lexical context, so that it can 4765 // be seen when iterating through the list of declarations in that 4766 // context. However, specializations are not found by name lookup. 4767 CurContext->addDecl(Specialization); 4768 4769 // Note that this is an explicit specialization. 4770 Specialization->setSpecializationKind(TSK_ExplicitSpecialization); 4771 4772 if (PrevDecl) { 4773 // Check that this isn't a redefinition of this specialization, 4774 // merging with previous declarations. 4775 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName, 4776 forRedeclarationInCurContext()); 4777 PrevSpec.addDecl(PrevDecl); 4778 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec)); 4779 } else if (Specialization->isStaticDataMember() && 4780 Specialization->isOutOfLine()) { 4781 Specialization->setAccess(VarTemplate->getAccess()); 4782 } 4783 4784 return Specialization; 4785 } 4786 4787 namespace { 4788 /// A partial specialization whose template arguments have matched 4789 /// a given template-id. 4790 struct PartialSpecMatchResult { 4791 VarTemplatePartialSpecializationDecl *Partial; 4792 TemplateArgumentList *Args; 4793 }; 4794 } // end anonymous namespace 4795 4796 DeclResult 4797 Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc, 4798 SourceLocation TemplateNameLoc, 4799 const TemplateArgumentListInfo &TemplateArgs) { 4800 assert(Template && "A variable template id without template?"); 4801 4802 // Check that the template argument list is well-formed for this template. 4803 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted; 4804 if (CheckTemplateArgumentList( 4805 Template, TemplateNameLoc, 4806 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false, 4807 SugaredConverted, CanonicalConverted, 4808 /*UpdateArgsWithConversions=*/true)) 4809 return true; 4810 4811 // Produce a placeholder value if the specialization is dependent. 4812 if (Template->getDeclContext()->isDependentContext() || 4813 TemplateSpecializationType::anyDependentTemplateArguments( 4814 TemplateArgs, CanonicalConverted)) 4815 return DeclResult(); 4816 4817 // Find the variable template specialization declaration that 4818 // corresponds to these arguments. 4819 void *InsertPos = nullptr; 4820 if (VarTemplateSpecializationDecl *Spec = 4821 Template->findSpecialization(CanonicalConverted, InsertPos)) { 4822 checkSpecializationReachability(TemplateNameLoc, Spec); 4823 // If we already have a variable template specialization, return it. 4824 return Spec; 4825 } 4826 4827 // This is the first time we have referenced this variable template 4828 // specialization. Create the canonical declaration and add it to 4829 // the set of specializations, based on the closest partial specialization 4830 // that it represents. That is, 4831 VarDecl *InstantiationPattern = Template->getTemplatedDecl(); 4832 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack, 4833 CanonicalConverted); 4834 TemplateArgumentList *InstantiationArgs = &TemplateArgList; 4835 bool AmbiguousPartialSpec = false; 4836 typedef PartialSpecMatchResult MatchResult; 4837 SmallVector<MatchResult, 4> Matched; 4838 SourceLocation PointOfInstantiation = TemplateNameLoc; 4839 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation, 4840 /*ForTakingAddress=*/false); 4841 4842 // 1. Attempt to find the closest partial specialization that this 4843 // specializes, if any. 4844 // TODO: Unify with InstantiateClassTemplateSpecialization()? 4845 // Perhaps better after unification of DeduceTemplateArguments() and 4846 // getMoreSpecializedPartialSpecialization(). 4847 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs; 4848 Template->getPartialSpecializations(PartialSpecs); 4849 4850 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) { 4851 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I]; 4852 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 4853 4854 if (TemplateDeductionResult Result = 4855 DeduceTemplateArguments(Partial, TemplateArgList, Info)) { 4856 // Store the failed-deduction information for use in diagnostics, later. 4857 // TODO: Actually use the failed-deduction info? 4858 FailedCandidates.addCandidate().set( 4859 DeclAccessPair::make(Template, AS_public), Partial, 4860 MakeDeductionFailureInfo(Context, Result, Info)); 4861 (void)Result; 4862 } else { 4863 Matched.push_back(PartialSpecMatchResult()); 4864 Matched.back().Partial = Partial; 4865 Matched.back().Args = Info.takeCanonical(); 4866 } 4867 } 4868 4869 if (Matched.size() >= 1) { 4870 SmallVector<MatchResult, 4>::iterator Best = Matched.begin(); 4871 if (Matched.size() == 1) { 4872 // -- If exactly one matching specialization is found, the 4873 // instantiation is generated from that specialization. 4874 // We don't need to do anything for this. 4875 } else { 4876 // -- If more than one matching specialization is found, the 4877 // partial order rules (14.5.4.2) are used to determine 4878 // whether one of the specializations is more specialized 4879 // than the others. If none of the specializations is more 4880 // specialized than all of the other matching 4881 // specializations, then the use of the variable template is 4882 // ambiguous and the program is ill-formed. 4883 for (SmallVector<MatchResult, 4>::iterator P = Best + 1, 4884 PEnd = Matched.end(); 4885 P != PEnd; ++P) { 4886 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial, 4887 PointOfInstantiation) == 4888 P->Partial) 4889 Best = P; 4890 } 4891 4892 // Determine if the best partial specialization is more specialized than 4893 // the others. 4894 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(), 4895 PEnd = Matched.end(); 4896 P != PEnd; ++P) { 4897 if (P != Best && getMoreSpecializedPartialSpecialization( 4898 P->Partial, Best->Partial, 4899 PointOfInstantiation) != Best->Partial) { 4900 AmbiguousPartialSpec = true; 4901 break; 4902 } 4903 } 4904 } 4905 4906 // Instantiate using the best variable template partial specialization. 4907 InstantiationPattern = Best->Partial; 4908 InstantiationArgs = Best->Args; 4909 } else { 4910 // -- If no match is found, the instantiation is generated 4911 // from the primary template. 4912 // InstantiationPattern = Template->getTemplatedDecl(); 4913 } 4914 4915 // 2. Create the canonical declaration. 4916 // Note that we do not instantiate a definition until we see an odr-use 4917 // in DoMarkVarDeclReferenced(). 4918 // FIXME: LateAttrs et al.? 4919 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation( 4920 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs, 4921 CanonicalConverted, TemplateNameLoc /*, LateAttrs, StartingScope*/); 4922 if (!Decl) 4923 return true; 4924 4925 if (AmbiguousPartialSpec) { 4926 // Partial ordering did not produce a clear winner. Complain. 4927 Decl->setInvalidDecl(); 4928 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous) 4929 << Decl; 4930 4931 // Print the matching partial specializations. 4932 for (MatchResult P : Matched) 4933 Diag(P.Partial->getLocation(), diag::note_partial_spec_match) 4934 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(), 4935 *P.Args); 4936 return true; 4937 } 4938 4939 if (VarTemplatePartialSpecializationDecl *D = 4940 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern)) 4941 Decl->setInstantiationOf(D, InstantiationArgs); 4942 4943 checkSpecializationReachability(TemplateNameLoc, Decl); 4944 4945 assert(Decl && "No variable template specialization?"); 4946 return Decl; 4947 } 4948 4949 ExprResult 4950 Sema::CheckVarTemplateId(const CXXScopeSpec &SS, 4951 const DeclarationNameInfo &NameInfo, 4952 VarTemplateDecl *Template, SourceLocation TemplateLoc, 4953 const TemplateArgumentListInfo *TemplateArgs) { 4954 4955 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(), 4956 *TemplateArgs); 4957 if (Decl.isInvalid()) 4958 return ExprError(); 4959 4960 if (!Decl.get()) 4961 return ExprResult(); 4962 4963 VarDecl *Var = cast<VarDecl>(Decl.get()); 4964 if (!Var->getTemplateSpecializationKind()) 4965 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation, 4966 NameInfo.getLoc()); 4967 4968 // Build an ordinary singleton decl ref. 4969 return BuildDeclarationNameExpr(SS, NameInfo, Var, 4970 /*FoundD=*/nullptr, TemplateArgs); 4971 } 4972 4973 void Sema::diagnoseMissingTemplateArguments(TemplateName Name, 4974 SourceLocation Loc) { 4975 Diag(Loc, diag::err_template_missing_args) 4976 << (int)getTemplateNameKindForDiagnostics(Name) << Name; 4977 if (TemplateDecl *TD = Name.getAsTemplateDecl()) { 4978 NoteTemplateLocation(*TD, TD->getTemplateParameters()->getSourceRange()); 4979 } 4980 } 4981 4982 ExprResult 4983 Sema::CheckConceptTemplateId(const CXXScopeSpec &SS, 4984 SourceLocation TemplateKWLoc, 4985 const DeclarationNameInfo &ConceptNameInfo, 4986 NamedDecl *FoundDecl, 4987 ConceptDecl *NamedConcept, 4988 const TemplateArgumentListInfo *TemplateArgs) { 4989 assert(NamedConcept && "A concept template id without a template?"); 4990 4991 llvm::SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted; 4992 if (CheckTemplateArgumentList( 4993 NamedConcept, ConceptNameInfo.getLoc(), 4994 const_cast<TemplateArgumentListInfo &>(*TemplateArgs), 4995 /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted, 4996 /*UpdateArgsWithConversions=*/false)) 4997 return ExprError(); 4998 4999 auto *CSD = ImplicitConceptSpecializationDecl::Create( 5000 Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(), 5001 CanonicalConverted); 5002 ConstraintSatisfaction Satisfaction; 5003 bool AreArgsDependent = 5004 TemplateSpecializationType::anyDependentTemplateArguments( 5005 *TemplateArgs, CanonicalConverted); 5006 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CanonicalConverted, 5007 /*Final=*/false); 5008 LocalInstantiationScope Scope(*this); 5009 5010 EnterExpressionEvaluationContext EECtx{ 5011 *this, ExpressionEvaluationContext::ConstantEvaluated, CSD}; 5012 5013 if (!AreArgsDependent && 5014 CheckConstraintSatisfaction( 5015 NamedConcept, {NamedConcept->getConstraintExpr()}, MLTAL, 5016 SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(), 5017 TemplateArgs->getRAngleLoc()), 5018 Satisfaction)) 5019 return ExprError(); 5020 auto *CL = ConceptReference::Create( 5021 Context, 5022 SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc{}, 5023 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept, 5024 ASTTemplateArgumentListInfo::Create(Context, *TemplateArgs)); 5025 return ConceptSpecializationExpr::Create( 5026 Context, CL, CSD, AreArgsDependent ? nullptr : &Satisfaction); 5027 } 5028 5029 ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS, 5030 SourceLocation TemplateKWLoc, 5031 LookupResult &R, 5032 bool RequiresADL, 5033 const TemplateArgumentListInfo *TemplateArgs) { 5034 // FIXME: Can we do any checking at this point? I guess we could check the 5035 // template arguments that we have against the template name, if the template 5036 // name refers to a single template. That's not a terribly common case, 5037 // though. 5038 // foo<int> could identify a single function unambiguously 5039 // This approach does NOT work, since f<int>(1); 5040 // gets resolved prior to resorting to overload resolution 5041 // i.e., template<class T> void f(double); 5042 // vs template<class T, class U> void f(U); 5043 5044 // These should be filtered out by our callers. 5045 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid"); 5046 5047 // Non-function templates require a template argument list. 5048 if (auto *TD = R.getAsSingle<TemplateDecl>()) { 5049 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) { 5050 diagnoseMissingTemplateArguments(TemplateName(TD), R.getNameLoc()); 5051 return ExprError(); 5052 } 5053 } 5054 bool KnownDependent = false; 5055 // In C++1y, check variable template ids. 5056 if (R.getAsSingle<VarTemplateDecl>()) { 5057 ExprResult Res = CheckVarTemplateId(SS, R.getLookupNameInfo(), 5058 R.getAsSingle<VarTemplateDecl>(), 5059 TemplateKWLoc, TemplateArgs); 5060 if (Res.isInvalid() || Res.isUsable()) 5061 return Res; 5062 // Result is dependent. Carry on to build an UnresolvedLookupEpxr. 5063 KnownDependent = true; 5064 } 5065 5066 if (R.getAsSingle<ConceptDecl>()) { 5067 return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(), 5068 R.getFoundDecl(), 5069 R.getAsSingle<ConceptDecl>(), TemplateArgs); 5070 } 5071 5072 // We don't want lookup warnings at this point. 5073 R.suppressDiagnostics(); 5074 5075 UnresolvedLookupExpr *ULE = UnresolvedLookupExpr::Create( 5076 Context, R.getNamingClass(), SS.getWithLocInContext(Context), 5077 TemplateKWLoc, R.getLookupNameInfo(), RequiresADL, TemplateArgs, 5078 R.begin(), R.end(), KnownDependent); 5079 5080 return ULE; 5081 } 5082 5083 // We actually only call this from template instantiation. 5084 ExprResult 5085 Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, 5086 SourceLocation TemplateKWLoc, 5087 const DeclarationNameInfo &NameInfo, 5088 const TemplateArgumentListInfo *TemplateArgs) { 5089 5090 assert(TemplateArgs || TemplateKWLoc.isValid()); 5091 DeclContext *DC; 5092 if (!(DC = computeDeclContext(SS, false)) || 5093 DC->isDependentContext() || 5094 RequireCompleteDeclContext(SS, DC)) 5095 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs); 5096 5097 bool MemberOfUnknownSpecialization; 5098 LookupResult R(*this, NameInfo, LookupOrdinaryName); 5099 if (LookupTemplateName(R, (Scope *)nullptr, SS, QualType(), 5100 /*Entering*/false, MemberOfUnknownSpecialization, 5101 TemplateKWLoc)) 5102 return ExprError(); 5103 5104 if (R.isAmbiguous()) 5105 return ExprError(); 5106 5107 if (R.empty()) { 5108 Diag(NameInfo.getLoc(), diag::err_no_member) 5109 << NameInfo.getName() << DC << SS.getRange(); 5110 return ExprError(); 5111 } 5112 5113 auto DiagnoseTypeTemplateDecl = [&](TemplateDecl *Temp, 5114 bool isTypeAliasTemplateDecl) { 5115 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template) 5116 << SS.getScopeRep() << NameInfo.getName().getAsString() << SS.getRange() 5117 << isTypeAliasTemplateDecl; 5118 Diag(Temp->getLocation(), diag::note_referenced_type_template) << 0; 5119 return ExprError(); 5120 }; 5121 5122 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) 5123 return DiagnoseTypeTemplateDecl(Temp, false); 5124 5125 if (TypeAliasTemplateDecl *Temp = R.getAsSingle<TypeAliasTemplateDecl>()) 5126 return DiagnoseTypeTemplateDecl(Temp, true); 5127 5128 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs); 5129 } 5130 5131 /// Form a template name from a name that is syntactically required to name a 5132 /// template, either due to use of the 'template' keyword or because a name in 5133 /// this syntactic context is assumed to name a template (C++ [temp.names]p2-4). 5134 /// 5135 /// This action forms a template name given the name of the template and its 5136 /// optional scope specifier. This is used when the 'template' keyword is used 5137 /// or when the parsing context unambiguously treats a following '<' as 5138 /// introducing a template argument list. Note that this may produce a 5139 /// non-dependent template name if we can perform the lookup now and identify 5140 /// the named template. 5141 /// 5142 /// For example, given "x.MetaFun::template apply", the scope specifier 5143 /// \p SS will be "MetaFun::", \p TemplateKWLoc contains the location 5144 /// of the "template" keyword, and "apply" is the \p Name. 5145 TemplateNameKind Sema::ActOnTemplateName(Scope *S, 5146 CXXScopeSpec &SS, 5147 SourceLocation TemplateKWLoc, 5148 const UnqualifiedId &Name, 5149 ParsedType ObjectType, 5150 bool EnteringContext, 5151 TemplateTy &Result, 5152 bool AllowInjectedClassName) { 5153 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent()) 5154 Diag(TemplateKWLoc, 5155 getLangOpts().CPlusPlus11 ? 5156 diag::warn_cxx98_compat_template_outside_of_template : 5157 diag::ext_template_outside_of_template) 5158 << FixItHint::CreateRemoval(TemplateKWLoc); 5159 5160 if (SS.isInvalid()) 5161 return TNK_Non_template; 5162 5163 // Figure out where isTemplateName is going to look. 5164 DeclContext *LookupCtx = nullptr; 5165 if (SS.isNotEmpty()) 5166 LookupCtx = computeDeclContext(SS, EnteringContext); 5167 else if (ObjectType) 5168 LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType)); 5169 5170 // C++0x [temp.names]p5: 5171 // If a name prefixed by the keyword template is not the name of 5172 // a template, the program is ill-formed. [Note: the keyword 5173 // template may not be applied to non-template members of class 5174 // templates. -end note ] [ Note: as is the case with the 5175 // typename prefix, the template prefix is allowed in cases 5176 // where it is not strictly necessary; i.e., when the 5177 // nested-name-specifier or the expression on the left of the -> 5178 // or . is not dependent on a template-parameter, or the use 5179 // does not appear in the scope of a template. -end note] 5180 // 5181 // Note: C++03 was more strict here, because it banned the use of 5182 // the "template" keyword prior to a template-name that was not a 5183 // dependent name. C++ DR468 relaxed this requirement (the 5184 // "template" keyword is now permitted). We follow the C++0x 5185 // rules, even in C++03 mode with a warning, retroactively applying the DR. 5186 bool MemberOfUnknownSpecialization; 5187 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name, 5188 ObjectType, EnteringContext, Result, 5189 MemberOfUnknownSpecialization); 5190 if (TNK != TNK_Non_template) { 5191 // We resolved this to a (non-dependent) template name. Return it. 5192 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 5193 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD && 5194 Name.getKind() == UnqualifiedIdKind::IK_Identifier && 5195 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) { 5196 // C++14 [class.qual]p2: 5197 // In a lookup in which function names are not ignored and the 5198 // nested-name-specifier nominates a class C, if the name specified 5199 // [...] is the injected-class-name of C, [...] the name is instead 5200 // considered to name the constructor 5201 // 5202 // We don't get here if naming the constructor would be valid, so we 5203 // just reject immediately and recover by treating the 5204 // injected-class-name as naming the template. 5205 Diag(Name.getBeginLoc(), 5206 diag::ext_out_of_line_qualified_id_type_names_constructor) 5207 << Name.Identifier 5208 << 0 /*injected-class-name used as template name*/ 5209 << TemplateKWLoc.isValid(); 5210 } 5211 return TNK; 5212 } 5213 5214 if (!MemberOfUnknownSpecialization) { 5215 // Didn't find a template name, and the lookup wasn't dependent. 5216 // Do the lookup again to determine if this is a "nothing found" case or 5217 // a "not a template" case. FIXME: Refactor isTemplateName so we don't 5218 // need to do this. 5219 DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name); 5220 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(), 5221 LookupOrdinaryName); 5222 bool MOUS; 5223 // Tell LookupTemplateName that we require a template so that it diagnoses 5224 // cases where it finds a non-template. 5225 RequiredTemplateKind RTK = TemplateKWLoc.isValid() 5226 ? RequiredTemplateKind(TemplateKWLoc) 5227 : TemplateNameIsRequired; 5228 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, MOUS, 5229 RTK, nullptr, /*AllowTypoCorrection=*/false) && 5230 !R.isAmbiguous()) { 5231 if (LookupCtx) 5232 Diag(Name.getBeginLoc(), diag::err_no_member) 5233 << DNI.getName() << LookupCtx << SS.getRange(); 5234 else 5235 Diag(Name.getBeginLoc(), diag::err_undeclared_use) 5236 << DNI.getName() << SS.getRange(); 5237 } 5238 return TNK_Non_template; 5239 } 5240 5241 NestedNameSpecifier *Qualifier = SS.getScopeRep(); 5242 5243 switch (Name.getKind()) { 5244 case UnqualifiedIdKind::IK_Identifier: 5245 Result = TemplateTy::make( 5246 Context.getDependentTemplateName(Qualifier, Name.Identifier)); 5247 return TNK_Dependent_template_name; 5248 5249 case UnqualifiedIdKind::IK_OperatorFunctionId: 5250 Result = TemplateTy::make(Context.getDependentTemplateName( 5251 Qualifier, Name.OperatorFunctionId.Operator)); 5252 return TNK_Function_template; 5253 5254 case UnqualifiedIdKind::IK_LiteralOperatorId: 5255 // This is a kind of template name, but can never occur in a dependent 5256 // scope (literal operators can only be declared at namespace scope). 5257 break; 5258 5259 default: 5260 break; 5261 } 5262 5263 // This name cannot possibly name a dependent template. Diagnose this now 5264 // rather than building a dependent template name that can never be valid. 5265 Diag(Name.getBeginLoc(), 5266 diag::err_template_kw_refers_to_dependent_non_template) 5267 << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange() 5268 << TemplateKWLoc.isValid() << TemplateKWLoc; 5269 return TNK_Non_template; 5270 } 5271 5272 bool Sema::CheckTemplateTypeArgument( 5273 TemplateTypeParmDecl *Param, TemplateArgumentLoc &AL, 5274 SmallVectorImpl<TemplateArgument> &SugaredConverted, 5275 SmallVectorImpl<TemplateArgument> &CanonicalConverted) { 5276 const TemplateArgument &Arg = AL.getArgument(); 5277 QualType ArgType; 5278 TypeSourceInfo *TSI = nullptr; 5279 5280 // Check template type parameter. 5281 switch(Arg.getKind()) { 5282 case TemplateArgument::Type: 5283 // C++ [temp.arg.type]p1: 5284 // A template-argument for a template-parameter which is a 5285 // type shall be a type-id. 5286 ArgType = Arg.getAsType(); 5287 TSI = AL.getTypeSourceInfo(); 5288 break; 5289 case TemplateArgument::Template: 5290 case TemplateArgument::TemplateExpansion: { 5291 // We have a template type parameter but the template argument 5292 // is a template without any arguments. 5293 SourceRange SR = AL.getSourceRange(); 5294 TemplateName Name = Arg.getAsTemplateOrTemplatePattern(); 5295 diagnoseMissingTemplateArguments(Name, SR.getEnd()); 5296 return true; 5297 } 5298 case TemplateArgument::Expression: { 5299 // We have a template type parameter but the template argument is an 5300 // expression; see if maybe it is missing the "typename" keyword. 5301 CXXScopeSpec SS; 5302 DeclarationNameInfo NameInfo; 5303 5304 if (DependentScopeDeclRefExpr *ArgExpr = 5305 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) { 5306 SS.Adopt(ArgExpr->getQualifierLoc()); 5307 NameInfo = ArgExpr->getNameInfo(); 5308 } else if (CXXDependentScopeMemberExpr *ArgExpr = 5309 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) { 5310 if (ArgExpr->isImplicitAccess()) { 5311 SS.Adopt(ArgExpr->getQualifierLoc()); 5312 NameInfo = ArgExpr->getMemberNameInfo(); 5313 } 5314 } 5315 5316 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) { 5317 LookupResult Result(*this, NameInfo, LookupOrdinaryName); 5318 LookupParsedName(Result, CurScope, &SS); 5319 5320 if (Result.getAsSingle<TypeDecl>() || 5321 Result.getResultKind() == 5322 LookupResult::NotFoundInCurrentInstantiation) { 5323 assert(SS.getScopeRep() && "dependent scope expr must has a scope!"); 5324 // Suggest that the user add 'typename' before the NNS. 5325 SourceLocation Loc = AL.getSourceRange().getBegin(); 5326 Diag(Loc, getLangOpts().MSVCCompat 5327 ? diag::ext_ms_template_type_arg_missing_typename 5328 : diag::err_template_arg_must_be_type_suggest) 5329 << FixItHint::CreateInsertion(Loc, "typename "); 5330 NoteTemplateParameterLocation(*Param); 5331 5332 // Recover by synthesizing a type using the location information that we 5333 // already have. 5334 ArgType = Context.getDependentNameType(ElaboratedTypeKeyword::Typename, 5335 SS.getScopeRep(), II); 5336 TypeLocBuilder TLB; 5337 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType); 5338 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/)); 5339 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 5340 TL.setNameLoc(NameInfo.getLoc()); 5341 TSI = TLB.getTypeSourceInfo(Context, ArgType); 5342 5343 // Overwrite our input TemplateArgumentLoc so that we can recover 5344 // properly. 5345 AL = TemplateArgumentLoc(TemplateArgument(ArgType), 5346 TemplateArgumentLocInfo(TSI)); 5347 5348 break; 5349 } 5350 } 5351 // fallthrough 5352 [[fallthrough]]; 5353 } 5354 default: { 5355 // We have a template type parameter but the template argument 5356 // is not a type. 5357 SourceRange SR = AL.getSourceRange(); 5358 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR; 5359 NoteTemplateParameterLocation(*Param); 5360 5361 return true; 5362 } 5363 } 5364 5365 if (CheckTemplateArgument(TSI)) 5366 return true; 5367 5368 // Objective-C ARC: 5369 // If an explicitly-specified template argument type is a lifetime type 5370 // with no lifetime qualifier, the __strong lifetime qualifier is inferred. 5371 if (getLangOpts().ObjCAutoRefCount && 5372 ArgType->isObjCLifetimeType() && 5373 !ArgType.getObjCLifetime()) { 5374 Qualifiers Qs; 5375 Qs.setObjCLifetime(Qualifiers::OCL_Strong); 5376 ArgType = Context.getQualifiedType(ArgType, Qs); 5377 } 5378 5379 SugaredConverted.push_back(TemplateArgument(ArgType)); 5380 CanonicalConverted.push_back( 5381 TemplateArgument(Context.getCanonicalType(ArgType))); 5382 return false; 5383 } 5384 5385 /// Substitute template arguments into the default template argument for 5386 /// the given template type parameter. 5387 /// 5388 /// \param SemaRef the semantic analysis object for which we are performing 5389 /// the substitution. 5390 /// 5391 /// \param Template the template that we are synthesizing template arguments 5392 /// for. 5393 /// 5394 /// \param TemplateLoc the location of the template name that started the 5395 /// template-id we are checking. 5396 /// 5397 /// \param RAngleLoc the location of the right angle bracket ('>') that 5398 /// terminates the template-id. 5399 /// 5400 /// \param Param the template template parameter whose default we are 5401 /// substituting into. 5402 /// 5403 /// \param Converted the list of template arguments provided for template 5404 /// parameters that precede \p Param in the template parameter list. 5405 /// \returns the substituted template argument, or NULL if an error occurred. 5406 static TypeSourceInfo *SubstDefaultTemplateArgument( 5407 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc, 5408 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param, 5409 ArrayRef<TemplateArgument> SugaredConverted, 5410 ArrayRef<TemplateArgument> CanonicalConverted) { 5411 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo(); 5412 5413 // If the argument type is dependent, instantiate it now based 5414 // on the previously-computed template arguments. 5415 if (ArgType->getType()->isInstantiationDependentType()) { 5416 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template, 5417 SugaredConverted, 5418 SourceRange(TemplateLoc, RAngleLoc)); 5419 if (Inst.isInvalid()) 5420 return nullptr; 5421 5422 // Only substitute for the innermost template argument list. 5423 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted, 5424 /*Final=*/true); 5425 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i) 5426 TemplateArgLists.addOuterTemplateArguments(std::nullopt); 5427 5428 bool ForLambdaCallOperator = false; 5429 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext())) 5430 ForLambdaCallOperator = Rec->isLambda(); 5431 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(), 5432 !ForLambdaCallOperator); 5433 ArgType = 5434 SemaRef.SubstType(ArgType, TemplateArgLists, 5435 Param->getDefaultArgumentLoc(), Param->getDeclName()); 5436 } 5437 5438 return ArgType; 5439 } 5440 5441 /// Substitute template arguments into the default template argument for 5442 /// the given non-type template parameter. 5443 /// 5444 /// \param SemaRef the semantic analysis object for which we are performing 5445 /// the substitution. 5446 /// 5447 /// \param Template the template that we are synthesizing template arguments 5448 /// for. 5449 /// 5450 /// \param TemplateLoc the location of the template name that started the 5451 /// template-id we are checking. 5452 /// 5453 /// \param RAngleLoc the location of the right angle bracket ('>') that 5454 /// terminates the template-id. 5455 /// 5456 /// \param Param the non-type template parameter whose default we are 5457 /// substituting into. 5458 /// 5459 /// \param Converted the list of template arguments provided for template 5460 /// parameters that precede \p Param in the template parameter list. 5461 /// 5462 /// \returns the substituted template argument, or NULL if an error occurred. 5463 static ExprResult SubstDefaultTemplateArgument( 5464 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc, 5465 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param, 5466 ArrayRef<TemplateArgument> SugaredConverted, 5467 ArrayRef<TemplateArgument> CanonicalConverted) { 5468 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template, 5469 SugaredConverted, 5470 SourceRange(TemplateLoc, RAngleLoc)); 5471 if (Inst.isInvalid()) 5472 return ExprError(); 5473 5474 // Only substitute for the innermost template argument list. 5475 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted, 5476 /*Final=*/true); 5477 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i) 5478 TemplateArgLists.addOuterTemplateArguments(std::nullopt); 5479 5480 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext()); 5481 EnterExpressionEvaluationContext ConstantEvaluated( 5482 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated); 5483 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists); 5484 } 5485 5486 /// Substitute template arguments into the default template argument for 5487 /// the given template template parameter. 5488 /// 5489 /// \param SemaRef the semantic analysis object for which we are performing 5490 /// the substitution. 5491 /// 5492 /// \param Template the template that we are synthesizing template arguments 5493 /// for. 5494 /// 5495 /// \param TemplateLoc the location of the template name that started the 5496 /// template-id we are checking. 5497 /// 5498 /// \param RAngleLoc the location of the right angle bracket ('>') that 5499 /// terminates the template-id. 5500 /// 5501 /// \param Param the template template parameter whose default we are 5502 /// substituting into. 5503 /// 5504 /// \param Converted the list of template arguments provided for template 5505 /// parameters that precede \p Param in the template parameter list. 5506 /// 5507 /// \param QualifierLoc Will be set to the nested-name-specifier (with 5508 /// source-location information) that precedes the template name. 5509 /// 5510 /// \returns the substituted template argument, or NULL if an error occurred. 5511 static TemplateName SubstDefaultTemplateArgument( 5512 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc, 5513 SourceLocation RAngleLoc, TemplateTemplateParmDecl *Param, 5514 ArrayRef<TemplateArgument> SugaredConverted, 5515 ArrayRef<TemplateArgument> CanonicalConverted, 5516 NestedNameSpecifierLoc &QualifierLoc) { 5517 Sema::InstantiatingTemplate Inst( 5518 SemaRef, TemplateLoc, TemplateParameter(Param), Template, 5519 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc)); 5520 if (Inst.isInvalid()) 5521 return TemplateName(); 5522 5523 // Only substitute for the innermost template argument list. 5524 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted, 5525 /*Final=*/true); 5526 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i) 5527 TemplateArgLists.addOuterTemplateArguments(std::nullopt); 5528 5529 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext()); 5530 // Substitute into the nested-name-specifier first, 5531 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc(); 5532 if (QualifierLoc) { 5533 QualifierLoc = 5534 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists); 5535 if (!QualifierLoc) 5536 return TemplateName(); 5537 } 5538 5539 return SemaRef.SubstTemplateName( 5540 QualifierLoc, 5541 Param->getDefaultArgument().getArgument().getAsTemplate(), 5542 Param->getDefaultArgument().getTemplateNameLoc(), 5543 TemplateArgLists); 5544 } 5545 5546 /// If the given template parameter has a default template 5547 /// argument, substitute into that default template argument and 5548 /// return the corresponding template argument. 5549 TemplateArgumentLoc Sema::SubstDefaultTemplateArgumentIfAvailable( 5550 TemplateDecl *Template, SourceLocation TemplateLoc, 5551 SourceLocation RAngleLoc, Decl *Param, 5552 ArrayRef<TemplateArgument> SugaredConverted, 5553 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) { 5554 HasDefaultArg = false; 5555 5556 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) { 5557 if (!hasReachableDefaultArgument(TypeParm)) 5558 return TemplateArgumentLoc(); 5559 5560 HasDefaultArg = true; 5561 TypeSourceInfo *DI = SubstDefaultTemplateArgument( 5562 *this, Template, TemplateLoc, RAngleLoc, TypeParm, SugaredConverted, 5563 CanonicalConverted); 5564 if (DI) 5565 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI); 5566 5567 return TemplateArgumentLoc(); 5568 } 5569 5570 if (NonTypeTemplateParmDecl *NonTypeParm 5571 = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 5572 if (!hasReachableDefaultArgument(NonTypeParm)) 5573 return TemplateArgumentLoc(); 5574 5575 HasDefaultArg = true; 5576 ExprResult Arg = SubstDefaultTemplateArgument( 5577 *this, Template, TemplateLoc, RAngleLoc, NonTypeParm, SugaredConverted, 5578 CanonicalConverted); 5579 if (Arg.isInvalid()) 5580 return TemplateArgumentLoc(); 5581 5582 Expr *ArgE = Arg.getAs<Expr>(); 5583 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE); 5584 } 5585 5586 TemplateTemplateParmDecl *TempTempParm 5587 = cast<TemplateTemplateParmDecl>(Param); 5588 if (!hasReachableDefaultArgument(TempTempParm)) 5589 return TemplateArgumentLoc(); 5590 5591 HasDefaultArg = true; 5592 NestedNameSpecifierLoc QualifierLoc; 5593 TemplateName TName = SubstDefaultTemplateArgument( 5594 *this, Template, TemplateLoc, RAngleLoc, TempTempParm, SugaredConverted, 5595 CanonicalConverted, QualifierLoc); 5596 if (TName.isNull()) 5597 return TemplateArgumentLoc(); 5598 5599 return TemplateArgumentLoc( 5600 Context, TemplateArgument(TName), 5601 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(), 5602 TempTempParm->getDefaultArgument().getTemplateNameLoc()); 5603 } 5604 5605 /// Convert a template-argument that we parsed as a type into a template, if 5606 /// possible. C++ permits injected-class-names to perform dual service as 5607 /// template template arguments and as template type arguments. 5608 static TemplateArgumentLoc 5609 convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc) { 5610 // Extract and step over any surrounding nested-name-specifier. 5611 NestedNameSpecifierLoc QualLoc; 5612 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) { 5613 if (ETLoc.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None) 5614 return TemplateArgumentLoc(); 5615 5616 QualLoc = ETLoc.getQualifierLoc(); 5617 TLoc = ETLoc.getNamedTypeLoc(); 5618 } 5619 // If this type was written as an injected-class-name, it can be used as a 5620 // template template argument. 5621 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>()) 5622 return TemplateArgumentLoc(Context, InjLoc.getTypePtr()->getTemplateName(), 5623 QualLoc, InjLoc.getNameLoc()); 5624 5625 // If this type was written as an injected-class-name, it may have been 5626 // converted to a RecordType during instantiation. If the RecordType is 5627 // *not* wrapped in a TemplateSpecializationType and denotes a class 5628 // template specialization, it must have come from an injected-class-name. 5629 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>()) 5630 if (auto *CTSD = 5631 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl())) 5632 return TemplateArgumentLoc(Context, 5633 TemplateName(CTSD->getSpecializedTemplate()), 5634 QualLoc, RecLoc.getNameLoc()); 5635 5636 return TemplateArgumentLoc(); 5637 } 5638 5639 /// Check that the given template argument corresponds to the given 5640 /// template parameter. 5641 /// 5642 /// \param Param The template parameter against which the argument will be 5643 /// checked. 5644 /// 5645 /// \param Arg The template argument, which may be updated due to conversions. 5646 /// 5647 /// \param Template The template in which the template argument resides. 5648 /// 5649 /// \param TemplateLoc The location of the template name for the template 5650 /// whose argument list we're matching. 5651 /// 5652 /// \param RAngleLoc The location of the right angle bracket ('>') that closes 5653 /// the template argument list. 5654 /// 5655 /// \param ArgumentPackIndex The index into the argument pack where this 5656 /// argument will be placed. Only valid if the parameter is a parameter pack. 5657 /// 5658 /// \param Converted The checked, converted argument will be added to the 5659 /// end of this small vector. 5660 /// 5661 /// \param CTAK Describes how we arrived at this particular template argument: 5662 /// explicitly written, deduced, etc. 5663 /// 5664 /// \returns true on error, false otherwise. 5665 bool Sema::CheckTemplateArgument( 5666 NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, 5667 SourceLocation TemplateLoc, SourceLocation RAngleLoc, 5668 unsigned ArgumentPackIndex, 5669 SmallVectorImpl<TemplateArgument> &SugaredConverted, 5670 SmallVectorImpl<TemplateArgument> &CanonicalConverted, 5671 CheckTemplateArgumentKind CTAK) { 5672 // Check template type parameters. 5673 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) 5674 return CheckTemplateTypeArgument(TTP, Arg, SugaredConverted, 5675 CanonicalConverted); 5676 5677 // Check non-type template parameters. 5678 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) { 5679 // Do substitution on the type of the non-type template parameter 5680 // with the template arguments we've seen thus far. But if the 5681 // template has a dependent context then we cannot substitute yet. 5682 QualType NTTPType = NTTP->getType(); 5683 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack()) 5684 NTTPType = NTTP->getExpansionType(ArgumentPackIndex); 5685 5686 if (NTTPType->isInstantiationDependentType() && 5687 !isa<TemplateTemplateParmDecl>(Template) && 5688 !Template->getDeclContext()->isDependentContext()) { 5689 // Do substitution on the type of the non-type template parameter. 5690 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP, 5691 SugaredConverted, 5692 SourceRange(TemplateLoc, RAngleLoc)); 5693 if (Inst.isInvalid()) 5694 return true; 5695 5696 MultiLevelTemplateArgumentList MLTAL(Template, SugaredConverted, 5697 /*Final=*/true); 5698 // If the parameter is a pack expansion, expand this slice of the pack. 5699 if (auto *PET = NTTPType->getAs<PackExpansionType>()) { 5700 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, 5701 ArgumentPackIndex); 5702 NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(), 5703 NTTP->getDeclName()); 5704 } else { 5705 NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(), 5706 NTTP->getDeclName()); 5707 } 5708 5709 // If that worked, check the non-type template parameter type 5710 // for validity. 5711 if (!NTTPType.isNull()) 5712 NTTPType = CheckNonTypeTemplateParameterType(NTTPType, 5713 NTTP->getLocation()); 5714 if (NTTPType.isNull()) 5715 return true; 5716 } 5717 5718 switch (Arg.getArgument().getKind()) { 5719 case TemplateArgument::Null: 5720 llvm_unreachable("Should never see a NULL template argument here"); 5721 5722 case TemplateArgument::Expression: { 5723 Expr *E = Arg.getArgument().getAsExpr(); 5724 TemplateArgument SugaredResult, CanonicalResult; 5725 unsigned CurSFINAEErrors = NumSFINAEErrors; 5726 ExprResult Res = CheckTemplateArgument(NTTP, NTTPType, E, SugaredResult, 5727 CanonicalResult, CTAK); 5728 if (Res.isInvalid()) 5729 return true; 5730 // If the current template argument causes an error, give up now. 5731 if (CurSFINAEErrors < NumSFINAEErrors) 5732 return true; 5733 5734 // If the resulting expression is new, then use it in place of the 5735 // old expression in the template argument. 5736 if (Res.get() != E) { 5737 TemplateArgument TA(Res.get()); 5738 Arg = TemplateArgumentLoc(TA, Res.get()); 5739 } 5740 5741 SugaredConverted.push_back(SugaredResult); 5742 CanonicalConverted.push_back(CanonicalResult); 5743 break; 5744 } 5745 5746 case TemplateArgument::Declaration: 5747 case TemplateArgument::Integral: 5748 case TemplateArgument::NullPtr: 5749 // We've already checked this template argument, so just copy 5750 // it to the list of converted arguments. 5751 SugaredConverted.push_back(Arg.getArgument()); 5752 CanonicalConverted.push_back( 5753 Context.getCanonicalTemplateArgument(Arg.getArgument())); 5754 break; 5755 5756 case TemplateArgument::Template: 5757 case TemplateArgument::TemplateExpansion: 5758 // We were given a template template argument. It may not be ill-formed; 5759 // see below. 5760 if (DependentTemplateName *DTN 5761 = Arg.getArgument().getAsTemplateOrTemplatePattern() 5762 .getAsDependentTemplateName()) { 5763 // We have a template argument such as \c T::template X, which we 5764 // parsed as a template template argument. However, since we now 5765 // know that we need a non-type template argument, convert this 5766 // template name into an expression. 5767 5768 DeclarationNameInfo NameInfo(DTN->getIdentifier(), 5769 Arg.getTemplateNameLoc()); 5770 5771 CXXScopeSpec SS; 5772 SS.Adopt(Arg.getTemplateQualifierLoc()); 5773 // FIXME: the template-template arg was a DependentTemplateName, 5774 // so it was provided with a template keyword. However, its source 5775 // location is not stored in the template argument structure. 5776 SourceLocation TemplateKWLoc; 5777 ExprResult E = DependentScopeDeclRefExpr::Create( 5778 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 5779 nullptr); 5780 5781 // If we parsed the template argument as a pack expansion, create a 5782 // pack expansion expression. 5783 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){ 5784 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc()); 5785 if (E.isInvalid()) 5786 return true; 5787 } 5788 5789 TemplateArgument SugaredResult, CanonicalResult; 5790 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), SugaredResult, 5791 CanonicalResult, CTAK_Specified); 5792 if (E.isInvalid()) 5793 return true; 5794 5795 SugaredConverted.push_back(SugaredResult); 5796 CanonicalConverted.push_back(CanonicalResult); 5797 break; 5798 } 5799 5800 // We have a template argument that actually does refer to a class 5801 // template, alias template, or template template parameter, and 5802 // therefore cannot be a non-type template argument. 5803 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr) 5804 << Arg.getSourceRange(); 5805 NoteTemplateParameterLocation(*Param); 5806 5807 return true; 5808 5809 case TemplateArgument::Type: { 5810 // We have a non-type template parameter but the template 5811 // argument is a type. 5812 5813 // C++ [temp.arg]p2: 5814 // In a template-argument, an ambiguity between a type-id and 5815 // an expression is resolved to a type-id, regardless of the 5816 // form of the corresponding template-parameter. 5817 // 5818 // We warn specifically about this case, since it can be rather 5819 // confusing for users. 5820 QualType T = Arg.getArgument().getAsType(); 5821 SourceRange SR = Arg.getSourceRange(); 5822 if (T->isFunctionType()) 5823 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T; 5824 else 5825 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR; 5826 NoteTemplateParameterLocation(*Param); 5827 return true; 5828 } 5829 5830 case TemplateArgument::Pack: 5831 llvm_unreachable("Caller must expand template argument packs"); 5832 } 5833 5834 return false; 5835 } 5836 5837 5838 // Check template template parameters. 5839 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param); 5840 5841 TemplateParameterList *Params = TempParm->getTemplateParameters(); 5842 if (TempParm->isExpandedParameterPack()) 5843 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex); 5844 5845 // Substitute into the template parameter list of the template 5846 // template parameter, since previously-supplied template arguments 5847 // may appear within the template template parameter. 5848 // 5849 // FIXME: Skip this if the parameters aren't instantiation-dependent. 5850 { 5851 // Set up a template instantiation context. 5852 LocalInstantiationScope Scope(*this); 5853 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm, 5854 SugaredConverted, 5855 SourceRange(TemplateLoc, RAngleLoc)); 5856 if (Inst.isInvalid()) 5857 return true; 5858 5859 Params = 5860 SubstTemplateParams(Params, CurContext, 5861 MultiLevelTemplateArgumentList( 5862 Template, SugaredConverted, /*Final=*/true), 5863 /*EvaluateConstraints=*/false); 5864 if (!Params) 5865 return true; 5866 } 5867 5868 // C++1z [temp.local]p1: (DR1004) 5869 // When [the injected-class-name] is used [...] as a template-argument for 5870 // a template template-parameter [...] it refers to the class template 5871 // itself. 5872 if (Arg.getArgument().getKind() == TemplateArgument::Type) { 5873 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate( 5874 Context, Arg.getTypeSourceInfo()->getTypeLoc()); 5875 if (!ConvertedArg.getArgument().isNull()) 5876 Arg = ConvertedArg; 5877 } 5878 5879 switch (Arg.getArgument().getKind()) { 5880 case TemplateArgument::Null: 5881 llvm_unreachable("Should never see a NULL template argument here"); 5882 5883 case TemplateArgument::Template: 5884 case TemplateArgument::TemplateExpansion: 5885 if (CheckTemplateTemplateArgument(TempParm, Params, Arg)) 5886 return true; 5887 5888 SugaredConverted.push_back(Arg.getArgument()); 5889 CanonicalConverted.push_back( 5890 Context.getCanonicalTemplateArgument(Arg.getArgument())); 5891 break; 5892 5893 case TemplateArgument::Expression: 5894 case TemplateArgument::Type: 5895 // We have a template template parameter but the template 5896 // argument does not refer to a template. 5897 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template) 5898 << getLangOpts().CPlusPlus11; 5899 return true; 5900 5901 case TemplateArgument::Declaration: 5902 llvm_unreachable("Declaration argument with template template parameter"); 5903 case TemplateArgument::Integral: 5904 llvm_unreachable("Integral argument with template template parameter"); 5905 case TemplateArgument::NullPtr: 5906 llvm_unreachable("Null pointer argument with template template parameter"); 5907 5908 case TemplateArgument::Pack: 5909 llvm_unreachable("Caller must expand template argument packs"); 5910 } 5911 5912 return false; 5913 } 5914 5915 /// Diagnose a missing template argument. 5916 template<typename TemplateParmDecl> 5917 static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc, 5918 TemplateDecl *TD, 5919 const TemplateParmDecl *D, 5920 TemplateArgumentListInfo &Args) { 5921 // Dig out the most recent declaration of the template parameter; there may be 5922 // declarations of the template that are more recent than TD. 5923 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl()) 5924 ->getTemplateParameters() 5925 ->getParam(D->getIndex())); 5926 5927 // If there's a default argument that's not reachable, diagnose that we're 5928 // missing a module import. 5929 llvm::SmallVector<Module*, 8> Modules; 5930 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, &Modules)) { 5931 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD), 5932 D->getDefaultArgumentLoc(), Modules, 5933 Sema::MissingImportKind::DefaultArgument, 5934 /*Recover*/true); 5935 return true; 5936 } 5937 5938 // FIXME: If there's a more recent default argument that *is* visible, 5939 // diagnose that it was declared too late. 5940 5941 TemplateParameterList *Params = TD->getTemplateParameters(); 5942 5943 S.Diag(Loc, diag::err_template_arg_list_different_arity) 5944 << /*not enough args*/0 5945 << (int)S.getTemplateNameKindForDiagnostics(TemplateName(TD)) 5946 << TD; 5947 S.NoteTemplateLocation(*TD, Params->getSourceRange()); 5948 return true; 5949 } 5950 5951 /// Check that the given template argument list is well-formed 5952 /// for specializing the given template. 5953 bool Sema::CheckTemplateArgumentList( 5954 TemplateDecl *Template, SourceLocation TemplateLoc, 5955 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs, 5956 SmallVectorImpl<TemplateArgument> &SugaredConverted, 5957 SmallVectorImpl<TemplateArgument> &CanonicalConverted, 5958 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) { 5959 5960 if (ConstraintsNotSatisfied) 5961 *ConstraintsNotSatisfied = false; 5962 5963 // Make a copy of the template arguments for processing. Only make the 5964 // changes at the end when successful in matching the arguments to the 5965 // template. 5966 TemplateArgumentListInfo NewArgs = TemplateArgs; 5967 5968 TemplateParameterList *Params = GetTemplateParameterList(Template); 5969 5970 SourceLocation RAngleLoc = NewArgs.getRAngleLoc(); 5971 5972 // C++ [temp.arg]p1: 5973 // [...] The type and form of each template-argument specified in 5974 // a template-id shall match the type and form specified for the 5975 // corresponding parameter declared by the template in its 5976 // template-parameter-list. 5977 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template); 5978 SmallVector<TemplateArgument, 2> SugaredArgumentPack; 5979 SmallVector<TemplateArgument, 2> CanonicalArgumentPack; 5980 unsigned ArgIdx = 0, NumArgs = NewArgs.size(); 5981 LocalInstantiationScope InstScope(*this, true); 5982 for (TemplateParameterList::iterator Param = Params->begin(), 5983 ParamEnd = Params->end(); 5984 Param != ParamEnd; /* increment in loop */) { 5985 // If we have an expanded parameter pack, make sure we don't have too 5986 // many arguments. 5987 if (std::optional<unsigned> Expansions = getExpandedPackSize(*Param)) { 5988 if (*Expansions == SugaredArgumentPack.size()) { 5989 // We're done with this parameter pack. Pack up its arguments and add 5990 // them to the list. 5991 SugaredConverted.push_back( 5992 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack)); 5993 SugaredArgumentPack.clear(); 5994 5995 CanonicalConverted.push_back( 5996 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack)); 5997 CanonicalArgumentPack.clear(); 5998 5999 // This argument is assigned to the next parameter. 6000 ++Param; 6001 continue; 6002 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) { 6003 // Not enough arguments for this parameter pack. 6004 Diag(TemplateLoc, diag::err_template_arg_list_different_arity) 6005 << /*not enough args*/0 6006 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template)) 6007 << Template; 6008 NoteTemplateLocation(*Template, Params->getSourceRange()); 6009 return true; 6010 } 6011 } 6012 6013 if (ArgIdx < NumArgs) { 6014 // Check the template argument we were given. 6015 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template, TemplateLoc, 6016 RAngleLoc, SugaredArgumentPack.size(), 6017 SugaredConverted, CanonicalConverted, 6018 CTAK_Specified)) 6019 return true; 6020 6021 CanonicalConverted.back().setIsDefaulted( 6022 clang::isSubstitutedDefaultArgument( 6023 Context, NewArgs[ArgIdx].getArgument(), *Param, 6024 CanonicalConverted, Params->getDepth())); 6025 6026 bool PackExpansionIntoNonPack = 6027 NewArgs[ArgIdx].getArgument().isPackExpansion() && 6028 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param)); 6029 if (PackExpansionIntoNonPack && (isa<TypeAliasTemplateDecl>(Template) || 6030 isa<ConceptDecl>(Template))) { 6031 // Core issue 1430: we have a pack expansion as an argument to an 6032 // alias template, and it's not part of a parameter pack. This 6033 // can't be canonicalized, so reject it now. 6034 // As for concepts - we cannot normalize constraints where this 6035 // situation exists. 6036 Diag(NewArgs[ArgIdx].getLocation(), 6037 diag::err_template_expansion_into_fixed_list) 6038 << (isa<ConceptDecl>(Template) ? 1 : 0) 6039 << NewArgs[ArgIdx].getSourceRange(); 6040 NoteTemplateParameterLocation(**Param); 6041 return true; 6042 } 6043 6044 // We're now done with this argument. 6045 ++ArgIdx; 6046 6047 if ((*Param)->isTemplateParameterPack()) { 6048 // The template parameter was a template parameter pack, so take the 6049 // deduced argument and place it on the argument pack. Note that we 6050 // stay on the same template parameter so that we can deduce more 6051 // arguments. 6052 SugaredArgumentPack.push_back(SugaredConverted.pop_back_val()); 6053 CanonicalArgumentPack.push_back(CanonicalConverted.pop_back_val()); 6054 } else { 6055 // Move to the next template parameter. 6056 ++Param; 6057 } 6058 6059 // If we just saw a pack expansion into a non-pack, then directly convert 6060 // the remaining arguments, because we don't know what parameters they'll 6061 // match up with. 6062 if (PackExpansionIntoNonPack) { 6063 if (!SugaredArgumentPack.empty()) { 6064 // If we were part way through filling in an expanded parameter pack, 6065 // fall back to just producing individual arguments. 6066 SugaredConverted.insert(SugaredConverted.end(), 6067 SugaredArgumentPack.begin(), 6068 SugaredArgumentPack.end()); 6069 SugaredArgumentPack.clear(); 6070 6071 CanonicalConverted.insert(CanonicalConverted.end(), 6072 CanonicalArgumentPack.begin(), 6073 CanonicalArgumentPack.end()); 6074 CanonicalArgumentPack.clear(); 6075 } 6076 6077 while (ArgIdx < NumArgs) { 6078 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument(); 6079 SugaredConverted.push_back(Arg); 6080 CanonicalConverted.push_back( 6081 Context.getCanonicalTemplateArgument(Arg)); 6082 ++ArgIdx; 6083 } 6084 6085 return false; 6086 } 6087 6088 continue; 6089 } 6090 6091 // If we're checking a partial template argument list, we're done. 6092 if (PartialTemplateArgs) { 6093 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) { 6094 SugaredConverted.push_back( 6095 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack)); 6096 CanonicalConverted.push_back( 6097 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack)); 6098 } 6099 return false; 6100 } 6101 6102 // If we have a template parameter pack with no more corresponding 6103 // arguments, just break out now and we'll fill in the argument pack below. 6104 if ((*Param)->isTemplateParameterPack()) { 6105 assert(!getExpandedPackSize(*Param) && 6106 "Should have dealt with this already"); 6107 6108 // A non-expanded parameter pack before the end of the parameter list 6109 // only occurs for an ill-formed template parameter list, unless we've 6110 // got a partial argument list for a function template, so just bail out. 6111 if (Param + 1 != ParamEnd) { 6112 assert( 6113 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) && 6114 "Concept templates must have parameter packs at the end."); 6115 return true; 6116 } 6117 6118 SugaredConverted.push_back( 6119 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack)); 6120 SugaredArgumentPack.clear(); 6121 6122 CanonicalConverted.push_back( 6123 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack)); 6124 CanonicalArgumentPack.clear(); 6125 6126 ++Param; 6127 continue; 6128 } 6129 6130 // Check whether we have a default argument. 6131 TemplateArgumentLoc Arg; 6132 6133 // Retrieve the default template argument from the template 6134 // parameter. For each kind of template parameter, we substitute the 6135 // template arguments provided thus far and any "outer" template arguments 6136 // (when the template parameter was part of a nested template) into 6137 // the default argument. 6138 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) { 6139 if (!hasReachableDefaultArgument(TTP)) 6140 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP, 6141 NewArgs); 6142 6143 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument( 6144 *this, Template, TemplateLoc, RAngleLoc, TTP, SugaredConverted, 6145 CanonicalConverted); 6146 if (!ArgType) 6147 return true; 6148 6149 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()), 6150 ArgType); 6151 } else if (NonTypeTemplateParmDecl *NTTP 6152 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) { 6153 if (!hasReachableDefaultArgument(NTTP)) 6154 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP, 6155 NewArgs); 6156 6157 ExprResult E = SubstDefaultTemplateArgument( 6158 *this, Template, TemplateLoc, RAngleLoc, NTTP, SugaredConverted, 6159 CanonicalConverted); 6160 if (E.isInvalid()) 6161 return true; 6162 6163 Expr *Ex = E.getAs<Expr>(); 6164 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex); 6165 } else { 6166 TemplateTemplateParmDecl *TempParm 6167 = cast<TemplateTemplateParmDecl>(*Param); 6168 6169 if (!hasReachableDefaultArgument(TempParm)) 6170 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm, 6171 NewArgs); 6172 6173 NestedNameSpecifierLoc QualifierLoc; 6174 TemplateName Name = SubstDefaultTemplateArgument( 6175 *this, Template, TemplateLoc, RAngleLoc, TempParm, SugaredConverted, 6176 CanonicalConverted, QualifierLoc); 6177 if (Name.isNull()) 6178 return true; 6179 6180 Arg = TemplateArgumentLoc( 6181 Context, TemplateArgument(Name), QualifierLoc, 6182 TempParm->getDefaultArgument().getTemplateNameLoc()); 6183 } 6184 6185 // Introduce an instantiation record that describes where we are using 6186 // the default template argument. We're not actually instantiating a 6187 // template here, we just create this object to put a note into the 6188 // context stack. 6189 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, 6190 SugaredConverted, 6191 SourceRange(TemplateLoc, RAngleLoc)); 6192 if (Inst.isInvalid()) 6193 return true; 6194 6195 // Check the default template argument. 6196 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0, 6197 SugaredConverted, CanonicalConverted, 6198 CTAK_Specified)) 6199 return true; 6200 6201 CanonicalConverted.back().setIsDefaulted(true); 6202 6203 // Core issue 150 (assumed resolution): if this is a template template 6204 // parameter, keep track of the default template arguments from the 6205 // template definition. 6206 if (isTemplateTemplateParameter) 6207 NewArgs.addArgument(Arg); 6208 6209 // Move to the next template parameter and argument. 6210 ++Param; 6211 ++ArgIdx; 6212 } 6213 6214 // If we're performing a partial argument substitution, allow any trailing 6215 // pack expansions; they might be empty. This can happen even if 6216 // PartialTemplateArgs is false (the list of arguments is complete but 6217 // still dependent). 6218 if (ArgIdx < NumArgs && CurrentInstantiationScope && 6219 CurrentInstantiationScope->getPartiallySubstitutedPack()) { 6220 while (ArgIdx < NumArgs && 6221 NewArgs[ArgIdx].getArgument().isPackExpansion()) { 6222 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument(); 6223 SugaredConverted.push_back(Arg); 6224 CanonicalConverted.push_back(Context.getCanonicalTemplateArgument(Arg)); 6225 } 6226 } 6227 6228 // If we have any leftover arguments, then there were too many arguments. 6229 // Complain and fail. 6230 if (ArgIdx < NumArgs) { 6231 Diag(TemplateLoc, diag::err_template_arg_list_different_arity) 6232 << /*too many args*/1 6233 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template)) 6234 << Template 6235 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc()); 6236 NoteTemplateLocation(*Template, Params->getSourceRange()); 6237 return true; 6238 } 6239 6240 // No problems found with the new argument list, propagate changes back 6241 // to caller. 6242 if (UpdateArgsWithConversions) 6243 TemplateArgs = std::move(NewArgs); 6244 6245 if (!PartialTemplateArgs) { 6246 TemplateArgumentList StackTemplateArgs(TemplateArgumentList::OnStack, 6247 CanonicalConverted); 6248 // Setup the context/ThisScope for the case where we are needing to 6249 // re-instantiate constraints outside of normal instantiation. 6250 DeclContext *NewContext = Template->getDeclContext(); 6251 6252 // If this template is in a template, make sure we extract the templated 6253 // decl. 6254 if (auto *TD = dyn_cast<TemplateDecl>(NewContext)) 6255 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl()); 6256 auto *RD = dyn_cast<CXXRecordDecl>(NewContext); 6257 6258 Qualifiers ThisQuals; 6259 if (const auto *Method = 6260 dyn_cast_or_null<CXXMethodDecl>(Template->getTemplatedDecl())) 6261 ThisQuals = Method->getMethodQualifiers(); 6262 6263 ContextRAII Context(*this, NewContext); 6264 CXXThisScopeRAII(*this, RD, ThisQuals, RD != nullptr); 6265 6266 MultiLevelTemplateArgumentList MLTAL = getTemplateInstantiationArgs( 6267 Template, NewContext, /*Final=*/false, &StackTemplateArgs, 6268 /*RelativeToPrimary=*/true, 6269 /*Pattern=*/nullptr, 6270 /*ForConceptInstantiation=*/true); 6271 if (EnsureTemplateArgumentListConstraints( 6272 Template, MLTAL, 6273 SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) { 6274 if (ConstraintsNotSatisfied) 6275 *ConstraintsNotSatisfied = true; 6276 return true; 6277 } 6278 } 6279 6280 return false; 6281 } 6282 6283 namespace { 6284 class UnnamedLocalNoLinkageFinder 6285 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool> 6286 { 6287 Sema &S; 6288 SourceRange SR; 6289 6290 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited; 6291 6292 public: 6293 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { } 6294 6295 bool Visit(QualType T) { 6296 return T.isNull() ? false : inherited::Visit(T.getTypePtr()); 6297 } 6298 6299 #define TYPE(Class, Parent) \ 6300 bool Visit##Class##Type(const Class##Type *); 6301 #define ABSTRACT_TYPE(Class, Parent) \ 6302 bool Visit##Class##Type(const Class##Type *) { return false; } 6303 #define NON_CANONICAL_TYPE(Class, Parent) \ 6304 bool Visit##Class##Type(const Class##Type *) { return false; } 6305 #include "clang/AST/TypeNodes.inc" 6306 6307 bool VisitTagDecl(const TagDecl *Tag); 6308 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS); 6309 }; 6310 } // end anonymous namespace 6311 6312 bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) { 6313 return false; 6314 } 6315 6316 bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) { 6317 return Visit(T->getElementType()); 6318 } 6319 6320 bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) { 6321 return Visit(T->getPointeeType()); 6322 } 6323 6324 bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType( 6325 const BlockPointerType* T) { 6326 return Visit(T->getPointeeType()); 6327 } 6328 6329 bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType( 6330 const LValueReferenceType* T) { 6331 return Visit(T->getPointeeType()); 6332 } 6333 6334 bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType( 6335 const RValueReferenceType* T) { 6336 return Visit(T->getPointeeType()); 6337 } 6338 6339 bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType( 6340 const MemberPointerType* T) { 6341 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0)); 6342 } 6343 6344 bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType( 6345 const ConstantArrayType* T) { 6346 return Visit(T->getElementType()); 6347 } 6348 6349 bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType( 6350 const IncompleteArrayType* T) { 6351 return Visit(T->getElementType()); 6352 } 6353 6354 bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType( 6355 const VariableArrayType* T) { 6356 return Visit(T->getElementType()); 6357 } 6358 6359 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType( 6360 const DependentSizedArrayType* T) { 6361 return Visit(T->getElementType()); 6362 } 6363 6364 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType( 6365 const DependentSizedExtVectorType* T) { 6366 return Visit(T->getElementType()); 6367 } 6368 6369 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType( 6370 const DependentSizedMatrixType *T) { 6371 return Visit(T->getElementType()); 6372 } 6373 6374 bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType( 6375 const DependentAddressSpaceType *T) { 6376 return Visit(T->getPointeeType()); 6377 } 6378 6379 bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) { 6380 return Visit(T->getElementType()); 6381 } 6382 6383 bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType( 6384 const DependentVectorType *T) { 6385 return Visit(T->getElementType()); 6386 } 6387 6388 bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) { 6389 return Visit(T->getElementType()); 6390 } 6391 6392 bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType( 6393 const ConstantMatrixType *T) { 6394 return Visit(T->getElementType()); 6395 } 6396 6397 bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType( 6398 const FunctionProtoType* T) { 6399 for (const auto &A : T->param_types()) { 6400 if (Visit(A)) 6401 return true; 6402 } 6403 6404 return Visit(T->getReturnType()); 6405 } 6406 6407 bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType( 6408 const FunctionNoProtoType* T) { 6409 return Visit(T->getReturnType()); 6410 } 6411 6412 bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType( 6413 const UnresolvedUsingType*) { 6414 return false; 6415 } 6416 6417 bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) { 6418 return false; 6419 } 6420 6421 bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) { 6422 return Visit(T->getUnmodifiedType()); 6423 } 6424 6425 bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) { 6426 return false; 6427 } 6428 6429 bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType( 6430 const UnaryTransformType*) { 6431 return false; 6432 } 6433 6434 bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) { 6435 return Visit(T->getDeducedType()); 6436 } 6437 6438 bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType( 6439 const DeducedTemplateSpecializationType *T) { 6440 return Visit(T->getDeducedType()); 6441 } 6442 6443 bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) { 6444 return VisitTagDecl(T->getDecl()); 6445 } 6446 6447 bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) { 6448 return VisitTagDecl(T->getDecl()); 6449 } 6450 6451 bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType( 6452 const TemplateTypeParmType*) { 6453 return false; 6454 } 6455 6456 bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType( 6457 const SubstTemplateTypeParmPackType *) { 6458 return false; 6459 } 6460 6461 bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType( 6462 const TemplateSpecializationType*) { 6463 return false; 6464 } 6465 6466 bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType( 6467 const InjectedClassNameType* T) { 6468 return VisitTagDecl(T->getDecl()); 6469 } 6470 6471 bool UnnamedLocalNoLinkageFinder::VisitDependentNameType( 6472 const DependentNameType* T) { 6473 return VisitNestedNameSpecifier(T->getQualifier()); 6474 } 6475 6476 bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType( 6477 const DependentTemplateSpecializationType* T) { 6478 if (auto *Q = T->getQualifier()) 6479 return VisitNestedNameSpecifier(Q); 6480 return false; 6481 } 6482 6483 bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType( 6484 const PackExpansionType* T) { 6485 return Visit(T->getPattern()); 6486 } 6487 6488 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) { 6489 return false; 6490 } 6491 6492 bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType( 6493 const ObjCInterfaceType *) { 6494 return false; 6495 } 6496 6497 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType( 6498 const ObjCObjectPointerType *) { 6499 return false; 6500 } 6501 6502 bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) { 6503 return Visit(T->getValueType()); 6504 } 6505 6506 bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) { 6507 return false; 6508 } 6509 6510 bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) { 6511 return false; 6512 } 6513 6514 bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType( 6515 const DependentBitIntType *T) { 6516 return false; 6517 } 6518 6519 bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) { 6520 if (Tag->getDeclContext()->isFunctionOrMethod()) { 6521 S.Diag(SR.getBegin(), 6522 S.getLangOpts().CPlusPlus11 ? 6523 diag::warn_cxx98_compat_template_arg_local_type : 6524 diag::ext_template_arg_local_type) 6525 << S.Context.getTypeDeclType(Tag) << SR; 6526 return true; 6527 } 6528 6529 if (!Tag->hasNameForLinkage()) { 6530 S.Diag(SR.getBegin(), 6531 S.getLangOpts().CPlusPlus11 ? 6532 diag::warn_cxx98_compat_template_arg_unnamed_type : 6533 diag::ext_template_arg_unnamed_type) << SR; 6534 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here); 6535 return true; 6536 } 6537 6538 return false; 6539 } 6540 6541 bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier( 6542 NestedNameSpecifier *NNS) { 6543 assert(NNS); 6544 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix())) 6545 return true; 6546 6547 switch (NNS->getKind()) { 6548 case NestedNameSpecifier::Identifier: 6549 case NestedNameSpecifier::Namespace: 6550 case NestedNameSpecifier::NamespaceAlias: 6551 case NestedNameSpecifier::Global: 6552 case NestedNameSpecifier::Super: 6553 return false; 6554 6555 case NestedNameSpecifier::TypeSpec: 6556 case NestedNameSpecifier::TypeSpecWithTemplate: 6557 return Visit(QualType(NNS->getAsType(), 0)); 6558 } 6559 llvm_unreachable("Invalid NestedNameSpecifier::Kind!"); 6560 } 6561 6562 /// Check a template argument against its corresponding 6563 /// template type parameter. 6564 /// 6565 /// This routine implements the semantics of C++ [temp.arg.type]. It 6566 /// returns true if an error occurred, and false otherwise. 6567 bool Sema::CheckTemplateArgument(TypeSourceInfo *ArgInfo) { 6568 assert(ArgInfo && "invalid TypeSourceInfo"); 6569 QualType Arg = ArgInfo->getType(); 6570 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange(); 6571 QualType CanonArg = Context.getCanonicalType(Arg); 6572 6573 if (CanonArg->isVariablyModifiedType()) { 6574 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg; 6575 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) { 6576 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR; 6577 } 6578 6579 // C++03 [temp.arg.type]p2: 6580 // A local type, a type with no linkage, an unnamed type or a type 6581 // compounded from any of these types shall not be used as a 6582 // template-argument for a template type-parameter. 6583 // 6584 // C++11 allows these, and even in C++03 we allow them as an extension with 6585 // a warning. 6586 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) { 6587 UnnamedLocalNoLinkageFinder Finder(*this, SR); 6588 (void)Finder.Visit(CanonArg); 6589 } 6590 6591 return false; 6592 } 6593 6594 enum NullPointerValueKind { 6595 NPV_NotNullPointer, 6596 NPV_NullPointer, 6597 NPV_Error 6598 }; 6599 6600 /// Determine whether the given template argument is a null pointer 6601 /// value of the appropriate type. 6602 static NullPointerValueKind 6603 isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param, 6604 QualType ParamType, Expr *Arg, 6605 Decl *Entity = nullptr) { 6606 if (Arg->isValueDependent() || Arg->isTypeDependent()) 6607 return NPV_NotNullPointer; 6608 6609 // dllimport'd entities aren't constant but are available inside of template 6610 // arguments. 6611 if (Entity && Entity->hasAttr<DLLImportAttr>()) 6612 return NPV_NotNullPointer; 6613 6614 if (!S.isCompleteType(Arg->getExprLoc(), ParamType)) 6615 llvm_unreachable( 6616 "Incomplete parameter type in isNullPointerValueTemplateArgument!"); 6617 6618 if (!S.getLangOpts().CPlusPlus11) 6619 return NPV_NotNullPointer; 6620 6621 // Determine whether we have a constant expression. 6622 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg); 6623 if (ArgRV.isInvalid()) 6624 return NPV_Error; 6625 Arg = ArgRV.get(); 6626 6627 Expr::EvalResult EvalResult; 6628 SmallVector<PartialDiagnosticAt, 8> Notes; 6629 EvalResult.Diag = &Notes; 6630 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) || 6631 EvalResult.HasSideEffects) { 6632 SourceLocation DiagLoc = Arg->getExprLoc(); 6633 6634 // If our only note is the usual "invalid subexpression" note, just point 6635 // the caret at its location rather than producing an essentially 6636 // redundant note. 6637 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 6638 diag::note_invalid_subexpr_in_const_expr) { 6639 DiagLoc = Notes[0].first; 6640 Notes.clear(); 6641 } 6642 6643 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant) 6644 << Arg->getType() << Arg->getSourceRange(); 6645 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 6646 S.Diag(Notes[I].first, Notes[I].second); 6647 6648 S.NoteTemplateParameterLocation(*Param); 6649 return NPV_Error; 6650 } 6651 6652 // C++11 [temp.arg.nontype]p1: 6653 // - an address constant expression of type std::nullptr_t 6654 if (Arg->getType()->isNullPtrType()) 6655 return NPV_NullPointer; 6656 6657 // - a constant expression that evaluates to a null pointer value (4.10); or 6658 // - a constant expression that evaluates to a null member pointer value 6659 // (4.11); or 6660 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) || 6661 (EvalResult.Val.isMemberPointer() && 6662 !EvalResult.Val.getMemberPointerDecl())) { 6663 // If our expression has an appropriate type, we've succeeded. 6664 bool ObjCLifetimeConversion; 6665 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) || 6666 S.IsQualificationConversion(Arg->getType(), ParamType, false, 6667 ObjCLifetimeConversion)) 6668 return NPV_NullPointer; 6669 6670 // The types didn't match, but we know we got a null pointer; complain, 6671 // then recover as if the types were correct. 6672 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant) 6673 << Arg->getType() << ParamType << Arg->getSourceRange(); 6674 S.NoteTemplateParameterLocation(*Param); 6675 return NPV_NullPointer; 6676 } 6677 6678 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) { 6679 // We found a pointer that isn't null, but doesn't refer to an object. 6680 // We could just return NPV_NotNullPointer, but we can print a better 6681 // message with the information we have here. 6682 S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid) 6683 << EvalResult.Val.getAsString(S.Context, ParamType); 6684 S.NoteTemplateParameterLocation(*Param); 6685 return NPV_Error; 6686 } 6687 6688 // If we don't have a null pointer value, but we do have a NULL pointer 6689 // constant, suggest a cast to the appropriate type. 6690 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) { 6691 std::string Code = "static_cast<" + ParamType.getAsString() + ">("; 6692 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant) 6693 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code) 6694 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getEndLoc()), 6695 ")"); 6696 S.NoteTemplateParameterLocation(*Param); 6697 return NPV_NullPointer; 6698 } 6699 6700 // FIXME: If we ever want to support general, address-constant expressions 6701 // as non-type template arguments, we should return the ExprResult here to 6702 // be interpreted by the caller. 6703 return NPV_NotNullPointer; 6704 } 6705 6706 /// Checks whether the given template argument is compatible with its 6707 /// template parameter. 6708 static bool CheckTemplateArgumentIsCompatibleWithParameter( 6709 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn, 6710 Expr *Arg, QualType ArgType) { 6711 bool ObjCLifetimeConversion; 6712 if (ParamType->isPointerType() && 6713 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() && 6714 S.IsQualificationConversion(ArgType, ParamType, false, 6715 ObjCLifetimeConversion)) { 6716 // For pointer-to-object types, qualification conversions are 6717 // permitted. 6718 } else { 6719 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) { 6720 if (!ParamRef->getPointeeType()->isFunctionType()) { 6721 // C++ [temp.arg.nontype]p5b3: 6722 // For a non-type template-parameter of type reference to 6723 // object, no conversions apply. The type referred to by the 6724 // reference may be more cv-qualified than the (otherwise 6725 // identical) type of the template- argument. The 6726 // template-parameter is bound directly to the 6727 // template-argument, which shall be an lvalue. 6728 6729 // FIXME: Other qualifiers? 6730 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers(); 6731 unsigned ArgQuals = ArgType.getCVRQualifiers(); 6732 6733 if ((ParamQuals | ArgQuals) != ParamQuals) { 6734 S.Diag(Arg->getBeginLoc(), 6735 diag::err_template_arg_ref_bind_ignores_quals) 6736 << ParamType << Arg->getType() << Arg->getSourceRange(); 6737 S.NoteTemplateParameterLocation(*Param); 6738 return true; 6739 } 6740 } 6741 } 6742 6743 // At this point, the template argument refers to an object or 6744 // function with external linkage. We now need to check whether the 6745 // argument and parameter types are compatible. 6746 if (!S.Context.hasSameUnqualifiedType(ArgType, 6747 ParamType.getNonReferenceType())) { 6748 // We can't perform this conversion or binding. 6749 if (ParamType->isReferenceType()) 6750 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind) 6751 << ParamType << ArgIn->getType() << Arg->getSourceRange(); 6752 else 6753 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible) 6754 << ArgIn->getType() << ParamType << Arg->getSourceRange(); 6755 S.NoteTemplateParameterLocation(*Param); 6756 return true; 6757 } 6758 } 6759 6760 return false; 6761 } 6762 6763 /// Checks whether the given template argument is the address 6764 /// of an object or function according to C++ [temp.arg.nontype]p1. 6765 static bool CheckTemplateArgumentAddressOfObjectOrFunction( 6766 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn, 6767 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) { 6768 bool Invalid = false; 6769 Expr *Arg = ArgIn; 6770 QualType ArgType = Arg->getType(); 6771 6772 bool AddressTaken = false; 6773 SourceLocation AddrOpLoc; 6774 if (S.getLangOpts().MicrosoftExt) { 6775 // Microsoft Visual C++ strips all casts, allows an arbitrary number of 6776 // dereference and address-of operators. 6777 Arg = Arg->IgnoreParenCasts(); 6778 6779 bool ExtWarnMSTemplateArg = false; 6780 UnaryOperatorKind FirstOpKind; 6781 SourceLocation FirstOpLoc; 6782 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) { 6783 UnaryOperatorKind UnOpKind = UnOp->getOpcode(); 6784 if (UnOpKind == UO_Deref) 6785 ExtWarnMSTemplateArg = true; 6786 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) { 6787 Arg = UnOp->getSubExpr()->IgnoreParenCasts(); 6788 if (!AddrOpLoc.isValid()) { 6789 FirstOpKind = UnOpKind; 6790 FirstOpLoc = UnOp->getOperatorLoc(); 6791 } 6792 } else 6793 break; 6794 } 6795 if (FirstOpLoc.isValid()) { 6796 if (ExtWarnMSTemplateArg) 6797 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument) 6798 << ArgIn->getSourceRange(); 6799 6800 if (FirstOpKind == UO_AddrOf) 6801 AddressTaken = true; 6802 else if (Arg->getType()->isPointerType()) { 6803 // We cannot let pointers get dereferenced here, that is obviously not a 6804 // constant expression. 6805 assert(FirstOpKind == UO_Deref); 6806 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref) 6807 << Arg->getSourceRange(); 6808 } 6809 } 6810 } else { 6811 // See through any implicit casts we added to fix the type. 6812 Arg = Arg->IgnoreImpCasts(); 6813 6814 // C++ [temp.arg.nontype]p1: 6815 // 6816 // A template-argument for a non-type, non-template 6817 // template-parameter shall be one of: [...] 6818 // 6819 // -- the address of an object or function with external 6820 // linkage, including function templates and function 6821 // template-ids but excluding non-static class members, 6822 // expressed as & id-expression where the & is optional if 6823 // the name refers to a function or array, or if the 6824 // corresponding template-parameter is a reference; or 6825 6826 // In C++98/03 mode, give an extension warning on any extra parentheses. 6827 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773 6828 bool ExtraParens = false; 6829 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) { 6830 if (!Invalid && !ExtraParens) { 6831 S.Diag(Arg->getBeginLoc(), 6832 S.getLangOpts().CPlusPlus11 6833 ? diag::warn_cxx98_compat_template_arg_extra_parens 6834 : diag::ext_template_arg_extra_parens) 6835 << Arg->getSourceRange(); 6836 ExtraParens = true; 6837 } 6838 6839 Arg = Parens->getSubExpr(); 6840 } 6841 6842 while (SubstNonTypeTemplateParmExpr *subst = 6843 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg)) 6844 Arg = subst->getReplacement()->IgnoreImpCasts(); 6845 6846 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) { 6847 if (UnOp->getOpcode() == UO_AddrOf) { 6848 Arg = UnOp->getSubExpr(); 6849 AddressTaken = true; 6850 AddrOpLoc = UnOp->getOperatorLoc(); 6851 } 6852 } 6853 6854 while (SubstNonTypeTemplateParmExpr *subst = 6855 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg)) 6856 Arg = subst->getReplacement()->IgnoreImpCasts(); 6857 } 6858 6859 ValueDecl *Entity = nullptr; 6860 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg)) 6861 Entity = DRE->getDecl(); 6862 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Arg)) 6863 Entity = CUE->getGuidDecl(); 6864 6865 // If our parameter has pointer type, check for a null template value. 6866 if (ParamType->isPointerType() || ParamType->isNullPtrType()) { 6867 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn, 6868 Entity)) { 6869 case NPV_NullPointer: 6870 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null); 6871 SugaredConverted = TemplateArgument(ParamType, 6872 /*isNullPtr=*/true); 6873 CanonicalConverted = 6874 TemplateArgument(S.Context.getCanonicalType(ParamType), 6875 /*isNullPtr=*/true); 6876 return false; 6877 6878 case NPV_Error: 6879 return true; 6880 6881 case NPV_NotNullPointer: 6882 break; 6883 } 6884 } 6885 6886 // Stop checking the precise nature of the argument if it is value dependent, 6887 // it should be checked when instantiated. 6888 if (Arg->isValueDependent()) { 6889 SugaredConverted = TemplateArgument(ArgIn); 6890 CanonicalConverted = 6891 S.Context.getCanonicalTemplateArgument(SugaredConverted); 6892 return false; 6893 } 6894 6895 if (!Entity) { 6896 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref) 6897 << Arg->getSourceRange(); 6898 S.NoteTemplateParameterLocation(*Param); 6899 return true; 6900 } 6901 6902 // Cannot refer to non-static data members 6903 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) { 6904 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field) 6905 << Entity << Arg->getSourceRange(); 6906 S.NoteTemplateParameterLocation(*Param); 6907 return true; 6908 } 6909 6910 // Cannot refer to non-static member functions 6911 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) { 6912 if (!Method->isStatic()) { 6913 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method) 6914 << Method << Arg->getSourceRange(); 6915 S.NoteTemplateParameterLocation(*Param); 6916 return true; 6917 } 6918 } 6919 6920 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity); 6921 VarDecl *Var = dyn_cast<VarDecl>(Entity); 6922 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Entity); 6923 6924 // A non-type template argument must refer to an object or function. 6925 if (!Func && !Var && !Guid) { 6926 // We found something, but we don't know specifically what it is. 6927 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func) 6928 << Arg->getSourceRange(); 6929 S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here); 6930 return true; 6931 } 6932 6933 // Address / reference template args must have external linkage in C++98. 6934 if (Entity->getFormalLinkage() == Linkage::Internal) { 6935 S.Diag(Arg->getBeginLoc(), 6936 S.getLangOpts().CPlusPlus11 6937 ? diag::warn_cxx98_compat_template_arg_object_internal 6938 : diag::ext_template_arg_object_internal) 6939 << !Func << Entity << Arg->getSourceRange(); 6940 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object) 6941 << !Func; 6942 } else if (!Entity->hasLinkage()) { 6943 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage) 6944 << !Func << Entity << Arg->getSourceRange(); 6945 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object) 6946 << !Func; 6947 return true; 6948 } 6949 6950 if (Var) { 6951 // A value of reference type is not an object. 6952 if (Var->getType()->isReferenceType()) { 6953 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var) 6954 << Var->getType() << Arg->getSourceRange(); 6955 S.NoteTemplateParameterLocation(*Param); 6956 return true; 6957 } 6958 6959 // A template argument must have static storage duration. 6960 if (Var->getTLSKind()) { 6961 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local) 6962 << Arg->getSourceRange(); 6963 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here); 6964 return true; 6965 } 6966 } 6967 6968 if (AddressTaken && ParamType->isReferenceType()) { 6969 // If we originally had an address-of operator, but the 6970 // parameter has reference type, complain and (if things look 6971 // like they will work) drop the address-of operator. 6972 if (!S.Context.hasSameUnqualifiedType(Entity->getType(), 6973 ParamType.getNonReferenceType())) { 6974 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer) 6975 << ParamType; 6976 S.NoteTemplateParameterLocation(*Param); 6977 return true; 6978 } 6979 6980 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer) 6981 << ParamType 6982 << FixItHint::CreateRemoval(AddrOpLoc); 6983 S.NoteTemplateParameterLocation(*Param); 6984 6985 ArgType = Entity->getType(); 6986 } 6987 6988 // If the template parameter has pointer type, either we must have taken the 6989 // address or the argument must decay to a pointer. 6990 if (!AddressTaken && ParamType->isPointerType()) { 6991 if (Func) { 6992 // Function-to-pointer decay. 6993 ArgType = S.Context.getPointerType(Func->getType()); 6994 } else if (Entity->getType()->isArrayType()) { 6995 // Array-to-pointer decay. 6996 ArgType = S.Context.getArrayDecayedType(Entity->getType()); 6997 } else { 6998 // If the template parameter has pointer type but the address of 6999 // this object was not taken, complain and (possibly) recover by 7000 // taking the address of the entity. 7001 ArgType = S.Context.getPointerType(Entity->getType()); 7002 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) { 7003 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of) 7004 << ParamType; 7005 S.NoteTemplateParameterLocation(*Param); 7006 return true; 7007 } 7008 7009 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of) 7010 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&"); 7011 7012 S.NoteTemplateParameterLocation(*Param); 7013 } 7014 } 7015 7016 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn, 7017 Arg, ArgType)) 7018 return true; 7019 7020 // Create the template argument. 7021 SugaredConverted = TemplateArgument(Entity, ParamType); 7022 CanonicalConverted = 7023 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), 7024 S.Context.getCanonicalType(ParamType)); 7025 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false); 7026 return false; 7027 } 7028 7029 /// Checks whether the given template argument is a pointer to 7030 /// member constant according to C++ [temp.arg.nontype]p1. 7031 static bool 7032 CheckTemplateArgumentPointerToMember(Sema &S, NonTypeTemplateParmDecl *Param, 7033 QualType ParamType, Expr *&ResultArg, 7034 TemplateArgument &SugaredConverted, 7035 TemplateArgument &CanonicalConverted) { 7036 bool Invalid = false; 7037 7038 Expr *Arg = ResultArg; 7039 bool ObjCLifetimeConversion; 7040 7041 // C++ [temp.arg.nontype]p1: 7042 // 7043 // A template-argument for a non-type, non-template 7044 // template-parameter shall be one of: [...] 7045 // 7046 // -- a pointer to member expressed as described in 5.3.1. 7047 DeclRefExpr *DRE = nullptr; 7048 7049 // In C++98/03 mode, give an extension warning on any extra parentheses. 7050 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773 7051 bool ExtraParens = false; 7052 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) { 7053 if (!Invalid && !ExtraParens) { 7054 S.Diag(Arg->getBeginLoc(), 7055 S.getLangOpts().CPlusPlus11 7056 ? diag::warn_cxx98_compat_template_arg_extra_parens 7057 : diag::ext_template_arg_extra_parens) 7058 << Arg->getSourceRange(); 7059 ExtraParens = true; 7060 } 7061 7062 Arg = Parens->getSubExpr(); 7063 } 7064 7065 while (SubstNonTypeTemplateParmExpr *subst = 7066 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg)) 7067 Arg = subst->getReplacement()->IgnoreImpCasts(); 7068 7069 // A pointer-to-member constant written &Class::member. 7070 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) { 7071 if (UnOp->getOpcode() == UO_AddrOf) { 7072 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr()); 7073 if (DRE && !DRE->getQualifier()) 7074 DRE = nullptr; 7075 } 7076 } 7077 // A constant of pointer-to-member type. 7078 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) { 7079 ValueDecl *VD = DRE->getDecl(); 7080 if (VD->getType()->isMemberPointerType()) { 7081 if (isa<NonTypeTemplateParmDecl>(VD)) { 7082 if (Arg->isTypeDependent() || Arg->isValueDependent()) { 7083 SugaredConverted = TemplateArgument(Arg); 7084 CanonicalConverted = 7085 S.Context.getCanonicalTemplateArgument(SugaredConverted); 7086 } else { 7087 SugaredConverted = TemplateArgument(VD, ParamType); 7088 CanonicalConverted = 7089 TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()), 7090 S.Context.getCanonicalType(ParamType)); 7091 } 7092 return Invalid; 7093 } 7094 } 7095 7096 DRE = nullptr; 7097 } 7098 7099 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr; 7100 7101 // Check for a null pointer value. 7102 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg, 7103 Entity)) { 7104 case NPV_Error: 7105 return true; 7106 case NPV_NullPointer: 7107 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null); 7108 SugaredConverted = TemplateArgument(ParamType, 7109 /*isNullPtr*/ true); 7110 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(ParamType), 7111 /*isNullPtr*/ true); 7112 return false; 7113 case NPV_NotNullPointer: 7114 break; 7115 } 7116 7117 if (S.IsQualificationConversion(ResultArg->getType(), 7118 ParamType.getNonReferenceType(), false, 7119 ObjCLifetimeConversion)) { 7120 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp, 7121 ResultArg->getValueKind()) 7122 .get(); 7123 } else if (!S.Context.hasSameUnqualifiedType( 7124 ResultArg->getType(), ParamType.getNonReferenceType())) { 7125 // We can't perform this conversion. 7126 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible) 7127 << ResultArg->getType() << ParamType << ResultArg->getSourceRange(); 7128 S.NoteTemplateParameterLocation(*Param); 7129 return true; 7130 } 7131 7132 if (!DRE) 7133 return S.Diag(Arg->getBeginLoc(), 7134 diag::err_template_arg_not_pointer_to_member_form) 7135 << Arg->getSourceRange(); 7136 7137 if (isa<FieldDecl>(DRE->getDecl()) || 7138 isa<IndirectFieldDecl>(DRE->getDecl()) || 7139 isa<CXXMethodDecl>(DRE->getDecl())) { 7140 assert((isa<FieldDecl>(DRE->getDecl()) || 7141 isa<IndirectFieldDecl>(DRE->getDecl()) || 7142 cast<CXXMethodDecl>(DRE->getDecl()) 7143 ->isImplicitObjectMemberFunction()) && 7144 "Only non-static member pointers can make it here"); 7145 7146 // Okay: this is the address of a non-static member, and therefore 7147 // a member pointer constant. 7148 if (Arg->isTypeDependent() || Arg->isValueDependent()) { 7149 SugaredConverted = TemplateArgument(Arg); 7150 CanonicalConverted = 7151 S.Context.getCanonicalTemplateArgument(SugaredConverted); 7152 } else { 7153 ValueDecl *D = DRE->getDecl(); 7154 SugaredConverted = TemplateArgument(D, ParamType); 7155 CanonicalConverted = 7156 TemplateArgument(cast<ValueDecl>(D->getCanonicalDecl()), 7157 S.Context.getCanonicalType(ParamType)); 7158 } 7159 return Invalid; 7160 } 7161 7162 // We found something else, but we don't know specifically what it is. 7163 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form) 7164 << Arg->getSourceRange(); 7165 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here); 7166 return true; 7167 } 7168 7169 /// Check a template argument against its corresponding 7170 /// non-type template parameter. 7171 /// 7172 /// This routine implements the semantics of C++ [temp.arg.nontype]. 7173 /// If an error occurred, it returns ExprError(); otherwise, it 7174 /// returns the converted template argument. \p ParamType is the 7175 /// type of the non-type template parameter after it has been instantiated. 7176 ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param, 7177 QualType ParamType, Expr *Arg, 7178 TemplateArgument &SugaredConverted, 7179 TemplateArgument &CanonicalConverted, 7180 CheckTemplateArgumentKind CTAK) { 7181 SourceLocation StartLoc = Arg->getBeginLoc(); 7182 7183 // If the parameter type somehow involves auto, deduce the type now. 7184 DeducedType *DeducedT = ParamType->getContainedDeducedType(); 7185 if (getLangOpts().CPlusPlus17 && DeducedT && !DeducedT->isDeduced()) { 7186 // During template argument deduction, we allow 'decltype(auto)' to 7187 // match an arbitrary dependent argument. 7188 // FIXME: The language rules don't say what happens in this case. 7189 // FIXME: We get an opaque dependent type out of decltype(auto) if the 7190 // expression is merely instantiation-dependent; is this enough? 7191 if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) { 7192 auto *AT = dyn_cast<AutoType>(DeducedT); 7193 if (AT && AT->isDecltypeAuto()) { 7194 SugaredConverted = TemplateArgument(Arg); 7195 CanonicalConverted = TemplateArgument( 7196 Context.getCanonicalTemplateArgument(SugaredConverted)); 7197 return Arg; 7198 } 7199 } 7200 7201 // When checking a deduced template argument, deduce from its type even if 7202 // the type is dependent, in order to check the types of non-type template 7203 // arguments line up properly in partial ordering. 7204 Expr *DeductionArg = Arg; 7205 if (auto *PE = dyn_cast<PackExpansionExpr>(DeductionArg)) 7206 DeductionArg = PE->getPattern(); 7207 TypeSourceInfo *TSI = 7208 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()); 7209 if (isa<DeducedTemplateSpecializationType>(DeducedT)) { 7210 InitializedEntity Entity = 7211 InitializedEntity::InitializeTemplateParameter(ParamType, Param); 7212 InitializationKind Kind = InitializationKind::CreateForInit( 7213 DeductionArg->getBeginLoc(), /*DirectInit*/false, DeductionArg); 7214 Expr *Inits[1] = {DeductionArg}; 7215 ParamType = 7216 DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, Inits); 7217 if (ParamType.isNull()) 7218 return ExprError(); 7219 } else { 7220 TemplateDeductionInfo Info(DeductionArg->getExprLoc(), 7221 Param->getDepth() + 1); 7222 ParamType = QualType(); 7223 TemplateDeductionResult Result = 7224 DeduceAutoType(TSI->getTypeLoc(), DeductionArg, ParamType, Info, 7225 /*DependentDeduction=*/true, 7226 // We do not check constraints right now because the 7227 // immediately-declared constraint of the auto type is 7228 // also an associated constraint, and will be checked 7229 // along with the other associated constraints after 7230 // checking the template argument list. 7231 /*IgnoreConstraints=*/true); 7232 if (Result == TDK_AlreadyDiagnosed) { 7233 if (ParamType.isNull()) 7234 return ExprError(); 7235 } else if (Result != TDK_Success) { 7236 Diag(Arg->getExprLoc(), 7237 diag::err_non_type_template_parm_type_deduction_failure) 7238 << Param->getDeclName() << Param->getType() << Arg->getType() 7239 << Arg->getSourceRange(); 7240 NoteTemplateParameterLocation(*Param); 7241 return ExprError(); 7242 } 7243 } 7244 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's 7245 // an error. The error message normally references the parameter 7246 // declaration, but here we'll pass the argument location because that's 7247 // where the parameter type is deduced. 7248 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc()); 7249 if (ParamType.isNull()) { 7250 NoteTemplateParameterLocation(*Param); 7251 return ExprError(); 7252 } 7253 } 7254 7255 // We should have already dropped all cv-qualifiers by now. 7256 assert(!ParamType.hasQualifiers() && 7257 "non-type template parameter type cannot be qualified"); 7258 7259 // FIXME: When Param is a reference, should we check that Arg is an lvalue? 7260 if (CTAK == CTAK_Deduced && 7261 (ParamType->isReferenceType() 7262 ? !Context.hasSameType(ParamType.getNonReferenceType(), 7263 Arg->getType()) 7264 : !Context.hasSameUnqualifiedType(ParamType, Arg->getType()))) { 7265 // FIXME: If either type is dependent, we skip the check. This isn't 7266 // correct, since during deduction we're supposed to have replaced each 7267 // template parameter with some unique (non-dependent) placeholder. 7268 // FIXME: If the argument type contains 'auto', we carry on and fail the 7269 // type check in order to force specific types to be more specialized than 7270 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to 7271 // work. Similarly for CTAD, when comparing 'A<x>' against 'A'. 7272 if ((ParamType->isDependentType() || Arg->isTypeDependent()) && 7273 !Arg->getType()->getContainedDeducedType()) { 7274 SugaredConverted = TemplateArgument(Arg); 7275 CanonicalConverted = TemplateArgument( 7276 Context.getCanonicalTemplateArgument(SugaredConverted)); 7277 return Arg; 7278 } 7279 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770, 7280 // we should actually be checking the type of the template argument in P, 7281 // not the type of the template argument deduced from A, against the 7282 // template parameter type. 7283 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch) 7284 << Arg->getType() 7285 << ParamType.getUnqualifiedType(); 7286 NoteTemplateParameterLocation(*Param); 7287 return ExprError(); 7288 } 7289 7290 // If either the parameter has a dependent type or the argument is 7291 // type-dependent, there's nothing we can check now. 7292 if (ParamType->isDependentType() || Arg->isTypeDependent()) { 7293 // Force the argument to the type of the parameter to maintain invariants. 7294 auto *PE = dyn_cast<PackExpansionExpr>(Arg); 7295 if (PE) 7296 Arg = PE->getPattern(); 7297 ExprResult E = ImpCastExprToType( 7298 Arg, ParamType.getNonLValueExprType(Context), CK_Dependent, 7299 ParamType->isLValueReferenceType() ? VK_LValue 7300 : ParamType->isRValueReferenceType() ? VK_XValue 7301 : VK_PRValue); 7302 if (E.isInvalid()) 7303 return ExprError(); 7304 if (PE) { 7305 // Recreate a pack expansion if we unwrapped one. 7306 E = new (Context) 7307 PackExpansionExpr(E.get()->getType(), E.get(), PE->getEllipsisLoc(), 7308 PE->getNumExpansions()); 7309 } 7310 SugaredConverted = TemplateArgument(E.get()); 7311 CanonicalConverted = TemplateArgument( 7312 Context.getCanonicalTemplateArgument(SugaredConverted)); 7313 return E; 7314 } 7315 7316 QualType CanonParamType = Context.getCanonicalType(ParamType); 7317 // Avoid making a copy when initializing a template parameter of class type 7318 // from a template parameter object of the same type. This is going beyond 7319 // the standard, but is required for soundness: in 7320 // template<A a> struct X { X *p; X<a> *q; }; 7321 // ... we need p and q to have the same type. 7322 // 7323 // Similarly, don't inject a call to a copy constructor when initializing 7324 // from a template parameter of the same type. 7325 Expr *InnerArg = Arg->IgnoreParenImpCasts(); 7326 if (ParamType->isRecordType() && isa<DeclRefExpr>(InnerArg) && 7327 Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) { 7328 NamedDecl *ND = cast<DeclRefExpr>(InnerArg)->getDecl(); 7329 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) { 7330 7331 SugaredConverted = TemplateArgument(TPO, ParamType); 7332 CanonicalConverted = 7333 TemplateArgument(TPO->getCanonicalDecl(), CanonParamType); 7334 return Arg; 7335 } 7336 if (isa<NonTypeTemplateParmDecl>(ND)) { 7337 SugaredConverted = TemplateArgument(Arg); 7338 CanonicalConverted = 7339 Context.getCanonicalTemplateArgument(SugaredConverted); 7340 return Arg; 7341 } 7342 } 7343 7344 // The initialization of the parameter from the argument is 7345 // a constant-evaluated context. 7346 EnterExpressionEvaluationContext ConstantEvaluated( 7347 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated); 7348 7349 bool IsConvertedConstantExpression = true; 7350 if (isa<InitListExpr>(Arg) || ParamType->isRecordType()) { 7351 InitializationKind Kind = InitializationKind::CreateForInit( 7352 Arg->getBeginLoc(), /*DirectInit=*/false, Arg); 7353 Expr *Inits[1] = {Arg}; 7354 InitializedEntity Entity = 7355 InitializedEntity::InitializeTemplateParameter(ParamType, Param); 7356 InitializationSequence InitSeq(*this, Entity, Kind, Inits); 7357 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Inits); 7358 if (Result.isInvalid() || !Result.get()) 7359 return ExprError(); 7360 Result = ActOnConstantExpression(Result.get()); 7361 if (Result.isInvalid() || !Result.get()) 7362 return ExprError(); 7363 Arg = ActOnFinishFullExpr(Result.get(), Arg->getBeginLoc(), 7364 /*DiscardedValue=*/false, 7365 /*IsConstexpr=*/true, /*IsTemplateArgument=*/true) 7366 .get(); 7367 IsConvertedConstantExpression = false; 7368 } 7369 7370 if (getLangOpts().CPlusPlus17) { 7371 // C++17 [temp.arg.nontype]p1: 7372 // A template-argument for a non-type template parameter shall be 7373 // a converted constant expression of the type of the template-parameter. 7374 APValue Value; 7375 ExprResult ArgResult; 7376 if (IsConvertedConstantExpression) { 7377 ArgResult = BuildConvertedConstantExpression(Arg, ParamType, 7378 CCEK_TemplateArg, Param); 7379 if (ArgResult.isInvalid()) 7380 return ExprError(); 7381 } else { 7382 ArgResult = Arg; 7383 } 7384 7385 // For a value-dependent argument, CheckConvertedConstantExpression is 7386 // permitted (and expected) to be unable to determine a value. 7387 if (ArgResult.get()->isValueDependent()) { 7388 SugaredConverted = TemplateArgument(ArgResult.get()); 7389 CanonicalConverted = 7390 Context.getCanonicalTemplateArgument(SugaredConverted); 7391 return ArgResult; 7392 } 7393 7394 APValue PreNarrowingValue; 7395 ArgResult = EvaluateConvertedConstantExpression( 7396 ArgResult.get(), ParamType, Value, CCEK_TemplateArg, /*RequireInt=*/ 7397 false, PreNarrowingValue); 7398 if (ArgResult.isInvalid()) 7399 return ExprError(); 7400 7401 // Convert the APValue to a TemplateArgument. 7402 switch (Value.getKind()) { 7403 case APValue::None: 7404 assert(ParamType->isNullPtrType()); 7405 SugaredConverted = TemplateArgument(ParamType, /*isNullPtr=*/true); 7406 CanonicalConverted = TemplateArgument(CanonParamType, /*isNullPtr=*/true); 7407 break; 7408 case APValue::Indeterminate: 7409 llvm_unreachable("result of constant evaluation should be initialized"); 7410 break; 7411 case APValue::Int: 7412 assert(ParamType->isIntegralOrEnumerationType()); 7413 SugaredConverted = TemplateArgument(Context, Value.getInt(), ParamType); 7414 CanonicalConverted = 7415 TemplateArgument(Context, Value.getInt(), CanonParamType); 7416 break; 7417 case APValue::MemberPointer: { 7418 assert(ParamType->isMemberPointerType()); 7419 7420 // FIXME: We need TemplateArgument representation and mangling for these. 7421 if (!Value.getMemberPointerPath().empty()) { 7422 Diag(Arg->getBeginLoc(), 7423 diag::err_template_arg_member_ptr_base_derived_not_supported) 7424 << Value.getMemberPointerDecl() << ParamType 7425 << Arg->getSourceRange(); 7426 return ExprError(); 7427 } 7428 7429 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl()); 7430 SugaredConverted = VD ? TemplateArgument(VD, ParamType) 7431 : TemplateArgument(ParamType, /*isNullPtr=*/true); 7432 CanonicalConverted = 7433 VD ? TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()), 7434 CanonParamType) 7435 : TemplateArgument(CanonParamType, /*isNullPtr=*/true); 7436 break; 7437 } 7438 case APValue::LValue: { 7439 // For a non-type template-parameter of pointer or reference type, 7440 // the value of the constant expression shall not refer to 7441 assert(ParamType->isPointerType() || ParamType->isReferenceType() || 7442 ParamType->isNullPtrType()); 7443 // -- a temporary object 7444 // -- a string literal 7445 // -- the result of a typeid expression, or 7446 // -- a predefined __func__ variable 7447 APValue::LValueBase Base = Value.getLValueBase(); 7448 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>()); 7449 if (Base && 7450 (!VD || 7451 isa<LifetimeExtendedTemporaryDecl, UnnamedGlobalConstantDecl>(VD))) { 7452 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref) 7453 << Arg->getSourceRange(); 7454 return ExprError(); 7455 } 7456 // -- a subobject 7457 // FIXME: Until C++20 7458 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && 7459 VD && VD->getType()->isArrayType() && 7460 Value.getLValuePath()[0].getAsArrayIndex() == 0 && 7461 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) { 7462 // Per defect report (no number yet): 7463 // ... other than a pointer to the first element of a complete array 7464 // object. 7465 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() || 7466 Value.isLValueOnePastTheEnd()) { 7467 Diag(StartLoc, diag::err_non_type_template_arg_subobject) 7468 << Value.getAsString(Context, ParamType); 7469 return ExprError(); 7470 } 7471 assert((VD || !ParamType->isReferenceType()) && 7472 "null reference should not be a constant expression"); 7473 assert((!VD || !ParamType->isNullPtrType()) && 7474 "non-null value of type nullptr_t?"); 7475 7476 SugaredConverted = VD ? TemplateArgument(VD, ParamType) 7477 : TemplateArgument(ParamType, /*isNullPtr=*/true); 7478 CanonicalConverted = 7479 VD ? TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()), 7480 CanonParamType) 7481 : TemplateArgument(CanonParamType, /*isNullPtr=*/true); 7482 break; 7483 } 7484 case APValue::Struct: 7485 case APValue::Union: { 7486 // Get or create the corresponding template parameter object. 7487 TemplateParamObjectDecl *D = 7488 Context.getTemplateParamObjectDecl(ParamType, Value); 7489 SugaredConverted = TemplateArgument(D, ParamType); 7490 CanonicalConverted = 7491 TemplateArgument(D->getCanonicalDecl(), CanonParamType); 7492 break; 7493 } 7494 case APValue::AddrLabelDiff: 7495 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff); 7496 case APValue::FixedPoint: 7497 case APValue::Float: 7498 case APValue::ComplexInt: 7499 case APValue::ComplexFloat: 7500 case APValue::Vector: 7501 case APValue::Array: 7502 return Diag(StartLoc, diag::err_non_type_template_arg_unsupported) 7503 << ParamType; 7504 } 7505 7506 return ArgResult.get(); 7507 } 7508 7509 // C++ [temp.arg.nontype]p5: 7510 // The following conversions are performed on each expression used 7511 // as a non-type template-argument. If a non-type 7512 // template-argument cannot be converted to the type of the 7513 // corresponding template-parameter then the program is 7514 // ill-formed. 7515 if (ParamType->isIntegralOrEnumerationType()) { 7516 // C++11: 7517 // -- for a non-type template-parameter of integral or 7518 // enumeration type, conversions permitted in a converted 7519 // constant expression are applied. 7520 // 7521 // C++98: 7522 // -- for a non-type template-parameter of integral or 7523 // enumeration type, integral promotions (4.5) and integral 7524 // conversions (4.7) are applied. 7525 7526 if (getLangOpts().CPlusPlus11) { 7527 // C++ [temp.arg.nontype]p1: 7528 // A template-argument for a non-type, non-template template-parameter 7529 // shall be one of: 7530 // 7531 // -- for a non-type template-parameter of integral or enumeration 7532 // type, a converted constant expression of the type of the 7533 // template-parameter; or 7534 llvm::APSInt Value; 7535 ExprResult ArgResult = 7536 CheckConvertedConstantExpression(Arg, ParamType, Value, 7537 CCEK_TemplateArg); 7538 if (ArgResult.isInvalid()) 7539 return ExprError(); 7540 7541 // We can't check arbitrary value-dependent arguments. 7542 if (ArgResult.get()->isValueDependent()) { 7543 SugaredConverted = TemplateArgument(ArgResult.get()); 7544 CanonicalConverted = 7545 Context.getCanonicalTemplateArgument(SugaredConverted); 7546 return ArgResult; 7547 } 7548 7549 // Widen the argument value to sizeof(parameter type). This is almost 7550 // always a no-op, except when the parameter type is bool. In 7551 // that case, this may extend the argument from 1 bit to 8 bits. 7552 QualType IntegerType = ParamType; 7553 if (const EnumType *Enum = IntegerType->getAs<EnumType>()) 7554 IntegerType = Enum->getDecl()->getIntegerType(); 7555 Value = Value.extOrTrunc(IntegerType->isBitIntType() 7556 ? Context.getIntWidth(IntegerType) 7557 : Context.getTypeSize(IntegerType)); 7558 7559 SugaredConverted = TemplateArgument(Context, Value, ParamType); 7560 CanonicalConverted = 7561 TemplateArgument(Context, Value, Context.getCanonicalType(ParamType)); 7562 return ArgResult; 7563 } 7564 7565 ExprResult ArgResult = DefaultLvalueConversion(Arg); 7566 if (ArgResult.isInvalid()) 7567 return ExprError(); 7568 Arg = ArgResult.get(); 7569 7570 QualType ArgType = Arg->getType(); 7571 7572 // C++ [temp.arg.nontype]p1: 7573 // A template-argument for a non-type, non-template 7574 // template-parameter shall be one of: 7575 // 7576 // -- an integral constant-expression of integral or enumeration 7577 // type; or 7578 // -- the name of a non-type template-parameter; or 7579 llvm::APSInt Value; 7580 if (!ArgType->isIntegralOrEnumerationType()) { 7581 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral) 7582 << ArgType << Arg->getSourceRange(); 7583 NoteTemplateParameterLocation(*Param); 7584 return ExprError(); 7585 } else if (!Arg->isValueDependent()) { 7586 class TmplArgICEDiagnoser : public VerifyICEDiagnoser { 7587 QualType T; 7588 7589 public: 7590 TmplArgICEDiagnoser(QualType T) : T(T) { } 7591 7592 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, 7593 SourceLocation Loc) override { 7594 return S.Diag(Loc, diag::err_template_arg_not_ice) << T; 7595 } 7596 } Diagnoser(ArgType); 7597 7598 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser).get(); 7599 if (!Arg) 7600 return ExprError(); 7601 } 7602 7603 // From here on out, all we care about is the unqualified form 7604 // of the argument type. 7605 ArgType = ArgType.getUnqualifiedType(); 7606 7607 // Try to convert the argument to the parameter's type. 7608 if (Context.hasSameType(ParamType, ArgType)) { 7609 // Okay: no conversion necessary 7610 } else if (ParamType->isBooleanType()) { 7611 // This is an integral-to-boolean conversion. 7612 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get(); 7613 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) || 7614 !ParamType->isEnumeralType()) { 7615 // This is an integral promotion or conversion. 7616 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get(); 7617 } else { 7618 // We can't perform this conversion. 7619 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible) 7620 << Arg->getType() << ParamType << Arg->getSourceRange(); 7621 NoteTemplateParameterLocation(*Param); 7622 return ExprError(); 7623 } 7624 7625 // Add the value of this argument to the list of converted 7626 // arguments. We use the bitwidth and signedness of the template 7627 // parameter. 7628 if (Arg->isValueDependent()) { 7629 // The argument is value-dependent. Create a new 7630 // TemplateArgument with the converted expression. 7631 SugaredConverted = TemplateArgument(Arg); 7632 CanonicalConverted = 7633 Context.getCanonicalTemplateArgument(SugaredConverted); 7634 return Arg; 7635 } 7636 7637 QualType IntegerType = ParamType; 7638 if (const EnumType *Enum = IntegerType->getAs<EnumType>()) { 7639 IntegerType = Enum->getDecl()->getIntegerType(); 7640 } 7641 7642 if (ParamType->isBooleanType()) { 7643 // Value must be zero or one. 7644 Value = Value != 0; 7645 unsigned AllowedBits = Context.getTypeSize(IntegerType); 7646 if (Value.getBitWidth() != AllowedBits) 7647 Value = Value.extOrTrunc(AllowedBits); 7648 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType()); 7649 } else { 7650 llvm::APSInt OldValue = Value; 7651 7652 // Coerce the template argument's value to the value it will have 7653 // based on the template parameter's type. 7654 unsigned AllowedBits = IntegerType->isBitIntType() 7655 ? Context.getIntWidth(IntegerType) 7656 : Context.getTypeSize(IntegerType); 7657 if (Value.getBitWidth() != AllowedBits) 7658 Value = Value.extOrTrunc(AllowedBits); 7659 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType()); 7660 7661 // Complain if an unsigned parameter received a negative value. 7662 if (IntegerType->isUnsignedIntegerOrEnumerationType() && 7663 (OldValue.isSigned() && OldValue.isNegative())) { 7664 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative) 7665 << toString(OldValue, 10) << toString(Value, 10) << Param->getType() 7666 << Arg->getSourceRange(); 7667 NoteTemplateParameterLocation(*Param); 7668 } 7669 7670 // Complain if we overflowed the template parameter's type. 7671 unsigned RequiredBits; 7672 if (IntegerType->isUnsignedIntegerOrEnumerationType()) 7673 RequiredBits = OldValue.getActiveBits(); 7674 else if (OldValue.isUnsigned()) 7675 RequiredBits = OldValue.getActiveBits() + 1; 7676 else 7677 RequiredBits = OldValue.getSignificantBits(); 7678 if (RequiredBits > AllowedBits) { 7679 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large) 7680 << toString(OldValue, 10) << toString(Value, 10) << Param->getType() 7681 << Arg->getSourceRange(); 7682 NoteTemplateParameterLocation(*Param); 7683 } 7684 } 7685 7686 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType; 7687 SugaredConverted = TemplateArgument(Context, Value, T); 7688 CanonicalConverted = 7689 TemplateArgument(Context, Value, Context.getCanonicalType(T)); 7690 return Arg; 7691 } 7692 7693 QualType ArgType = Arg->getType(); 7694 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction 7695 7696 // Handle pointer-to-function, reference-to-function, and 7697 // pointer-to-member-function all in (roughly) the same way. 7698 if (// -- For a non-type template-parameter of type pointer to 7699 // function, only the function-to-pointer conversion (4.3) is 7700 // applied. If the template-argument represents a set of 7701 // overloaded functions (or a pointer to such), the matching 7702 // function is selected from the set (13.4). 7703 (ParamType->isPointerType() && 7704 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) || 7705 // -- For a non-type template-parameter of type reference to 7706 // function, no conversions apply. If the template-argument 7707 // represents a set of overloaded functions, the matching 7708 // function is selected from the set (13.4). 7709 (ParamType->isReferenceType() && 7710 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) || 7711 // -- For a non-type template-parameter of type pointer to 7712 // member function, no conversions apply. If the 7713 // template-argument represents a set of overloaded member 7714 // functions, the matching member function is selected from 7715 // the set (13.4). 7716 (ParamType->isMemberPointerType() && 7717 ParamType->castAs<MemberPointerType>()->getPointeeType() 7718 ->isFunctionType())) { 7719 7720 if (Arg->getType() == Context.OverloadTy) { 7721 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType, 7722 true, 7723 FoundResult)) { 7724 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc())) 7725 return ExprError(); 7726 7727 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn); 7728 if (Res.isInvalid()) 7729 return ExprError(); 7730 Arg = Res.get(); 7731 ArgType = Arg->getType(); 7732 } else 7733 return ExprError(); 7734 } 7735 7736 if (!ParamType->isMemberPointerType()) { 7737 if (CheckTemplateArgumentAddressOfObjectOrFunction( 7738 *this, Param, ParamType, Arg, SugaredConverted, 7739 CanonicalConverted)) 7740 return ExprError(); 7741 return Arg; 7742 } 7743 7744 if (CheckTemplateArgumentPointerToMember( 7745 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted)) 7746 return ExprError(); 7747 return Arg; 7748 } 7749 7750 if (ParamType->isPointerType()) { 7751 // -- for a non-type template-parameter of type pointer to 7752 // object, qualification conversions (4.4) and the 7753 // array-to-pointer conversion (4.2) are applied. 7754 // C++0x also allows a value of std::nullptr_t. 7755 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() && 7756 "Only object pointers allowed here"); 7757 7758 if (CheckTemplateArgumentAddressOfObjectOrFunction( 7759 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted)) 7760 return ExprError(); 7761 return Arg; 7762 } 7763 7764 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) { 7765 // -- For a non-type template-parameter of type reference to 7766 // object, no conversions apply. The type referred to by the 7767 // reference may be more cv-qualified than the (otherwise 7768 // identical) type of the template-argument. The 7769 // template-parameter is bound directly to the 7770 // template-argument, which must be an lvalue. 7771 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() && 7772 "Only object references allowed here"); 7773 7774 if (Arg->getType() == Context.OverloadTy) { 7775 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, 7776 ParamRefType->getPointeeType(), 7777 true, 7778 FoundResult)) { 7779 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc())) 7780 return ExprError(); 7781 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn); 7782 if (Res.isInvalid()) 7783 return ExprError(); 7784 Arg = Res.get(); 7785 ArgType = Arg->getType(); 7786 } else 7787 return ExprError(); 7788 } 7789 7790 if (CheckTemplateArgumentAddressOfObjectOrFunction( 7791 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted)) 7792 return ExprError(); 7793 return Arg; 7794 } 7795 7796 // Deal with parameters of type std::nullptr_t. 7797 if (ParamType->isNullPtrType()) { 7798 if (Arg->isTypeDependent() || Arg->isValueDependent()) { 7799 SugaredConverted = TemplateArgument(Arg); 7800 CanonicalConverted = 7801 Context.getCanonicalTemplateArgument(SugaredConverted); 7802 return Arg; 7803 } 7804 7805 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) { 7806 case NPV_NotNullPointer: 7807 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible) 7808 << Arg->getType() << ParamType; 7809 NoteTemplateParameterLocation(*Param); 7810 return ExprError(); 7811 7812 case NPV_Error: 7813 return ExprError(); 7814 7815 case NPV_NullPointer: 7816 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null); 7817 SugaredConverted = TemplateArgument(ParamType, 7818 /*isNullPtr=*/true); 7819 CanonicalConverted = TemplateArgument(Context.getCanonicalType(ParamType), 7820 /*isNullPtr=*/true); 7821 return Arg; 7822 } 7823 } 7824 7825 // -- For a non-type template-parameter of type pointer to data 7826 // member, qualification conversions (4.4) are applied. 7827 assert(ParamType->isMemberPointerType() && "Only pointers to members remain"); 7828 7829 if (CheckTemplateArgumentPointerToMember( 7830 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted)) 7831 return ExprError(); 7832 return Arg; 7833 } 7834 7835 static void DiagnoseTemplateParameterListArityMismatch( 7836 Sema &S, TemplateParameterList *New, TemplateParameterList *Old, 7837 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc); 7838 7839 /// Check a template argument against its corresponding 7840 /// template template parameter. 7841 /// 7842 /// This routine implements the semantics of C++ [temp.arg.template]. 7843 /// It returns true if an error occurred, and false otherwise. 7844 bool Sema::CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param, 7845 TemplateParameterList *Params, 7846 TemplateArgumentLoc &Arg) { 7847 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern(); 7848 TemplateDecl *Template = Name.getAsTemplateDecl(); 7849 if (!Template) { 7850 // Any dependent template name is fine. 7851 assert(Name.isDependent() && "Non-dependent template isn't a declaration?"); 7852 return false; 7853 } 7854 7855 if (Template->isInvalidDecl()) 7856 return true; 7857 7858 // C++0x [temp.arg.template]p1: 7859 // A template-argument for a template template-parameter shall be 7860 // the name of a class template or an alias template, expressed as an 7861 // id-expression. When the template-argument names a class template, only 7862 // primary class templates are considered when matching the 7863 // template template argument with the corresponding parameter; 7864 // partial specializations are not considered even if their 7865 // parameter lists match that of the template template parameter. 7866 // 7867 // Note that we also allow template template parameters here, which 7868 // will happen when we are dealing with, e.g., class template 7869 // partial specializations. 7870 if (!isa<ClassTemplateDecl>(Template) && 7871 !isa<TemplateTemplateParmDecl>(Template) && 7872 !isa<TypeAliasTemplateDecl>(Template) && 7873 !isa<BuiltinTemplateDecl>(Template)) { 7874 assert(isa<FunctionTemplateDecl>(Template) && 7875 "Only function templates are possible here"); 7876 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template); 7877 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func) 7878 << Template; 7879 } 7880 7881 // C++1z [temp.arg.template]p3: (DR 150) 7882 // A template-argument matches a template template-parameter P when P 7883 // is at least as specialized as the template-argument A. 7884 // FIXME: We should enable RelaxedTemplateTemplateArgs by default as it is a 7885 // defect report resolution from C++17 and shouldn't be introduced by 7886 // concepts. 7887 if (getLangOpts().RelaxedTemplateTemplateArgs) { 7888 // Quick check for the common case: 7889 // If P contains a parameter pack, then A [...] matches P if each of A's 7890 // template parameters matches the corresponding template parameter in 7891 // the template-parameter-list of P. 7892 if (TemplateParameterListsAreEqual( 7893 Template->getTemplateParameters(), Params, false, 7894 TPL_TemplateTemplateArgumentMatch, Arg.getLocation()) && 7895 // If the argument has no associated constraints, then the parameter is 7896 // definitely at least as specialized as the argument. 7897 // Otherwise - we need a more thorough check. 7898 !Template->hasAssociatedConstraints()) 7899 return false; 7900 7901 if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template, 7902 Arg.getLocation())) { 7903 // P2113 7904 // C++20[temp.func.order]p2 7905 // [...] If both deductions succeed, the partial ordering selects the 7906 // more constrained template (if one exists) as determined below. 7907 SmallVector<const Expr *, 3> ParamsAC, TemplateAC; 7908 Params->getAssociatedConstraints(ParamsAC); 7909 // C++2a[temp.arg.template]p3 7910 // [...] In this comparison, if P is unconstrained, the constraints on A 7911 // are not considered. 7912 if (ParamsAC.empty()) 7913 return false; 7914 7915 Template->getAssociatedConstraints(TemplateAC); 7916 7917 bool IsParamAtLeastAsConstrained; 7918 if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC, 7919 IsParamAtLeastAsConstrained)) 7920 return true; 7921 if (!IsParamAtLeastAsConstrained) { 7922 Diag(Arg.getLocation(), 7923 diag::err_template_template_parameter_not_at_least_as_constrained) 7924 << Template << Param << Arg.getSourceRange(); 7925 Diag(Param->getLocation(), diag::note_entity_declared_at) << Param; 7926 Diag(Template->getLocation(), diag::note_entity_declared_at) 7927 << Template; 7928 MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Param, ParamsAC, Template, 7929 TemplateAC); 7930 return true; 7931 } 7932 return false; 7933 } 7934 // FIXME: Produce better diagnostics for deduction failures. 7935 } 7936 7937 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(), 7938 Params, 7939 true, 7940 TPL_TemplateTemplateArgumentMatch, 7941 Arg.getLocation()); 7942 } 7943 7944 static Sema::SemaDiagnosticBuilder noteLocation(Sema &S, const NamedDecl &Decl, 7945 unsigned HereDiagID, 7946 unsigned ExternalDiagID) { 7947 if (Decl.getLocation().isValid()) 7948 return S.Diag(Decl.getLocation(), HereDiagID); 7949 7950 SmallString<128> Str; 7951 llvm::raw_svector_ostream Out(Str); 7952 PrintingPolicy PP = S.getPrintingPolicy(); 7953 PP.TerseOutput = 1; 7954 Decl.print(Out, PP); 7955 return S.Diag(Decl.getLocation(), ExternalDiagID) << Out.str(); 7956 } 7957 7958 void Sema::NoteTemplateLocation(const NamedDecl &Decl, 7959 std::optional<SourceRange> ParamRange) { 7960 SemaDiagnosticBuilder DB = 7961 noteLocation(*this, Decl, diag::note_template_decl_here, 7962 diag::note_template_decl_external); 7963 if (ParamRange && ParamRange->isValid()) { 7964 assert(Decl.getLocation().isValid() && 7965 "Parameter range has location when Decl does not"); 7966 DB << *ParamRange; 7967 } 7968 } 7969 7970 void Sema::NoteTemplateParameterLocation(const NamedDecl &Decl) { 7971 noteLocation(*this, Decl, diag::note_template_param_here, 7972 diag::note_template_param_external); 7973 } 7974 7975 /// Given a non-type template argument that refers to a 7976 /// declaration and the type of its corresponding non-type template 7977 /// parameter, produce an expression that properly refers to that 7978 /// declaration. 7979 ExprResult 7980 Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, 7981 QualType ParamType, 7982 SourceLocation Loc) { 7983 // C++ [temp.param]p8: 7984 // 7985 // A non-type template-parameter of type "array of T" or 7986 // "function returning T" is adjusted to be of type "pointer to 7987 // T" or "pointer to function returning T", respectively. 7988 if (ParamType->isArrayType()) 7989 ParamType = Context.getArrayDecayedType(ParamType); 7990 else if (ParamType->isFunctionType()) 7991 ParamType = Context.getPointerType(ParamType); 7992 7993 // For a NULL non-type template argument, return nullptr casted to the 7994 // parameter's type. 7995 if (Arg.getKind() == TemplateArgument::NullPtr) { 7996 return ImpCastExprToType( 7997 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc), 7998 ParamType, 7999 ParamType->getAs<MemberPointerType>() 8000 ? CK_NullToMemberPointer 8001 : CK_NullToPointer); 8002 } 8003 assert(Arg.getKind() == TemplateArgument::Declaration && 8004 "Only declaration template arguments permitted here"); 8005 8006 ValueDecl *VD = Arg.getAsDecl(); 8007 8008 CXXScopeSpec SS; 8009 if (ParamType->isMemberPointerType()) { 8010 // If this is a pointer to member, we need to use a qualified name to 8011 // form a suitable pointer-to-member constant. 8012 assert(VD->getDeclContext()->isRecord() && 8013 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) || 8014 isa<IndirectFieldDecl>(VD))); 8015 QualType ClassType 8016 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext())); 8017 NestedNameSpecifier *Qualifier 8018 = NestedNameSpecifier::Create(Context, nullptr, false, 8019 ClassType.getTypePtr()); 8020 SS.MakeTrivial(Context, Qualifier, Loc); 8021 } 8022 8023 ExprResult RefExpr = BuildDeclarationNameExpr( 8024 SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD); 8025 if (RefExpr.isInvalid()) 8026 return ExprError(); 8027 8028 // For a pointer, the argument declaration is the pointee. Take its address. 8029 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0); 8030 if (ParamType->isPointerType() && !ElemT.isNull() && 8031 Context.hasSimilarType(ElemT, ParamType->getPointeeType())) { 8032 // Decay an array argument if we want a pointer to its first element. 8033 RefExpr = DefaultFunctionArrayConversion(RefExpr.get()); 8034 if (RefExpr.isInvalid()) 8035 return ExprError(); 8036 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) { 8037 // For any other pointer, take the address (or form a pointer-to-member). 8038 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get()); 8039 if (RefExpr.isInvalid()) 8040 return ExprError(); 8041 } else if (ParamType->isRecordType()) { 8042 assert(isa<TemplateParamObjectDecl>(VD) && 8043 "arg for class template param not a template parameter object"); 8044 // No conversions apply in this case. 8045 return RefExpr; 8046 } else { 8047 assert(ParamType->isReferenceType() && 8048 "unexpected type for decl template argument"); 8049 } 8050 8051 // At this point we should have the right value category. 8052 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() && 8053 "value kind mismatch for non-type template argument"); 8054 8055 // The type of the template parameter can differ from the type of the 8056 // argument in various ways; convert it now if necessary. 8057 QualType DestExprType = ParamType.getNonLValueExprType(Context); 8058 if (!Context.hasSameType(RefExpr.get()->getType(), DestExprType)) { 8059 CastKind CK; 8060 QualType Ignored; 8061 if (Context.hasSimilarType(RefExpr.get()->getType(), DestExprType) || 8062 IsFunctionConversion(RefExpr.get()->getType(), DestExprType, Ignored)) { 8063 CK = CK_NoOp; 8064 } else if (ParamType->isVoidPointerType() && 8065 RefExpr.get()->getType()->isPointerType()) { 8066 CK = CK_BitCast; 8067 } else { 8068 // FIXME: Pointers to members can need conversion derived-to-base or 8069 // base-to-derived conversions. We currently don't retain enough 8070 // information to convert properly (we need to track a cast path or 8071 // subobject number in the template argument). 8072 llvm_unreachable( 8073 "unexpected conversion required for non-type template argument"); 8074 } 8075 RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK, 8076 RefExpr.get()->getValueKind()); 8077 } 8078 8079 return RefExpr; 8080 } 8081 8082 /// Construct a new expression that refers to the given 8083 /// integral template argument with the given source-location 8084 /// information. 8085 /// 8086 /// This routine takes care of the mapping from an integral template 8087 /// argument (which may have any integral type) to the appropriate 8088 /// literal value. 8089 ExprResult 8090 Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, 8091 SourceLocation Loc) { 8092 assert(Arg.getKind() == TemplateArgument::Integral && 8093 "Operation is only valid for integral template arguments"); 8094 QualType OrigT = Arg.getIntegralType(); 8095 8096 // If this is an enum type that we're instantiating, we need to use an integer 8097 // type the same size as the enumerator. We don't want to build an 8098 // IntegerLiteral with enum type. The integer type of an enum type can be of 8099 // any integral type with C++11 enum classes, make sure we create the right 8100 // type of literal for it. 8101 QualType T = OrigT; 8102 if (const EnumType *ET = OrigT->getAs<EnumType>()) 8103 T = ET->getDecl()->getIntegerType(); 8104 8105 Expr *E; 8106 if (T->isAnyCharacterType()) { 8107 CharacterLiteralKind Kind; 8108 if (T->isWideCharType()) 8109 Kind = CharacterLiteralKind::Wide; 8110 else if (T->isChar8Type() && getLangOpts().Char8) 8111 Kind = CharacterLiteralKind::UTF8; 8112 else if (T->isChar16Type()) 8113 Kind = CharacterLiteralKind::UTF16; 8114 else if (T->isChar32Type()) 8115 Kind = CharacterLiteralKind::UTF32; 8116 else 8117 Kind = CharacterLiteralKind::Ascii; 8118 8119 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(), 8120 Kind, T, Loc); 8121 } else if (T->isBooleanType()) { 8122 E = CXXBoolLiteralExpr::Create(Context, Arg.getAsIntegral().getBoolValue(), 8123 T, Loc); 8124 } else if (T->isNullPtrType()) { 8125 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc); 8126 } else { 8127 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc); 8128 } 8129 8130 if (OrigT->isEnumeralType()) { 8131 // FIXME: This is a hack. We need a better way to handle substituted 8132 // non-type template parameters. 8133 E = CStyleCastExpr::Create(Context, OrigT, VK_PRValue, CK_IntegralCast, E, 8134 nullptr, CurFPFeatureOverrides(), 8135 Context.getTrivialTypeSourceInfo(OrigT, Loc), 8136 Loc, Loc); 8137 } 8138 8139 return E; 8140 } 8141 8142 /// Match two template parameters within template parameter lists. 8143 static bool MatchTemplateParameterKind( 8144 Sema &S, NamedDecl *New, 8145 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old, 8146 const NamedDecl *OldInstFrom, bool Complain, 8147 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) { 8148 // Check the actual kind (type, non-type, template). 8149 if (Old->getKind() != New->getKind()) { 8150 if (Complain) { 8151 unsigned NextDiag = diag::err_template_param_different_kind; 8152 if (TemplateArgLoc.isValid()) { 8153 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch); 8154 NextDiag = diag::note_template_param_different_kind; 8155 } 8156 S.Diag(New->getLocation(), NextDiag) 8157 << (Kind != Sema::TPL_TemplateMatch); 8158 S.Diag(Old->getLocation(), diag::note_template_prev_declaration) 8159 << (Kind != Sema::TPL_TemplateMatch); 8160 } 8161 8162 return false; 8163 } 8164 8165 // Check that both are parameter packs or neither are parameter packs. 8166 // However, if we are matching a template template argument to a 8167 // template template parameter, the template template parameter can have 8168 // a parameter pack where the template template argument does not. 8169 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() && 8170 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch && 8171 Old->isTemplateParameterPack())) { 8172 if (Complain) { 8173 unsigned NextDiag = diag::err_template_parameter_pack_non_pack; 8174 if (TemplateArgLoc.isValid()) { 8175 S.Diag(TemplateArgLoc, 8176 diag::err_template_arg_template_params_mismatch); 8177 NextDiag = diag::note_template_parameter_pack_non_pack; 8178 } 8179 8180 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0 8181 : isa<NonTypeTemplateParmDecl>(New)? 1 8182 : 2; 8183 S.Diag(New->getLocation(), NextDiag) 8184 << ParamKind << New->isParameterPack(); 8185 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here) 8186 << ParamKind << Old->isParameterPack(); 8187 } 8188 8189 return false; 8190 } 8191 8192 // For non-type template parameters, check the type of the parameter. 8193 if (NonTypeTemplateParmDecl *OldNTTP 8194 = dyn_cast<NonTypeTemplateParmDecl>(Old)) { 8195 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New); 8196 8197 // If we are matching a template template argument to a template 8198 // template parameter and one of the non-type template parameter types 8199 // is dependent, then we must wait until template instantiation time 8200 // to actually compare the arguments. 8201 if (Kind != Sema::TPL_TemplateTemplateArgumentMatch || 8202 (!OldNTTP->getType()->isDependentType() && 8203 !NewNTTP->getType()->isDependentType())) { 8204 // C++20 [temp.over.link]p6: 8205 // Two [non-type] template-parameters are equivalent [if] they have 8206 // equivalent types ignoring the use of type-constraints for 8207 // placeholder types 8208 QualType OldType = S.Context.getUnconstrainedType(OldNTTP->getType()); 8209 QualType NewType = S.Context.getUnconstrainedType(NewNTTP->getType()); 8210 if (!S.Context.hasSameType(OldType, NewType)) { 8211 if (Complain) { 8212 unsigned NextDiag = diag::err_template_nontype_parm_different_type; 8213 if (TemplateArgLoc.isValid()) { 8214 S.Diag(TemplateArgLoc, 8215 diag::err_template_arg_template_params_mismatch); 8216 NextDiag = diag::note_template_nontype_parm_different_type; 8217 } 8218 S.Diag(NewNTTP->getLocation(), NextDiag) 8219 << NewNTTP->getType() 8220 << (Kind != Sema::TPL_TemplateMatch); 8221 S.Diag(OldNTTP->getLocation(), 8222 diag::note_template_nontype_parm_prev_declaration) 8223 << OldNTTP->getType(); 8224 } 8225 8226 return false; 8227 } 8228 } 8229 } 8230 // For template template parameters, check the template parameter types. 8231 // The template parameter lists of template template 8232 // parameters must agree. 8233 else if (TemplateTemplateParmDecl *OldTTP = 8234 dyn_cast<TemplateTemplateParmDecl>(Old)) { 8235 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New); 8236 if (!S.TemplateParameterListsAreEqual( 8237 NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom, 8238 OldTTP->getTemplateParameters(), Complain, 8239 (Kind == Sema::TPL_TemplateMatch 8240 ? Sema::TPL_TemplateTemplateParmMatch 8241 : Kind), 8242 TemplateArgLoc)) 8243 return false; 8244 } 8245 8246 if (Kind != Sema::TPL_TemplateParamsEquivalent && 8247 Kind != Sema::TPL_TemplateTemplateArgumentMatch && 8248 !isa<TemplateTemplateParmDecl>(Old)) { 8249 const Expr *NewC = nullptr, *OldC = nullptr; 8250 8251 if (isa<TemplateTypeParmDecl>(New)) { 8252 if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint()) 8253 NewC = TC->getImmediatelyDeclaredConstraint(); 8254 if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint()) 8255 OldC = TC->getImmediatelyDeclaredConstraint(); 8256 } else if (isa<NonTypeTemplateParmDecl>(New)) { 8257 if (const Expr *E = cast<NonTypeTemplateParmDecl>(New) 8258 ->getPlaceholderTypeConstraint()) 8259 NewC = E; 8260 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Old) 8261 ->getPlaceholderTypeConstraint()) 8262 OldC = E; 8263 } else 8264 llvm_unreachable("unexpected template parameter type"); 8265 8266 auto Diagnose = [&] { 8267 S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(), 8268 diag::err_template_different_type_constraint); 8269 S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(), 8270 diag::note_template_prev_declaration) << /*declaration*/0; 8271 }; 8272 8273 if (!NewC != !OldC) { 8274 if (Complain) 8275 Diagnose(); 8276 return false; 8277 } 8278 8279 if (NewC) { 8280 if (!S.AreConstraintExpressionsEqual(OldInstFrom, OldC, NewInstFrom, 8281 NewC)) { 8282 if (Complain) 8283 Diagnose(); 8284 return false; 8285 } 8286 } 8287 } 8288 8289 return true; 8290 } 8291 8292 /// Diagnose a known arity mismatch when comparing template argument 8293 /// lists. 8294 static 8295 void DiagnoseTemplateParameterListArityMismatch(Sema &S, 8296 TemplateParameterList *New, 8297 TemplateParameterList *Old, 8298 Sema::TemplateParameterListEqualKind Kind, 8299 SourceLocation TemplateArgLoc) { 8300 unsigned NextDiag = diag::err_template_param_list_different_arity; 8301 if (TemplateArgLoc.isValid()) { 8302 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch); 8303 NextDiag = diag::note_template_param_list_different_arity; 8304 } 8305 S.Diag(New->getTemplateLoc(), NextDiag) 8306 << (New->size() > Old->size()) 8307 << (Kind != Sema::TPL_TemplateMatch) 8308 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc()); 8309 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration) 8310 << (Kind != Sema::TPL_TemplateMatch) 8311 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc()); 8312 } 8313 8314 /// Determine whether the given template parameter lists are 8315 /// equivalent. 8316 /// 8317 /// \param New The new template parameter list, typically written in the 8318 /// source code as part of a new template declaration. 8319 /// 8320 /// \param Old The old template parameter list, typically found via 8321 /// name lookup of the template declared with this template parameter 8322 /// list. 8323 /// 8324 /// \param Complain If true, this routine will produce a diagnostic if 8325 /// the template parameter lists are not equivalent. 8326 /// 8327 /// \param Kind describes how we are to match the template parameter lists. 8328 /// 8329 /// \param TemplateArgLoc If this source location is valid, then we 8330 /// are actually checking the template parameter list of a template 8331 /// argument (New) against the template parameter list of its 8332 /// corresponding template template parameter (Old). We produce 8333 /// slightly different diagnostics in this scenario. 8334 /// 8335 /// \returns True if the template parameter lists are equal, false 8336 /// otherwise. 8337 bool Sema::TemplateParameterListsAreEqual( 8338 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, 8339 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, 8340 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) { 8341 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) { 8342 if (Complain) 8343 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind, 8344 TemplateArgLoc); 8345 8346 return false; 8347 } 8348 8349 // C++0x [temp.arg.template]p3: 8350 // A template-argument matches a template template-parameter (call it P) 8351 // when each of the template parameters in the template-parameter-list of 8352 // the template-argument's corresponding class template or alias template 8353 // (call it A) matches the corresponding template parameter in the 8354 // template-parameter-list of P. [...] 8355 TemplateParameterList::iterator NewParm = New->begin(); 8356 TemplateParameterList::iterator NewParmEnd = New->end(); 8357 for (TemplateParameterList::iterator OldParm = Old->begin(), 8358 OldParmEnd = Old->end(); 8359 OldParm != OldParmEnd; ++OldParm) { 8360 if (Kind != TPL_TemplateTemplateArgumentMatch || 8361 !(*OldParm)->isTemplateParameterPack()) { 8362 if (NewParm == NewParmEnd) { 8363 if (Complain) 8364 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind, 8365 TemplateArgLoc); 8366 8367 return false; 8368 } 8369 8370 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm, 8371 OldInstFrom, Complain, Kind, 8372 TemplateArgLoc)) 8373 return false; 8374 8375 ++NewParm; 8376 continue; 8377 } 8378 8379 // C++0x [temp.arg.template]p3: 8380 // [...] When P's template- parameter-list contains a template parameter 8381 // pack (14.5.3), the template parameter pack will match zero or more 8382 // template parameters or template parameter packs in the 8383 // template-parameter-list of A with the same type and form as the 8384 // template parameter pack in P (ignoring whether those template 8385 // parameters are template parameter packs). 8386 for (; NewParm != NewParmEnd; ++NewParm) { 8387 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm, 8388 OldInstFrom, Complain, Kind, 8389 TemplateArgLoc)) 8390 return false; 8391 } 8392 } 8393 8394 // Make sure we exhausted all of the arguments. 8395 if (NewParm != NewParmEnd) { 8396 if (Complain) 8397 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind, 8398 TemplateArgLoc); 8399 8400 return false; 8401 } 8402 8403 if (Kind != TPL_TemplateTemplateArgumentMatch && 8404 Kind != TPL_TemplateParamsEquivalent) { 8405 const Expr *NewRC = New->getRequiresClause(); 8406 const Expr *OldRC = Old->getRequiresClause(); 8407 8408 auto Diagnose = [&] { 8409 Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(), 8410 diag::err_template_different_requires_clause); 8411 Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(), 8412 diag::note_template_prev_declaration) << /*declaration*/0; 8413 }; 8414 8415 if (!NewRC != !OldRC) { 8416 if (Complain) 8417 Diagnose(); 8418 return false; 8419 } 8420 8421 if (NewRC) { 8422 if (!AreConstraintExpressionsEqual(OldInstFrom, OldRC, NewInstFrom, 8423 NewRC)) { 8424 if (Complain) 8425 Diagnose(); 8426 return false; 8427 } 8428 } 8429 } 8430 8431 return true; 8432 } 8433 8434 /// Check whether a template can be declared within this scope. 8435 /// 8436 /// If the template declaration is valid in this scope, returns 8437 /// false. Otherwise, issues a diagnostic and returns true. 8438 bool 8439 Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) { 8440 if (!S) 8441 return false; 8442 8443 // Find the nearest enclosing declaration scope. 8444 while ((S->getFlags() & Scope::DeclScope) == 0 || 8445 (S->getFlags() & Scope::TemplateParamScope) != 0) 8446 S = S->getParent(); 8447 8448 // C++ [temp.pre]p6: [P2096] 8449 // A template, explicit specialization, or partial specialization shall not 8450 // have C linkage. 8451 DeclContext *Ctx = S->getEntity(); 8452 if (Ctx && Ctx->isExternCContext()) { 8453 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage) 8454 << TemplateParams->getSourceRange(); 8455 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext()) 8456 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 8457 return true; 8458 } 8459 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr; 8460 8461 // C++ [temp]p2: 8462 // A template-declaration can appear only as a namespace scope or 8463 // class scope declaration. 8464 // C++ [temp.expl.spec]p3: 8465 // An explicit specialization may be declared in any scope in which the 8466 // corresponding primary template may be defined. 8467 // C++ [temp.class.spec]p6: [P2096] 8468 // A partial specialization may be declared in any scope in which the 8469 // corresponding primary template may be defined. 8470 if (Ctx) { 8471 if (Ctx->isFileContext()) 8472 return false; 8473 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) { 8474 // C++ [temp.mem]p2: 8475 // A local class shall not have member templates. 8476 if (RD->isLocalClass()) 8477 return Diag(TemplateParams->getTemplateLoc(), 8478 diag::err_template_inside_local_class) 8479 << TemplateParams->getSourceRange(); 8480 else 8481 return false; 8482 } 8483 } 8484 8485 return Diag(TemplateParams->getTemplateLoc(), 8486 diag::err_template_outside_namespace_or_class_scope) 8487 << TemplateParams->getSourceRange(); 8488 } 8489 8490 /// Determine what kind of template specialization the given declaration 8491 /// is. 8492 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) { 8493 if (!D) 8494 return TSK_Undeclared; 8495 8496 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) 8497 return Record->getTemplateSpecializationKind(); 8498 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) 8499 return Function->getTemplateSpecializationKind(); 8500 if (VarDecl *Var = dyn_cast<VarDecl>(D)) 8501 return Var->getTemplateSpecializationKind(); 8502 8503 return TSK_Undeclared; 8504 } 8505 8506 /// Check whether a specialization is well-formed in the current 8507 /// context. 8508 /// 8509 /// This routine determines whether a template specialization can be declared 8510 /// in the current context (C++ [temp.expl.spec]p2). 8511 /// 8512 /// \param S the semantic analysis object for which this check is being 8513 /// performed. 8514 /// 8515 /// \param Specialized the entity being specialized or instantiated, which 8516 /// may be a kind of template (class template, function template, etc.) or 8517 /// a member of a class template (member function, static data member, 8518 /// member class). 8519 /// 8520 /// \param PrevDecl the previous declaration of this entity, if any. 8521 /// 8522 /// \param Loc the location of the explicit specialization or instantiation of 8523 /// this entity. 8524 /// 8525 /// \param IsPartialSpecialization whether this is a partial specialization of 8526 /// a class template. 8527 /// 8528 /// \returns true if there was an error that we cannot recover from, false 8529 /// otherwise. 8530 static bool CheckTemplateSpecializationScope(Sema &S, 8531 NamedDecl *Specialized, 8532 NamedDecl *PrevDecl, 8533 SourceLocation Loc, 8534 bool IsPartialSpecialization) { 8535 // Keep these "kind" numbers in sync with the %select statements in the 8536 // various diagnostics emitted by this routine. 8537 int EntityKind = 0; 8538 if (isa<ClassTemplateDecl>(Specialized)) 8539 EntityKind = IsPartialSpecialization? 1 : 0; 8540 else if (isa<VarTemplateDecl>(Specialized)) 8541 EntityKind = IsPartialSpecialization ? 3 : 2; 8542 else if (isa<FunctionTemplateDecl>(Specialized)) 8543 EntityKind = 4; 8544 else if (isa<CXXMethodDecl>(Specialized)) 8545 EntityKind = 5; 8546 else if (isa<VarDecl>(Specialized)) 8547 EntityKind = 6; 8548 else if (isa<RecordDecl>(Specialized)) 8549 EntityKind = 7; 8550 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11) 8551 EntityKind = 8; 8552 else { 8553 S.Diag(Loc, diag::err_template_spec_unknown_kind) 8554 << S.getLangOpts().CPlusPlus11; 8555 S.Diag(Specialized->getLocation(), diag::note_specialized_entity); 8556 return true; 8557 } 8558 8559 // C++ [temp.expl.spec]p2: 8560 // An explicit specialization may be declared in any scope in which 8561 // the corresponding primary template may be defined. 8562 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) { 8563 S.Diag(Loc, diag::err_template_spec_decl_function_scope) 8564 << Specialized; 8565 return true; 8566 } 8567 8568 // C++ [temp.class.spec]p6: 8569 // A class template partial specialization may be declared in any 8570 // scope in which the primary template may be defined. 8571 DeclContext *SpecializedContext = 8572 Specialized->getDeclContext()->getRedeclContext(); 8573 DeclContext *DC = S.CurContext->getRedeclContext(); 8574 8575 // Make sure that this redeclaration (or definition) occurs in the same 8576 // scope or an enclosing namespace. 8577 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext) 8578 : DC->Equals(SpecializedContext))) { 8579 if (isa<TranslationUnitDecl>(SpecializedContext)) 8580 S.Diag(Loc, diag::err_template_spec_redecl_global_scope) 8581 << EntityKind << Specialized; 8582 else { 8583 auto *ND = cast<NamedDecl>(SpecializedContext); 8584 int Diag = diag::err_template_spec_redecl_out_of_scope; 8585 if (S.getLangOpts().MicrosoftExt && !DC->isRecord()) 8586 Diag = diag::ext_ms_template_spec_redecl_out_of_scope; 8587 S.Diag(Loc, Diag) << EntityKind << Specialized 8588 << ND << isa<CXXRecordDecl>(ND); 8589 } 8590 8591 S.Diag(Specialized->getLocation(), diag::note_specialized_entity); 8592 8593 // Don't allow specializing in the wrong class during error recovery. 8594 // Otherwise, things can go horribly wrong. 8595 if (DC->isRecord()) 8596 return true; 8597 } 8598 8599 return false; 8600 } 8601 8602 static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) { 8603 if (!E->isTypeDependent()) 8604 return SourceLocation(); 8605 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true); 8606 Checker.TraverseStmt(E); 8607 if (Checker.MatchLoc.isInvalid()) 8608 return E->getSourceRange(); 8609 return Checker.MatchLoc; 8610 } 8611 8612 static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) { 8613 if (!TL.getType()->isDependentType()) 8614 return SourceLocation(); 8615 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true); 8616 Checker.TraverseTypeLoc(TL); 8617 if (Checker.MatchLoc.isInvalid()) 8618 return TL.getSourceRange(); 8619 return Checker.MatchLoc; 8620 } 8621 8622 /// Subroutine of Sema::CheckTemplatePartialSpecializationArgs 8623 /// that checks non-type template partial specialization arguments. 8624 static bool CheckNonTypeTemplatePartialSpecializationArgs( 8625 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param, 8626 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) { 8627 for (unsigned I = 0; I != NumArgs; ++I) { 8628 if (Args[I].getKind() == TemplateArgument::Pack) { 8629 if (CheckNonTypeTemplatePartialSpecializationArgs( 8630 S, TemplateNameLoc, Param, Args[I].pack_begin(), 8631 Args[I].pack_size(), IsDefaultArgument)) 8632 return true; 8633 8634 continue; 8635 } 8636 8637 if (Args[I].getKind() != TemplateArgument::Expression) 8638 continue; 8639 8640 Expr *ArgExpr = Args[I].getAsExpr(); 8641 8642 // We can have a pack expansion of any of the bullets below. 8643 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr)) 8644 ArgExpr = Expansion->getPattern(); 8645 8646 // Strip off any implicit casts we added as part of type checking. 8647 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 8648 ArgExpr = ICE->getSubExpr(); 8649 8650 // C++ [temp.class.spec]p8: 8651 // A non-type argument is non-specialized if it is the name of a 8652 // non-type parameter. All other non-type arguments are 8653 // specialized. 8654 // 8655 // Below, we check the two conditions that only apply to 8656 // specialized non-type arguments, so skip any non-specialized 8657 // arguments. 8658 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr)) 8659 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl())) 8660 continue; 8661 8662 // C++ [temp.class.spec]p9: 8663 // Within the argument list of a class template partial 8664 // specialization, the following restrictions apply: 8665 // -- A partially specialized non-type argument expression 8666 // shall not involve a template parameter of the partial 8667 // specialization except when the argument expression is a 8668 // simple identifier. 8669 // -- The type of a template parameter corresponding to a 8670 // specialized non-type argument shall not be dependent on a 8671 // parameter of the specialization. 8672 // DR1315 removes the first bullet, leaving an incoherent set of rules. 8673 // We implement a compromise between the original rules and DR1315: 8674 // -- A specialized non-type template argument shall not be 8675 // type-dependent and the corresponding template parameter 8676 // shall have a non-dependent type. 8677 SourceRange ParamUseRange = 8678 findTemplateParameterInType(Param->getDepth(), ArgExpr); 8679 if (ParamUseRange.isValid()) { 8680 if (IsDefaultArgument) { 8681 S.Diag(TemplateNameLoc, 8682 diag::err_dependent_non_type_arg_in_partial_spec); 8683 S.Diag(ParamUseRange.getBegin(), 8684 diag::note_dependent_non_type_default_arg_in_partial_spec) 8685 << ParamUseRange; 8686 } else { 8687 S.Diag(ParamUseRange.getBegin(), 8688 diag::err_dependent_non_type_arg_in_partial_spec) 8689 << ParamUseRange; 8690 } 8691 return true; 8692 } 8693 8694 ParamUseRange = findTemplateParameter( 8695 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc()); 8696 if (ParamUseRange.isValid()) { 8697 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(), 8698 diag::err_dependent_typed_non_type_arg_in_partial_spec) 8699 << Param->getType(); 8700 S.NoteTemplateParameterLocation(*Param); 8701 return true; 8702 } 8703 } 8704 8705 return false; 8706 } 8707 8708 /// Check the non-type template arguments of a class template 8709 /// partial specialization according to C++ [temp.class.spec]p9. 8710 /// 8711 /// \param TemplateNameLoc the location of the template name. 8712 /// \param PrimaryTemplate the template parameters of the primary class 8713 /// template. 8714 /// \param NumExplicit the number of explicitly-specified template arguments. 8715 /// \param TemplateArgs the template arguments of the class template 8716 /// partial specialization. 8717 /// 8718 /// \returns \c true if there was an error, \c false otherwise. 8719 bool Sema::CheckTemplatePartialSpecializationArgs( 8720 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate, 8721 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) { 8722 // We have to be conservative when checking a template in a dependent 8723 // context. 8724 if (PrimaryTemplate->getDeclContext()->isDependentContext()) 8725 return false; 8726 8727 TemplateParameterList *TemplateParams = 8728 PrimaryTemplate->getTemplateParameters(); 8729 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) { 8730 NonTypeTemplateParmDecl *Param 8731 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I)); 8732 if (!Param) 8733 continue; 8734 8735 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc, 8736 Param, &TemplateArgs[I], 8737 1, I >= NumExplicit)) 8738 return true; 8739 } 8740 8741 return false; 8742 } 8743 8744 DeclResult Sema::ActOnClassTemplateSpecialization( 8745 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, 8746 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS, 8747 TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr, 8748 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) { 8749 assert(TUK != TUK_Reference && "References are not specializations"); 8750 8751 // NOTE: KWLoc is the location of the tag keyword. This will instead 8752 // store the location of the outermost template keyword in the declaration. 8753 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0 8754 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc; 8755 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc; 8756 SourceLocation LAngleLoc = TemplateId.LAngleLoc; 8757 SourceLocation RAngleLoc = TemplateId.RAngleLoc; 8758 8759 // Find the class template we're specializing 8760 TemplateName Name = TemplateId.Template.get(); 8761 ClassTemplateDecl *ClassTemplate 8762 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl()); 8763 8764 if (!ClassTemplate) { 8765 Diag(TemplateNameLoc, diag::err_not_class_template_specialization) 8766 << (Name.getAsTemplateDecl() && 8767 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())); 8768 return true; 8769 } 8770 8771 bool isMemberSpecialization = false; 8772 bool isPartialSpecialization = false; 8773 8774 // Check the validity of the template headers that introduce this 8775 // template. 8776 // FIXME: We probably shouldn't complain about these headers for 8777 // friend declarations. 8778 bool Invalid = false; 8779 TemplateParameterList *TemplateParams = 8780 MatchTemplateParametersToScopeSpecifier( 8781 KWLoc, TemplateNameLoc, SS, &TemplateId, 8782 TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization, 8783 Invalid); 8784 if (Invalid) 8785 return true; 8786 8787 // Check that we can declare a template specialization here. 8788 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams)) 8789 return true; 8790 8791 if (TemplateParams && TemplateParams->size() > 0) { 8792 isPartialSpecialization = true; 8793 8794 if (TUK == TUK_Friend) { 8795 Diag(KWLoc, diag::err_partial_specialization_friend) 8796 << SourceRange(LAngleLoc, RAngleLoc); 8797 return true; 8798 } 8799 8800 // C++ [temp.class.spec]p10: 8801 // The template parameter list of a specialization shall not 8802 // contain default template argument values. 8803 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) { 8804 Decl *Param = TemplateParams->getParam(I); 8805 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) { 8806 if (TTP->hasDefaultArgument()) { 8807 Diag(TTP->getDefaultArgumentLoc(), 8808 diag::err_default_arg_in_partial_spec); 8809 TTP->removeDefaultArgument(); 8810 } 8811 } else if (NonTypeTemplateParmDecl *NTTP 8812 = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 8813 if (Expr *DefArg = NTTP->getDefaultArgument()) { 8814 Diag(NTTP->getDefaultArgumentLoc(), 8815 diag::err_default_arg_in_partial_spec) 8816 << DefArg->getSourceRange(); 8817 NTTP->removeDefaultArgument(); 8818 } 8819 } else { 8820 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param); 8821 if (TTP->hasDefaultArgument()) { 8822 Diag(TTP->getDefaultArgument().getLocation(), 8823 diag::err_default_arg_in_partial_spec) 8824 << TTP->getDefaultArgument().getSourceRange(); 8825 TTP->removeDefaultArgument(); 8826 } 8827 } 8828 } 8829 } else if (TemplateParams) { 8830 if (TUK == TUK_Friend) 8831 Diag(KWLoc, diag::err_template_spec_friend) 8832 << FixItHint::CreateRemoval( 8833 SourceRange(TemplateParams->getTemplateLoc(), 8834 TemplateParams->getRAngleLoc())) 8835 << SourceRange(LAngleLoc, RAngleLoc); 8836 } else { 8837 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl"); 8838 } 8839 8840 // Check that the specialization uses the same tag kind as the 8841 // original template. 8842 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 8843 assert(Kind != TagTypeKind::Enum && 8844 "Invalid enum tag in class template spec!"); 8845 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), 8846 Kind, TUK == TUK_Definition, KWLoc, 8847 ClassTemplate->getIdentifier())) { 8848 Diag(KWLoc, diag::err_use_with_wrong_tag) 8849 << ClassTemplate 8850 << FixItHint::CreateReplacement(KWLoc, 8851 ClassTemplate->getTemplatedDecl()->getKindName()); 8852 Diag(ClassTemplate->getTemplatedDecl()->getLocation(), 8853 diag::note_previous_use); 8854 Kind = ClassTemplate->getTemplatedDecl()->getTagKind(); 8855 } 8856 8857 // Translate the parser's template argument list in our AST format. 8858 TemplateArgumentListInfo TemplateArgs = 8859 makeTemplateArgumentListInfo(*this, TemplateId); 8860 8861 // Check for unexpanded parameter packs in any of the template arguments. 8862 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 8863 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I], 8864 isPartialSpecialization 8865 ? UPPC_PartialSpecialization 8866 : UPPC_ExplicitSpecialization)) 8867 return true; 8868 8869 // Check that the template argument list is well-formed for this 8870 // template. 8871 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted; 8872 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs, 8873 false, SugaredConverted, CanonicalConverted, 8874 /*UpdateArgsWithConversions=*/true)) 8875 return true; 8876 8877 // Find the class template (partial) specialization declaration that 8878 // corresponds to these arguments. 8879 if (isPartialSpecialization) { 8880 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate, 8881 TemplateArgs.size(), 8882 CanonicalConverted)) 8883 return true; 8884 8885 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we 8886 // also do it during instantiation. 8887 if (!Name.isDependent() && 8888 !TemplateSpecializationType::anyDependentTemplateArguments( 8889 TemplateArgs, CanonicalConverted)) { 8890 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized) 8891 << ClassTemplate->getDeclName(); 8892 isPartialSpecialization = false; 8893 } 8894 } 8895 8896 void *InsertPos = nullptr; 8897 ClassTemplateSpecializationDecl *PrevDecl = nullptr; 8898 8899 if (isPartialSpecialization) 8900 PrevDecl = ClassTemplate->findPartialSpecialization( 8901 CanonicalConverted, TemplateParams, InsertPos); 8902 else 8903 PrevDecl = ClassTemplate->findSpecialization(CanonicalConverted, InsertPos); 8904 8905 ClassTemplateSpecializationDecl *Specialization = nullptr; 8906 8907 // Check whether we can declare a class template specialization in 8908 // the current scope. 8909 if (TUK != TUK_Friend && 8910 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl, 8911 TemplateNameLoc, 8912 isPartialSpecialization)) 8913 return true; 8914 8915 // The canonical type 8916 QualType CanonType; 8917 if (isPartialSpecialization) { 8918 // Build the canonical type that describes the converted template 8919 // arguments of the class template partial specialization. 8920 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name); 8921 CanonType = Context.getTemplateSpecializationType(CanonTemplate, 8922 CanonicalConverted); 8923 8924 if (Context.hasSameType(CanonType, 8925 ClassTemplate->getInjectedClassNameSpecialization()) && 8926 (!Context.getLangOpts().CPlusPlus20 || 8927 !TemplateParams->hasAssociatedConstraints())) { 8928 // C++ [temp.class.spec]p9b3: 8929 // 8930 // -- The argument list of the specialization shall not be identical 8931 // to the implicit argument list of the primary template. 8932 // 8933 // This rule has since been removed, because it's redundant given DR1495, 8934 // but we keep it because it produces better diagnostics and recovery. 8935 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template) 8936 << /*class template*/0 << (TUK == TUK_Definition) 8937 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc)); 8938 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS, 8939 ClassTemplate->getIdentifier(), 8940 TemplateNameLoc, 8941 Attr, 8942 TemplateParams, 8943 AS_none, /*ModulePrivateLoc=*/SourceLocation(), 8944 /*FriendLoc*/SourceLocation(), 8945 TemplateParameterLists.size() - 1, 8946 TemplateParameterLists.data()); 8947 } 8948 8949 // Create a new class template partial specialization declaration node. 8950 ClassTemplatePartialSpecializationDecl *PrevPartial 8951 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl); 8952 ClassTemplatePartialSpecializationDecl *Partial = 8953 ClassTemplatePartialSpecializationDecl::Create( 8954 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, 8955 TemplateNameLoc, TemplateParams, ClassTemplate, CanonicalConverted, 8956 TemplateArgs, CanonType, PrevPartial); 8957 SetNestedNameSpecifier(*this, Partial, SS); 8958 if (TemplateParameterLists.size() > 1 && SS.isSet()) { 8959 Partial->setTemplateParameterListsInfo( 8960 Context, TemplateParameterLists.drop_back(1)); 8961 } 8962 8963 if (!PrevPartial) 8964 ClassTemplate->AddPartialSpecialization(Partial, InsertPos); 8965 Specialization = Partial; 8966 8967 // If we are providing an explicit specialization of a member class 8968 // template specialization, make a note of that. 8969 if (PrevPartial && PrevPartial->getInstantiatedFromMember()) 8970 PrevPartial->setMemberSpecialization(); 8971 8972 CheckTemplatePartialSpecialization(Partial); 8973 } else { 8974 // Create a new class template specialization declaration node for 8975 // this explicit specialization or friend declaration. 8976 Specialization = ClassTemplateSpecializationDecl::Create( 8977 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc, 8978 ClassTemplate, CanonicalConverted, PrevDecl); 8979 SetNestedNameSpecifier(*this, Specialization, SS); 8980 if (TemplateParameterLists.size() > 0) { 8981 Specialization->setTemplateParameterListsInfo(Context, 8982 TemplateParameterLists); 8983 } 8984 8985 if (!PrevDecl) 8986 ClassTemplate->AddSpecialization(Specialization, InsertPos); 8987 8988 if (CurContext->isDependentContext()) { 8989 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name); 8990 CanonType = Context.getTemplateSpecializationType(CanonTemplate, 8991 CanonicalConverted); 8992 } else { 8993 CanonType = Context.getTypeDeclType(Specialization); 8994 } 8995 } 8996 8997 // C++ [temp.expl.spec]p6: 8998 // If a template, a member template or the member of a class template is 8999 // explicitly specialized then that specialization shall be declared 9000 // before the first use of that specialization that would cause an implicit 9001 // instantiation to take place, in every translation unit in which such a 9002 // use occurs; no diagnostic is required. 9003 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) { 9004 bool Okay = false; 9005 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) { 9006 // Is there any previous explicit specialization declaration? 9007 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) { 9008 Okay = true; 9009 break; 9010 } 9011 } 9012 9013 if (!Okay) { 9014 SourceRange Range(TemplateNameLoc, RAngleLoc); 9015 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation) 9016 << Context.getTypeDeclType(Specialization) << Range; 9017 9018 Diag(PrevDecl->getPointOfInstantiation(), 9019 diag::note_instantiation_required_here) 9020 << (PrevDecl->getTemplateSpecializationKind() 9021 != TSK_ImplicitInstantiation); 9022 return true; 9023 } 9024 } 9025 9026 // If this is not a friend, note that this is an explicit specialization. 9027 if (TUK != TUK_Friend) 9028 Specialization->setSpecializationKind(TSK_ExplicitSpecialization); 9029 9030 // Check that this isn't a redefinition of this specialization. 9031 if (TUK == TUK_Definition) { 9032 RecordDecl *Def = Specialization->getDefinition(); 9033 NamedDecl *Hidden = nullptr; 9034 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 9035 SkipBody->ShouldSkip = true; 9036 SkipBody->Previous = Def; 9037 makeMergedDefinitionVisible(Hidden); 9038 } else if (Def) { 9039 SourceRange Range(TemplateNameLoc, RAngleLoc); 9040 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range; 9041 Diag(Def->getLocation(), diag::note_previous_definition); 9042 Specialization->setInvalidDecl(); 9043 return true; 9044 } 9045 } 9046 9047 ProcessDeclAttributeList(S, Specialization, Attr); 9048 9049 // Add alignment attributes if necessary; these attributes are checked when 9050 // the ASTContext lays out the structure. 9051 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 9052 AddAlignmentAttributesForRecord(Specialization); 9053 AddMsStructLayoutForRecord(Specialization); 9054 } 9055 9056 if (ModulePrivateLoc.isValid()) 9057 Diag(Specialization->getLocation(), diag::err_module_private_specialization) 9058 << (isPartialSpecialization? 1 : 0) 9059 << FixItHint::CreateRemoval(ModulePrivateLoc); 9060 9061 // Build the fully-sugared type for this class template 9062 // specialization as the user wrote in the specialization 9063 // itself. This means that we'll pretty-print the type retrieved 9064 // from the specialization's declaration the way that the user 9065 // actually wrote the specialization, rather than formatting the 9066 // name based on the "canonical" representation used to store the 9067 // template arguments in the specialization. 9068 TypeSourceInfo *WrittenTy 9069 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc, 9070 TemplateArgs, CanonType); 9071 if (TUK != TUK_Friend) { 9072 Specialization->setTypeAsWritten(WrittenTy); 9073 Specialization->setTemplateKeywordLoc(TemplateKWLoc); 9074 } 9075 9076 // C++ [temp.expl.spec]p9: 9077 // A template explicit specialization is in the scope of the 9078 // namespace in which the template was defined. 9079 // 9080 // We actually implement this paragraph where we set the semantic 9081 // context (in the creation of the ClassTemplateSpecializationDecl), 9082 // but we also maintain the lexical context where the actual 9083 // definition occurs. 9084 Specialization->setLexicalDeclContext(CurContext); 9085 9086 // We may be starting the definition of this specialization. 9087 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 9088 Specialization->startDefinition(); 9089 9090 if (TUK == TUK_Friend) { 9091 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, 9092 TemplateNameLoc, 9093 WrittenTy, 9094 /*FIXME:*/KWLoc); 9095 Friend->setAccess(AS_public); 9096 CurContext->addDecl(Friend); 9097 } else { 9098 // Add the specialization into its lexical context, so that it can 9099 // be seen when iterating through the list of declarations in that 9100 // context. However, specializations are not found by name lookup. 9101 CurContext->addDecl(Specialization); 9102 } 9103 9104 if (SkipBody && SkipBody->ShouldSkip) 9105 return SkipBody->Previous; 9106 9107 return Specialization; 9108 } 9109 9110 Decl *Sema::ActOnTemplateDeclarator(Scope *S, 9111 MultiTemplateParamsArg TemplateParameterLists, 9112 Declarator &D) { 9113 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists); 9114 ActOnDocumentableDecl(NewDecl); 9115 return NewDecl; 9116 } 9117 9118 Decl *Sema::ActOnConceptDefinition(Scope *S, 9119 MultiTemplateParamsArg TemplateParameterLists, 9120 IdentifierInfo *Name, SourceLocation NameLoc, 9121 Expr *ConstraintExpr) { 9122 DeclContext *DC = CurContext; 9123 9124 if (!DC->getRedeclContext()->isFileContext()) { 9125 Diag(NameLoc, 9126 diag::err_concept_decls_may_only_appear_in_global_namespace_scope); 9127 return nullptr; 9128 } 9129 9130 if (TemplateParameterLists.size() > 1) { 9131 Diag(NameLoc, diag::err_concept_extra_headers); 9132 return nullptr; 9133 } 9134 9135 TemplateParameterList *Params = TemplateParameterLists.front(); 9136 9137 if (Params->size() == 0) { 9138 Diag(NameLoc, diag::err_concept_no_parameters); 9139 return nullptr; 9140 } 9141 9142 // Ensure that the parameter pack, if present, is the last parameter in the 9143 // template. 9144 for (TemplateParameterList::const_iterator ParamIt = Params->begin(), 9145 ParamEnd = Params->end(); 9146 ParamIt != ParamEnd; ++ParamIt) { 9147 Decl const *Param = *ParamIt; 9148 if (Param->isParameterPack()) { 9149 if (++ParamIt == ParamEnd) 9150 break; 9151 Diag(Param->getLocation(), 9152 diag::err_template_param_pack_must_be_last_template_parameter); 9153 return nullptr; 9154 } 9155 } 9156 9157 if (DiagnoseUnexpandedParameterPack(ConstraintExpr)) 9158 return nullptr; 9159 9160 ConceptDecl *NewDecl = 9161 ConceptDecl::Create(Context, DC, NameLoc, Name, Params, ConstraintExpr); 9162 9163 if (NewDecl->hasAssociatedConstraints()) { 9164 // C++2a [temp.concept]p4: 9165 // A concept shall not have associated constraints. 9166 Diag(NameLoc, diag::err_concept_no_associated_constraints); 9167 NewDecl->setInvalidDecl(); 9168 } 9169 9170 // Check for conflicting previous declaration. 9171 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NameLoc); 9172 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 9173 forRedeclarationInCurContext()); 9174 LookupName(Previous, S); 9175 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage=*/false, 9176 /*AllowInlineNamespace*/false); 9177 bool AddToScope = true; 9178 CheckConceptRedefinition(NewDecl, Previous, AddToScope); 9179 9180 ActOnDocumentableDecl(NewDecl); 9181 if (AddToScope) 9182 PushOnScopeChains(NewDecl, S); 9183 return NewDecl; 9184 } 9185 9186 void Sema::CheckConceptRedefinition(ConceptDecl *NewDecl, 9187 LookupResult &Previous, bool &AddToScope) { 9188 AddToScope = true; 9189 9190 if (Previous.empty()) 9191 return; 9192 9193 auto *OldConcept = dyn_cast<ConceptDecl>(Previous.getRepresentativeDecl()->getUnderlyingDecl()); 9194 if (!OldConcept) { 9195 auto *Old = Previous.getRepresentativeDecl(); 9196 Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind) 9197 << NewDecl->getDeclName(); 9198 notePreviousDefinition(Old, NewDecl->getLocation()); 9199 AddToScope = false; 9200 return; 9201 } 9202 // Check if we can merge with a concept declaration. 9203 bool IsSame = Context.isSameEntity(NewDecl, OldConcept); 9204 if (!IsSame) { 9205 Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept) 9206 << NewDecl->getDeclName(); 9207 notePreviousDefinition(OldConcept, NewDecl->getLocation()); 9208 AddToScope = false; 9209 return; 9210 } 9211 if (hasReachableDefinition(OldConcept) && 9212 IsRedefinitionInModule(NewDecl, OldConcept)) { 9213 Diag(NewDecl->getLocation(), diag::err_redefinition) 9214 << NewDecl->getDeclName(); 9215 notePreviousDefinition(OldConcept, NewDecl->getLocation()); 9216 AddToScope = false; 9217 return; 9218 } 9219 if (!Previous.isSingleResult()) { 9220 // FIXME: we should produce an error in case of ambig and failed lookups. 9221 // Other decls (e.g. namespaces) also have this shortcoming. 9222 return; 9223 } 9224 // We unwrap canonical decl late to check for module visibility. 9225 Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl()); 9226 } 9227 9228 /// \brief Strips various properties off an implicit instantiation 9229 /// that has just been explicitly specialized. 9230 static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) { 9231 if (MinGW || (isa<FunctionDecl>(D) && 9232 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())) { 9233 D->dropAttr<DLLImportAttr>(); 9234 D->dropAttr<DLLExportAttr>(); 9235 } 9236 9237 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 9238 FD->setInlineSpecified(false); 9239 } 9240 9241 /// Compute the diagnostic location for an explicit instantiation 9242 // declaration or definition. 9243 static SourceLocation DiagLocForExplicitInstantiation( 9244 NamedDecl* D, SourceLocation PointOfInstantiation) { 9245 // Explicit instantiations following a specialization have no effect and 9246 // hence no PointOfInstantiation. In that case, walk decl backwards 9247 // until a valid name loc is found. 9248 SourceLocation PrevDiagLoc = PointOfInstantiation; 9249 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid(); 9250 Prev = Prev->getPreviousDecl()) { 9251 PrevDiagLoc = Prev->getLocation(); 9252 } 9253 assert(PrevDiagLoc.isValid() && 9254 "Explicit instantiation without point of instantiation?"); 9255 return PrevDiagLoc; 9256 } 9257 9258 /// Diagnose cases where we have an explicit template specialization 9259 /// before/after an explicit template instantiation, producing diagnostics 9260 /// for those cases where they are required and determining whether the 9261 /// new specialization/instantiation will have any effect. 9262 /// 9263 /// \param NewLoc the location of the new explicit specialization or 9264 /// instantiation. 9265 /// 9266 /// \param NewTSK the kind of the new explicit specialization or instantiation. 9267 /// 9268 /// \param PrevDecl the previous declaration of the entity. 9269 /// 9270 /// \param PrevTSK the kind of the old explicit specialization or instantiatin. 9271 /// 9272 /// \param PrevPointOfInstantiation if valid, indicates where the previous 9273 /// declaration was instantiated (either implicitly or explicitly). 9274 /// 9275 /// \param HasNoEffect will be set to true to indicate that the new 9276 /// specialization or instantiation has no effect and should be ignored. 9277 /// 9278 /// \returns true if there was an error that should prevent the introduction of 9279 /// the new declaration into the AST, false otherwise. 9280 bool 9281 Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, 9282 TemplateSpecializationKind NewTSK, 9283 NamedDecl *PrevDecl, 9284 TemplateSpecializationKind PrevTSK, 9285 SourceLocation PrevPointOfInstantiation, 9286 bool &HasNoEffect) { 9287 HasNoEffect = false; 9288 9289 switch (NewTSK) { 9290 case TSK_Undeclared: 9291 case TSK_ImplicitInstantiation: 9292 assert( 9293 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) && 9294 "previous declaration must be implicit!"); 9295 return false; 9296 9297 case TSK_ExplicitSpecialization: 9298 switch (PrevTSK) { 9299 case TSK_Undeclared: 9300 case TSK_ExplicitSpecialization: 9301 // Okay, we're just specializing something that is either already 9302 // explicitly specialized or has merely been mentioned without any 9303 // instantiation. 9304 return false; 9305 9306 case TSK_ImplicitInstantiation: 9307 if (PrevPointOfInstantiation.isInvalid()) { 9308 // The declaration itself has not actually been instantiated, so it is 9309 // still okay to specialize it. 9310 StripImplicitInstantiation( 9311 PrevDecl, 9312 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()); 9313 return false; 9314 } 9315 // Fall through 9316 [[fallthrough]]; 9317 9318 case TSK_ExplicitInstantiationDeclaration: 9319 case TSK_ExplicitInstantiationDefinition: 9320 assert((PrevTSK == TSK_ImplicitInstantiation || 9321 PrevPointOfInstantiation.isValid()) && 9322 "Explicit instantiation without point of instantiation?"); 9323 9324 // C++ [temp.expl.spec]p6: 9325 // If a template, a member template or the member of a class template 9326 // is explicitly specialized then that specialization shall be declared 9327 // before the first use of that specialization that would cause an 9328 // implicit instantiation to take place, in every translation unit in 9329 // which such a use occurs; no diagnostic is required. 9330 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) { 9331 // Is there any previous explicit specialization declaration? 9332 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) 9333 return false; 9334 } 9335 9336 Diag(NewLoc, diag::err_specialization_after_instantiation) 9337 << PrevDecl; 9338 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here) 9339 << (PrevTSK != TSK_ImplicitInstantiation); 9340 9341 return true; 9342 } 9343 llvm_unreachable("The switch over PrevTSK must be exhaustive."); 9344 9345 case TSK_ExplicitInstantiationDeclaration: 9346 switch (PrevTSK) { 9347 case TSK_ExplicitInstantiationDeclaration: 9348 // This explicit instantiation declaration is redundant (that's okay). 9349 HasNoEffect = true; 9350 return false; 9351 9352 case TSK_Undeclared: 9353 case TSK_ImplicitInstantiation: 9354 // We're explicitly instantiating something that may have already been 9355 // implicitly instantiated; that's fine. 9356 return false; 9357 9358 case TSK_ExplicitSpecialization: 9359 // C++0x [temp.explicit]p4: 9360 // For a given set of template parameters, if an explicit instantiation 9361 // of a template appears after a declaration of an explicit 9362 // specialization for that template, the explicit instantiation has no 9363 // effect. 9364 HasNoEffect = true; 9365 return false; 9366 9367 case TSK_ExplicitInstantiationDefinition: 9368 // C++0x [temp.explicit]p10: 9369 // If an entity is the subject of both an explicit instantiation 9370 // declaration and an explicit instantiation definition in the same 9371 // translation unit, the definition shall follow the declaration. 9372 Diag(NewLoc, 9373 diag::err_explicit_instantiation_declaration_after_definition); 9374 9375 // Explicit instantiations following a specialization have no effect and 9376 // hence no PrevPointOfInstantiation. In that case, walk decl backwards 9377 // until a valid name loc is found. 9378 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation), 9379 diag::note_explicit_instantiation_definition_here); 9380 HasNoEffect = true; 9381 return false; 9382 } 9383 llvm_unreachable("Unexpected TemplateSpecializationKind!"); 9384 9385 case TSK_ExplicitInstantiationDefinition: 9386 switch (PrevTSK) { 9387 case TSK_Undeclared: 9388 case TSK_ImplicitInstantiation: 9389 // We're explicitly instantiating something that may have already been 9390 // implicitly instantiated; that's fine. 9391 return false; 9392 9393 case TSK_ExplicitSpecialization: 9394 // C++ DR 259, C++0x [temp.explicit]p4: 9395 // For a given set of template parameters, if an explicit 9396 // instantiation of a template appears after a declaration of 9397 // an explicit specialization for that template, the explicit 9398 // instantiation has no effect. 9399 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization) 9400 << PrevDecl; 9401 Diag(PrevDecl->getLocation(), 9402 diag::note_previous_template_specialization); 9403 HasNoEffect = true; 9404 return false; 9405 9406 case TSK_ExplicitInstantiationDeclaration: 9407 // We're explicitly instantiating a definition for something for which we 9408 // were previously asked to suppress instantiations. That's fine. 9409 9410 // C++0x [temp.explicit]p4: 9411 // For a given set of template parameters, if an explicit instantiation 9412 // of a template appears after a declaration of an explicit 9413 // specialization for that template, the explicit instantiation has no 9414 // effect. 9415 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) { 9416 // Is there any previous explicit specialization declaration? 9417 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) { 9418 HasNoEffect = true; 9419 break; 9420 } 9421 } 9422 9423 return false; 9424 9425 case TSK_ExplicitInstantiationDefinition: 9426 // C++0x [temp.spec]p5: 9427 // For a given template and a given set of template-arguments, 9428 // - an explicit instantiation definition shall appear at most once 9429 // in a program, 9430 9431 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations. 9432 Diag(NewLoc, (getLangOpts().MSVCCompat) 9433 ? diag::ext_explicit_instantiation_duplicate 9434 : diag::err_explicit_instantiation_duplicate) 9435 << PrevDecl; 9436 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation), 9437 diag::note_previous_explicit_instantiation); 9438 HasNoEffect = true; 9439 return false; 9440 } 9441 } 9442 9443 llvm_unreachable("Missing specialization/instantiation case?"); 9444 } 9445 9446 /// Perform semantic analysis for the given dependent function 9447 /// template specialization. 9448 /// 9449 /// The only possible way to get a dependent function template specialization 9450 /// is with a friend declaration, like so: 9451 /// 9452 /// \code 9453 /// template \<class T> void foo(T); 9454 /// template \<class T> class A { 9455 /// friend void foo<>(T); 9456 /// }; 9457 /// \endcode 9458 /// 9459 /// There really isn't any useful analysis we can do here, so we 9460 /// just store the information. 9461 bool Sema::CheckDependentFunctionTemplateSpecialization( 9462 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs, 9463 LookupResult &Previous) { 9464 // Remove anything from Previous that isn't a function template in 9465 // the correct context. 9466 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext(); 9467 LookupResult::Filter F = Previous.makeFilter(); 9468 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing }; 9469 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates; 9470 while (F.hasNext()) { 9471 NamedDecl *D = F.next()->getUnderlyingDecl(); 9472 if (!isa<FunctionTemplateDecl>(D)) { 9473 F.erase(); 9474 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D)); 9475 continue; 9476 } 9477 9478 if (!FDLookupContext->InEnclosingNamespaceSetOf( 9479 D->getDeclContext()->getRedeclContext())) { 9480 F.erase(); 9481 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D)); 9482 continue; 9483 } 9484 } 9485 F.done(); 9486 9487 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None; 9488 if (Previous.empty()) { 9489 Diag(FD->getLocation(), diag::err_dependent_function_template_spec_no_match) 9490 << IsFriend; 9491 for (auto &P : DiscardedCandidates) 9492 Diag(P.second->getLocation(), 9493 diag::note_dependent_function_template_spec_discard_reason) 9494 << P.first << IsFriend; 9495 return true; 9496 } 9497 9498 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(), 9499 ExplicitTemplateArgs); 9500 return false; 9501 } 9502 9503 /// Perform semantic analysis for the given function template 9504 /// specialization. 9505 /// 9506 /// This routine performs all of the semantic analysis required for an 9507 /// explicit function template specialization. On successful completion, 9508 /// the function declaration \p FD will become a function template 9509 /// specialization. 9510 /// 9511 /// \param FD the function declaration, which will be updated to become a 9512 /// function template specialization. 9513 /// 9514 /// \param ExplicitTemplateArgs the explicitly-provided template arguments, 9515 /// if any. Note that this may be valid info even when 0 arguments are 9516 /// explicitly provided as in, e.g., \c void sort<>(char*, char*); 9517 /// as it anyway contains info on the angle brackets locations. 9518 /// 9519 /// \param Previous the set of declarations that may be specialized by 9520 /// this function specialization. 9521 /// 9522 /// \param QualifiedFriend whether this is a lookup for a qualified friend 9523 /// declaration with no explicit template argument list that might be 9524 /// befriending a function template specialization. 9525 bool Sema::CheckFunctionTemplateSpecialization( 9526 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, 9527 LookupResult &Previous, bool QualifiedFriend) { 9528 // The set of function template specializations that could match this 9529 // explicit function template specialization. 9530 UnresolvedSet<8> Candidates; 9531 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(), 9532 /*ForTakingAddress=*/false); 9533 9534 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8> 9535 ConvertedTemplateArgs; 9536 9537 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext(); 9538 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 9539 I != E; ++I) { 9540 NamedDecl *Ovl = (*I)->getUnderlyingDecl(); 9541 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) { 9542 // Only consider templates found within the same semantic lookup scope as 9543 // FD. 9544 if (!FDLookupContext->InEnclosingNamespaceSetOf( 9545 Ovl->getDeclContext()->getRedeclContext())) 9546 continue; 9547 9548 // When matching a constexpr member function template specialization 9549 // against the primary template, we don't yet know whether the 9550 // specialization has an implicit 'const' (because we don't know whether 9551 // it will be a static member function until we know which template it 9552 // specializes), so adjust it now assuming it specializes this template. 9553 QualType FT = FD->getType(); 9554 if (FD->isConstexpr()) { 9555 CXXMethodDecl *OldMD = 9556 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl()); 9557 if (OldMD && OldMD->isConst()) { 9558 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>(); 9559 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9560 EPI.TypeQuals.addConst(); 9561 FT = Context.getFunctionType(FPT->getReturnType(), 9562 FPT->getParamTypes(), EPI); 9563 } 9564 } 9565 9566 TemplateArgumentListInfo Args; 9567 if (ExplicitTemplateArgs) 9568 Args = *ExplicitTemplateArgs; 9569 9570 // C++ [temp.expl.spec]p11: 9571 // A trailing template-argument can be left unspecified in the 9572 // template-id naming an explicit function template specialization 9573 // provided it can be deduced from the function argument type. 9574 // Perform template argument deduction to determine whether we may be 9575 // specializing this template. 9576 // FIXME: It is somewhat wasteful to build 9577 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 9578 FunctionDecl *Specialization = nullptr; 9579 if (TemplateDeductionResult TDK = DeduceTemplateArguments( 9580 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()), 9581 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, 9582 Info)) { 9583 // Template argument deduction failed; record why it failed, so 9584 // that we can provide nifty diagnostics. 9585 FailedCandidates.addCandidate().set( 9586 I.getPair(), FunTmpl->getTemplatedDecl(), 9587 MakeDeductionFailureInfo(Context, TDK, Info)); 9588 (void)TDK; 9589 continue; 9590 } 9591 9592 // Target attributes are part of the cuda function signature, so 9593 // the deduced template's cuda target must match that of the 9594 // specialization. Given that C++ template deduction does not 9595 // take target attributes into account, we reject candidates 9596 // here that have a different target. 9597 if (LangOpts.CUDA && 9598 IdentifyCUDATarget(Specialization, 9599 /* IgnoreImplicitHDAttr = */ true) != 9600 IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttr = */ true)) { 9601 FailedCandidates.addCandidate().set( 9602 I.getPair(), FunTmpl->getTemplatedDecl(), 9603 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info)); 9604 continue; 9605 } 9606 9607 // Record this candidate. 9608 if (ExplicitTemplateArgs) 9609 ConvertedTemplateArgs[Specialization] = std::move(Args); 9610 Candidates.addDecl(Specialization, I.getAccess()); 9611 } 9612 } 9613 9614 // For a qualified friend declaration (with no explicit marker to indicate 9615 // that a template specialization was intended), note all (template and 9616 // non-template) candidates. 9617 if (QualifiedFriend && Candidates.empty()) { 9618 Diag(FD->getLocation(), diag::err_qualified_friend_no_match) 9619 << FD->getDeclName() << FDLookupContext; 9620 // FIXME: We should form a single candidate list and diagnose all 9621 // candidates at once, to get proper sorting and limiting. 9622 for (auto *OldND : Previous) { 9623 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl())) 9624 NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false); 9625 } 9626 FailedCandidates.NoteCandidates(*this, FD->getLocation()); 9627 return true; 9628 } 9629 9630 // Find the most specialized function template. 9631 UnresolvedSetIterator Result = getMostSpecialized( 9632 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(), 9633 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(), 9634 PDiag(diag::err_function_template_spec_ambiguous) 9635 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr), 9636 PDiag(diag::note_function_template_spec_matched)); 9637 9638 if (Result == Candidates.end()) 9639 return true; 9640 9641 // Ignore access information; it doesn't figure into redeclaration checking. 9642 FunctionDecl *Specialization = cast<FunctionDecl>(*Result); 9643 9644 FunctionTemplateSpecializationInfo *SpecInfo 9645 = Specialization->getTemplateSpecializationInfo(); 9646 assert(SpecInfo && "Function template specialization info missing?"); 9647 9648 // Note: do not overwrite location info if previous template 9649 // specialization kind was explicit. 9650 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind(); 9651 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) { 9652 Specialization->setLocation(FD->getLocation()); 9653 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext()); 9654 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr 9655 // function can differ from the template declaration with respect to 9656 // the constexpr specifier. 9657 // FIXME: We need an update record for this AST mutation. 9658 // FIXME: What if there are multiple such prior declarations (for instance, 9659 // from different modules)? 9660 Specialization->setConstexprKind(FD->getConstexprKind()); 9661 } 9662 9663 // FIXME: Check if the prior specialization has a point of instantiation. 9664 // If so, we have run afoul of . 9665 9666 // If this is a friend declaration, then we're not really declaring 9667 // an explicit specialization. 9668 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None); 9669 9670 // Check the scope of this explicit specialization. 9671 if (!isFriend && 9672 CheckTemplateSpecializationScope(*this, 9673 Specialization->getPrimaryTemplate(), 9674 Specialization, FD->getLocation(), 9675 false)) 9676 return true; 9677 9678 // C++ [temp.expl.spec]p6: 9679 // If a template, a member template or the member of a class template is 9680 // explicitly specialized then that specialization shall be declared 9681 // before the first use of that specialization that would cause an implicit 9682 // instantiation to take place, in every translation unit in which such a 9683 // use occurs; no diagnostic is required. 9684 bool HasNoEffect = false; 9685 if (!isFriend && 9686 CheckSpecializationInstantiationRedecl(FD->getLocation(), 9687 TSK_ExplicitSpecialization, 9688 Specialization, 9689 SpecInfo->getTemplateSpecializationKind(), 9690 SpecInfo->getPointOfInstantiation(), 9691 HasNoEffect)) 9692 return true; 9693 9694 // Mark the prior declaration as an explicit specialization, so that later 9695 // clients know that this is an explicit specialization. 9696 if (!isFriend) { 9697 // Since explicit specializations do not inherit '=delete' from their 9698 // primary function template - check if the 'specialization' that was 9699 // implicitly generated (during template argument deduction for partial 9700 // ordering) from the most specialized of all the function templates that 9701 // 'FD' could have been specializing, has a 'deleted' definition. If so, 9702 // first check that it was implicitly generated during template argument 9703 // deduction by making sure it wasn't referenced, and then reset the deleted 9704 // flag to not-deleted, so that we can inherit that information from 'FD'. 9705 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() && 9706 !Specialization->getCanonicalDecl()->isReferenced()) { 9707 // FIXME: This assert will not hold in the presence of modules. 9708 assert( 9709 Specialization->getCanonicalDecl() == Specialization && 9710 "This must be the only existing declaration of this specialization"); 9711 // FIXME: We need an update record for this AST mutation. 9712 Specialization->setDeletedAsWritten(false); 9713 } 9714 // FIXME: We need an update record for this AST mutation. 9715 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization); 9716 MarkUnusedFileScopedDecl(Specialization); 9717 } 9718 9719 // Turn the given function declaration into a function template 9720 // specialization, with the template arguments from the previous 9721 // specialization. 9722 // Take copies of (semantic and syntactic) template argument lists. 9723 const TemplateArgumentList* TemplArgs = new (Context) 9724 TemplateArgumentList(Specialization->getTemplateSpecializationArgs()); 9725 FD->setFunctionTemplateSpecialization( 9726 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr, 9727 SpecInfo->getTemplateSpecializationKind(), 9728 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr); 9729 9730 // A function template specialization inherits the target attributes 9731 // of its template. (We require the attributes explicitly in the 9732 // code to match, but a template may have implicit attributes by 9733 // virtue e.g. of being constexpr, and it passes these implicit 9734 // attributes on to its specializations.) 9735 if (LangOpts.CUDA) 9736 inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate()); 9737 9738 // The "previous declaration" for this function template specialization is 9739 // the prior function template specialization. 9740 Previous.clear(); 9741 Previous.addDecl(Specialization); 9742 return false; 9743 } 9744 9745 /// Perform semantic analysis for the given non-template member 9746 /// specialization. 9747 /// 9748 /// This routine performs all of the semantic analysis required for an 9749 /// explicit member function specialization. On successful completion, 9750 /// the function declaration \p FD will become a member function 9751 /// specialization. 9752 /// 9753 /// \param Member the member declaration, which will be updated to become a 9754 /// specialization. 9755 /// 9756 /// \param Previous the set of declarations, one of which may be specialized 9757 /// by this function specialization; the set will be modified to contain the 9758 /// redeclared member. 9759 bool 9760 Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) { 9761 assert(!isa<TemplateDecl>(Member) && "Only for non-template members"); 9762 9763 // Try to find the member we are instantiating. 9764 NamedDecl *FoundInstantiation = nullptr; 9765 NamedDecl *Instantiation = nullptr; 9766 NamedDecl *InstantiatedFrom = nullptr; 9767 MemberSpecializationInfo *MSInfo = nullptr; 9768 9769 if (Previous.empty()) { 9770 // Nowhere to look anyway. 9771 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) { 9772 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 9773 I != E; ++I) { 9774 NamedDecl *D = (*I)->getUnderlyingDecl(); 9775 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 9776 QualType Adjusted = Function->getType(); 9777 if (!hasExplicitCallingConv(Adjusted)) 9778 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType()); 9779 // This doesn't handle deduced return types, but both function 9780 // declarations should be undeduced at this point. 9781 if (Context.hasSameType(Adjusted, Method->getType())) { 9782 FoundInstantiation = *I; 9783 Instantiation = Method; 9784 InstantiatedFrom = Method->getInstantiatedFromMemberFunction(); 9785 MSInfo = Method->getMemberSpecializationInfo(); 9786 break; 9787 } 9788 } 9789 } 9790 } else if (isa<VarDecl>(Member)) { 9791 VarDecl *PrevVar; 9792 if (Previous.isSingleResult() && 9793 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl()))) 9794 if (PrevVar->isStaticDataMember()) { 9795 FoundInstantiation = Previous.getRepresentativeDecl(); 9796 Instantiation = PrevVar; 9797 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember(); 9798 MSInfo = PrevVar->getMemberSpecializationInfo(); 9799 } 9800 } else if (isa<RecordDecl>(Member)) { 9801 CXXRecordDecl *PrevRecord; 9802 if (Previous.isSingleResult() && 9803 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) { 9804 FoundInstantiation = Previous.getRepresentativeDecl(); 9805 Instantiation = PrevRecord; 9806 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass(); 9807 MSInfo = PrevRecord->getMemberSpecializationInfo(); 9808 } 9809 } else if (isa<EnumDecl>(Member)) { 9810 EnumDecl *PrevEnum; 9811 if (Previous.isSingleResult() && 9812 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) { 9813 FoundInstantiation = Previous.getRepresentativeDecl(); 9814 Instantiation = PrevEnum; 9815 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum(); 9816 MSInfo = PrevEnum->getMemberSpecializationInfo(); 9817 } 9818 } 9819 9820 if (!Instantiation) { 9821 // There is no previous declaration that matches. Since member 9822 // specializations are always out-of-line, the caller will complain about 9823 // this mismatch later. 9824 return false; 9825 } 9826 9827 // A member specialization in a friend declaration isn't really declaring 9828 // an explicit specialization, just identifying a specific (possibly implicit) 9829 // specialization. Don't change the template specialization kind. 9830 // 9831 // FIXME: Is this really valid? Other compilers reject. 9832 if (Member->getFriendObjectKind() != Decl::FOK_None) { 9833 // Preserve instantiation information. 9834 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) { 9835 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction( 9836 cast<CXXMethodDecl>(InstantiatedFrom), 9837 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind()); 9838 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) { 9839 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass( 9840 cast<CXXRecordDecl>(InstantiatedFrom), 9841 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind()); 9842 } 9843 9844 Previous.clear(); 9845 Previous.addDecl(FoundInstantiation); 9846 return false; 9847 } 9848 9849 // Make sure that this is a specialization of a member. 9850 if (!InstantiatedFrom) { 9851 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated) 9852 << Member; 9853 Diag(Instantiation->getLocation(), diag::note_specialized_decl); 9854 return true; 9855 } 9856 9857 // C++ [temp.expl.spec]p6: 9858 // If a template, a member template or the member of a class template is 9859 // explicitly specialized then that specialization shall be declared 9860 // before the first use of that specialization that would cause an implicit 9861 // instantiation to take place, in every translation unit in which such a 9862 // use occurs; no diagnostic is required. 9863 assert(MSInfo && "Member specialization info missing?"); 9864 9865 bool HasNoEffect = false; 9866 if (CheckSpecializationInstantiationRedecl(Member->getLocation(), 9867 TSK_ExplicitSpecialization, 9868 Instantiation, 9869 MSInfo->getTemplateSpecializationKind(), 9870 MSInfo->getPointOfInstantiation(), 9871 HasNoEffect)) 9872 return true; 9873 9874 // Check the scope of this explicit specialization. 9875 if (CheckTemplateSpecializationScope(*this, 9876 InstantiatedFrom, 9877 Instantiation, Member->getLocation(), 9878 false)) 9879 return true; 9880 9881 // Note that this member specialization is an "instantiation of" the 9882 // corresponding member of the original template. 9883 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) { 9884 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation); 9885 if (InstantiationFunction->getTemplateSpecializationKind() == 9886 TSK_ImplicitInstantiation) { 9887 // Explicit specializations of member functions of class templates do not 9888 // inherit '=delete' from the member function they are specializing. 9889 if (InstantiationFunction->isDeleted()) { 9890 // FIXME: This assert will not hold in the presence of modules. 9891 assert(InstantiationFunction->getCanonicalDecl() == 9892 InstantiationFunction); 9893 // FIXME: We need an update record for this AST mutation. 9894 InstantiationFunction->setDeletedAsWritten(false); 9895 } 9896 } 9897 9898 MemberFunction->setInstantiationOfMemberFunction( 9899 cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization); 9900 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) { 9901 MemberVar->setInstantiationOfStaticDataMember( 9902 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization); 9903 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) { 9904 MemberClass->setInstantiationOfMemberClass( 9905 cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization); 9906 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) { 9907 MemberEnum->setInstantiationOfMemberEnum( 9908 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization); 9909 } else { 9910 llvm_unreachable("unknown member specialization kind"); 9911 } 9912 9913 // Save the caller the trouble of having to figure out which declaration 9914 // this specialization matches. 9915 Previous.clear(); 9916 Previous.addDecl(FoundInstantiation); 9917 return false; 9918 } 9919 9920 /// Complete the explicit specialization of a member of a class template by 9921 /// updating the instantiated member to be marked as an explicit specialization. 9922 /// 9923 /// \param OrigD The member declaration instantiated from the template. 9924 /// \param Loc The location of the explicit specialization of the member. 9925 template<typename DeclT> 9926 static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD, 9927 SourceLocation Loc) { 9928 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) 9929 return; 9930 9931 // FIXME: Inform AST mutation listeners of this AST mutation. 9932 // FIXME: If there are multiple in-class declarations of the member (from 9933 // multiple modules, or a declaration and later definition of a member type), 9934 // should we update all of them? 9935 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization); 9936 OrigD->setLocation(Loc); 9937 } 9938 9939 void Sema::CompleteMemberSpecialization(NamedDecl *Member, 9940 LookupResult &Previous) { 9941 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl()); 9942 if (Instantiation == Member) 9943 return; 9944 9945 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation)) 9946 completeMemberSpecializationImpl(*this, Function, Member->getLocation()); 9947 else if (auto *Var = dyn_cast<VarDecl>(Instantiation)) 9948 completeMemberSpecializationImpl(*this, Var, Member->getLocation()); 9949 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation)) 9950 completeMemberSpecializationImpl(*this, Record, Member->getLocation()); 9951 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation)) 9952 completeMemberSpecializationImpl(*this, Enum, Member->getLocation()); 9953 else 9954 llvm_unreachable("unknown member specialization kind"); 9955 } 9956 9957 /// Check the scope of an explicit instantiation. 9958 /// 9959 /// \returns true if a serious error occurs, false otherwise. 9960 static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D, 9961 SourceLocation InstLoc, 9962 bool WasQualifiedName) { 9963 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext(); 9964 DeclContext *CurContext = S.CurContext->getRedeclContext(); 9965 9966 if (CurContext->isRecord()) { 9967 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class) 9968 << D; 9969 return true; 9970 } 9971 9972 // C++11 [temp.explicit]p3: 9973 // An explicit instantiation shall appear in an enclosing namespace of its 9974 // template. If the name declared in the explicit instantiation is an 9975 // unqualified name, the explicit instantiation shall appear in the 9976 // namespace where its template is declared or, if that namespace is inline 9977 // (7.3.1), any namespace from its enclosing namespace set. 9978 // 9979 // This is DR275, which we do not retroactively apply to C++98/03. 9980 if (WasQualifiedName) { 9981 if (CurContext->Encloses(OrigContext)) 9982 return false; 9983 } else { 9984 if (CurContext->InEnclosingNamespaceSetOf(OrigContext)) 9985 return false; 9986 } 9987 9988 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) { 9989 if (WasQualifiedName) 9990 S.Diag(InstLoc, 9991 S.getLangOpts().CPlusPlus11? 9992 diag::err_explicit_instantiation_out_of_scope : 9993 diag::warn_explicit_instantiation_out_of_scope_0x) 9994 << D << NS; 9995 else 9996 S.Diag(InstLoc, 9997 S.getLangOpts().CPlusPlus11? 9998 diag::err_explicit_instantiation_unqualified_wrong_namespace : 9999 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x) 10000 << D << NS; 10001 } else 10002 S.Diag(InstLoc, 10003 S.getLangOpts().CPlusPlus11? 10004 diag::err_explicit_instantiation_must_be_global : 10005 diag::warn_explicit_instantiation_must_be_global_0x) 10006 << D; 10007 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here); 10008 return false; 10009 } 10010 10011 /// Common checks for whether an explicit instantiation of \p D is valid. 10012 static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D, 10013 SourceLocation InstLoc, 10014 bool WasQualifiedName, 10015 TemplateSpecializationKind TSK) { 10016 // C++ [temp.explicit]p13: 10017 // An explicit instantiation declaration shall not name a specialization of 10018 // a template with internal linkage. 10019 if (TSK == TSK_ExplicitInstantiationDeclaration && 10020 D->getFormalLinkage() == Linkage::Internal) { 10021 S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D; 10022 return true; 10023 } 10024 10025 // C++11 [temp.explicit]p3: [DR 275] 10026 // An explicit instantiation shall appear in an enclosing namespace of its 10027 // template. 10028 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName)) 10029 return true; 10030 10031 return false; 10032 } 10033 10034 /// Determine whether the given scope specifier has a template-id in it. 10035 static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) { 10036 if (!SS.isSet()) 10037 return false; 10038 10039 // C++11 [temp.explicit]p3: 10040 // If the explicit instantiation is for a member function, a member class 10041 // or a static data member of a class template specialization, the name of 10042 // the class template specialization in the qualified-id for the member 10043 // name shall be a simple-template-id. 10044 // 10045 // C++98 has the same restriction, just worded differently. 10046 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS; 10047 NNS = NNS->getPrefix()) 10048 if (const Type *T = NNS->getAsType()) 10049 if (isa<TemplateSpecializationType>(T)) 10050 return true; 10051 10052 return false; 10053 } 10054 10055 /// Make a dllexport or dllimport attr on a class template specialization take 10056 /// effect. 10057 static void dllExportImportClassTemplateSpecialization( 10058 Sema &S, ClassTemplateSpecializationDecl *Def) { 10059 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def)); 10060 assert(A && "dllExportImportClassTemplateSpecialization called " 10061 "on Def without dllexport or dllimport"); 10062 10063 // We reject explicit instantiations in class scope, so there should 10064 // never be any delayed exported classes to worry about. 10065 assert(S.DelayedDllExportClasses.empty() && 10066 "delayed exports present at explicit instantiation"); 10067 S.checkClassLevelDLLAttribute(Def); 10068 10069 // Propagate attribute to base class templates. 10070 for (auto &B : Def->bases()) { 10071 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 10072 B.getType()->getAsCXXRecordDecl())) 10073 S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getBeginLoc()); 10074 } 10075 10076 S.referenceDLLExportedClassMethods(); 10077 } 10078 10079 // Explicit instantiation of a class template specialization 10080 DeclResult Sema::ActOnExplicitInstantiation( 10081 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, 10082 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, 10083 TemplateTy TemplateD, SourceLocation TemplateNameLoc, 10084 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn, 10085 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) { 10086 // Find the class template we're specializing 10087 TemplateName Name = TemplateD.get(); 10088 TemplateDecl *TD = Name.getAsTemplateDecl(); 10089 // Check that the specialization uses the same tag kind as the 10090 // original template. 10091 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 10092 assert(Kind != TagTypeKind::Enum && 10093 "Invalid enum tag in class template explicit instantiation!"); 10094 10095 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD); 10096 10097 if (!ClassTemplate) { 10098 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind); 10099 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) 10100 << TD << NTK << llvm::to_underlying(Kind); 10101 Diag(TD->getLocation(), diag::note_previous_use); 10102 return true; 10103 } 10104 10105 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), 10106 Kind, /*isDefinition*/false, KWLoc, 10107 ClassTemplate->getIdentifier())) { 10108 Diag(KWLoc, diag::err_use_with_wrong_tag) 10109 << ClassTemplate 10110 << FixItHint::CreateReplacement(KWLoc, 10111 ClassTemplate->getTemplatedDecl()->getKindName()); 10112 Diag(ClassTemplate->getTemplatedDecl()->getLocation(), 10113 diag::note_previous_use); 10114 Kind = ClassTemplate->getTemplatedDecl()->getTagKind(); 10115 } 10116 10117 // C++0x [temp.explicit]p2: 10118 // There are two forms of explicit instantiation: an explicit instantiation 10119 // definition and an explicit instantiation declaration. An explicit 10120 // instantiation declaration begins with the extern keyword. [...] 10121 TemplateSpecializationKind TSK = ExternLoc.isInvalid() 10122 ? TSK_ExplicitInstantiationDefinition 10123 : TSK_ExplicitInstantiationDeclaration; 10124 10125 if (TSK == TSK_ExplicitInstantiationDeclaration && 10126 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) { 10127 // Check for dllexport class template instantiation declarations, 10128 // except for MinGW mode. 10129 for (const ParsedAttr &AL : Attr) { 10130 if (AL.getKind() == ParsedAttr::AT_DLLExport) { 10131 Diag(ExternLoc, 10132 diag::warn_attribute_dllexport_explicit_instantiation_decl); 10133 Diag(AL.getLoc(), diag::note_attribute); 10134 break; 10135 } 10136 } 10137 10138 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) { 10139 Diag(ExternLoc, 10140 diag::warn_attribute_dllexport_explicit_instantiation_decl); 10141 Diag(A->getLocation(), diag::note_attribute); 10142 } 10143 } 10144 10145 // In MSVC mode, dllimported explicit instantiation definitions are treated as 10146 // instantiation declarations for most purposes. 10147 bool DLLImportExplicitInstantiationDef = false; 10148 if (TSK == TSK_ExplicitInstantiationDefinition && 10149 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 10150 // Check for dllimport class template instantiation definitions. 10151 bool DLLImport = 10152 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>(); 10153 for (const ParsedAttr &AL : Attr) { 10154 if (AL.getKind() == ParsedAttr::AT_DLLImport) 10155 DLLImport = true; 10156 if (AL.getKind() == ParsedAttr::AT_DLLExport) { 10157 // dllexport trumps dllimport here. 10158 DLLImport = false; 10159 break; 10160 } 10161 } 10162 if (DLLImport) { 10163 TSK = TSK_ExplicitInstantiationDeclaration; 10164 DLLImportExplicitInstantiationDef = true; 10165 } 10166 } 10167 10168 // Translate the parser's template argument list in our AST format. 10169 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); 10170 translateTemplateArguments(TemplateArgsIn, TemplateArgs); 10171 10172 // Check that the template argument list is well-formed for this 10173 // template. 10174 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted; 10175 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs, 10176 false, SugaredConverted, CanonicalConverted, 10177 /*UpdateArgsWithConversions=*/true)) 10178 return true; 10179 10180 // Find the class template specialization declaration that 10181 // corresponds to these arguments. 10182 void *InsertPos = nullptr; 10183 ClassTemplateSpecializationDecl *PrevDecl = 10184 ClassTemplate->findSpecialization(CanonicalConverted, InsertPos); 10185 10186 TemplateSpecializationKind PrevDecl_TSK 10187 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared; 10188 10189 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr && 10190 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) { 10191 // Check for dllexport class template instantiation definitions in MinGW 10192 // mode, if a previous declaration of the instantiation was seen. 10193 for (const ParsedAttr &AL : Attr) { 10194 if (AL.getKind() == ParsedAttr::AT_DLLExport) { 10195 Diag(AL.getLoc(), 10196 diag::warn_attribute_dllexport_explicit_instantiation_def); 10197 break; 10198 } 10199 } 10200 } 10201 10202 if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc, 10203 SS.isSet(), TSK)) 10204 return true; 10205 10206 ClassTemplateSpecializationDecl *Specialization = nullptr; 10207 10208 bool HasNoEffect = false; 10209 if (PrevDecl) { 10210 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK, 10211 PrevDecl, PrevDecl_TSK, 10212 PrevDecl->getPointOfInstantiation(), 10213 HasNoEffect)) 10214 return PrevDecl; 10215 10216 // Even though HasNoEffect == true means that this explicit instantiation 10217 // has no effect on semantics, we go on to put its syntax in the AST. 10218 10219 if (PrevDecl_TSK == TSK_ImplicitInstantiation || 10220 PrevDecl_TSK == TSK_Undeclared) { 10221 // Since the only prior class template specialization with these 10222 // arguments was referenced but not declared, reuse that 10223 // declaration node as our own, updating the source location 10224 // for the template name to reflect our new declaration. 10225 // (Other source locations will be updated later.) 10226 Specialization = PrevDecl; 10227 Specialization->setLocation(TemplateNameLoc); 10228 PrevDecl = nullptr; 10229 } 10230 10231 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration && 10232 DLLImportExplicitInstantiationDef) { 10233 // The new specialization might add a dllimport attribute. 10234 HasNoEffect = false; 10235 } 10236 } 10237 10238 if (!Specialization) { 10239 // Create a new class template specialization declaration node for 10240 // this explicit specialization. 10241 Specialization = ClassTemplateSpecializationDecl::Create( 10242 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc, 10243 ClassTemplate, CanonicalConverted, PrevDecl); 10244 SetNestedNameSpecifier(*this, Specialization, SS); 10245 10246 // A MSInheritanceAttr attached to the previous declaration must be 10247 // propagated to the new node prior to instantiation. 10248 if (PrevDecl) { 10249 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) { 10250 auto *Clone = A->clone(getASTContext()); 10251 Clone->setInherited(true); 10252 Specialization->addAttr(Clone); 10253 Consumer.AssignInheritanceModel(Specialization); 10254 } 10255 } 10256 10257 if (!HasNoEffect && !PrevDecl) { 10258 // Insert the new specialization. 10259 ClassTemplate->AddSpecialization(Specialization, InsertPos); 10260 } 10261 } 10262 10263 // Build the fully-sugared type for this explicit instantiation as 10264 // the user wrote in the explicit instantiation itself. This means 10265 // that we'll pretty-print the type retrieved from the 10266 // specialization's declaration the way that the user actually wrote 10267 // the explicit instantiation, rather than formatting the name based 10268 // on the "canonical" representation used to store the template 10269 // arguments in the specialization. 10270 TypeSourceInfo *WrittenTy 10271 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc, 10272 TemplateArgs, 10273 Context.getTypeDeclType(Specialization)); 10274 Specialization->setTypeAsWritten(WrittenTy); 10275 10276 // Set source locations for keywords. 10277 Specialization->setExternLoc(ExternLoc); 10278 Specialization->setTemplateKeywordLoc(TemplateLoc); 10279 Specialization->setBraceRange(SourceRange()); 10280 10281 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>(); 10282 ProcessDeclAttributeList(S, Specialization, Attr); 10283 10284 // Add the explicit instantiation into its lexical context. However, 10285 // since explicit instantiations are never found by name lookup, we 10286 // just put it into the declaration context directly. 10287 Specialization->setLexicalDeclContext(CurContext); 10288 CurContext->addDecl(Specialization); 10289 10290 // Syntax is now OK, so return if it has no other effect on semantics. 10291 if (HasNoEffect) { 10292 // Set the template specialization kind. 10293 Specialization->setTemplateSpecializationKind(TSK); 10294 return Specialization; 10295 } 10296 10297 // C++ [temp.explicit]p3: 10298 // A definition of a class template or class member template 10299 // shall be in scope at the point of the explicit instantiation of 10300 // the class template or class member template. 10301 // 10302 // This check comes when we actually try to perform the 10303 // instantiation. 10304 ClassTemplateSpecializationDecl *Def 10305 = cast_or_null<ClassTemplateSpecializationDecl>( 10306 Specialization->getDefinition()); 10307 if (!Def) 10308 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK); 10309 else if (TSK == TSK_ExplicitInstantiationDefinition) { 10310 MarkVTableUsed(TemplateNameLoc, Specialization, true); 10311 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation()); 10312 } 10313 10314 // Instantiate the members of this class template specialization. 10315 Def = cast_or_null<ClassTemplateSpecializationDecl>( 10316 Specialization->getDefinition()); 10317 if (Def) { 10318 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind(); 10319 // Fix a TSK_ExplicitInstantiationDeclaration followed by a 10320 // TSK_ExplicitInstantiationDefinition 10321 if (Old_TSK == TSK_ExplicitInstantiationDeclaration && 10322 (TSK == TSK_ExplicitInstantiationDefinition || 10323 DLLImportExplicitInstantiationDef)) { 10324 // FIXME: Need to notify the ASTMutationListener that we did this. 10325 Def->setTemplateSpecializationKind(TSK); 10326 10327 if (!getDLLAttr(Def) && getDLLAttr(Specialization) && 10328 (Context.getTargetInfo().shouldDLLImportComdatSymbols() && 10329 !Context.getTargetInfo().getTriple().isPS())) { 10330 // An explicit instantiation definition can add a dll attribute to a 10331 // template with a previous instantiation declaration. MinGW doesn't 10332 // allow this. 10333 auto *A = cast<InheritableAttr>( 10334 getDLLAttr(Specialization)->clone(getASTContext())); 10335 A->setInherited(true); 10336 Def->addAttr(A); 10337 dllExportImportClassTemplateSpecialization(*this, Def); 10338 } 10339 } 10340 10341 // Fix a TSK_ImplicitInstantiation followed by a 10342 // TSK_ExplicitInstantiationDefinition 10343 bool NewlyDLLExported = 10344 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>(); 10345 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported && 10346 (Context.getTargetInfo().shouldDLLImportComdatSymbols() && 10347 !Context.getTargetInfo().getTriple().isPS())) { 10348 // An explicit instantiation definition can add a dll attribute to a 10349 // template with a previous implicit instantiation. MinGW doesn't allow 10350 // this. We limit clang to only adding dllexport, to avoid potentially 10351 // strange codegen behavior. For example, if we extend this conditional 10352 // to dllimport, and we have a source file calling a method on an 10353 // implicitly instantiated template class instance and then declaring a 10354 // dllimport explicit instantiation definition for the same template 10355 // class, the codegen for the method call will not respect the dllimport, 10356 // while it will with cl. The Def will already have the DLL attribute, 10357 // since the Def and Specialization will be the same in the case of 10358 // Old_TSK == TSK_ImplicitInstantiation, and we already added the 10359 // attribute to the Specialization; we just need to make it take effect. 10360 assert(Def == Specialization && 10361 "Def and Specialization should match for implicit instantiation"); 10362 dllExportImportClassTemplateSpecialization(*this, Def); 10363 } 10364 10365 // In MinGW mode, export the template instantiation if the declaration 10366 // was marked dllexport. 10367 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration && 10368 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() && 10369 PrevDecl->hasAttr<DLLExportAttr>()) { 10370 dllExportImportClassTemplateSpecialization(*this, Def); 10371 } 10372 10373 // Set the template specialization kind. Make sure it is set before 10374 // instantiating the members which will trigger ASTConsumer callbacks. 10375 Specialization->setTemplateSpecializationKind(TSK); 10376 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK); 10377 } else { 10378 10379 // Set the template specialization kind. 10380 Specialization->setTemplateSpecializationKind(TSK); 10381 } 10382 10383 return Specialization; 10384 } 10385 10386 // Explicit instantiation of a member class of a class template. 10387 DeclResult 10388 Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, 10389 SourceLocation TemplateLoc, unsigned TagSpec, 10390 SourceLocation KWLoc, CXXScopeSpec &SS, 10391 IdentifierInfo *Name, SourceLocation NameLoc, 10392 const ParsedAttributesView &Attr) { 10393 10394 bool Owned = false; 10395 bool IsDependent = false; 10396 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference, KWLoc, SS, Name, 10397 NameLoc, Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(), 10398 MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(), 10399 false, TypeResult(), /*IsTypeSpecifier*/ false, 10400 /*IsTemplateParamOrArg*/ false, /*OOK=*/OOK_Outside).get(); 10401 assert(!IsDependent && "explicit instantiation of dependent name not yet handled"); 10402 10403 if (!TagD) 10404 return true; 10405 10406 TagDecl *Tag = cast<TagDecl>(TagD); 10407 assert(!Tag->isEnum() && "shouldn't see enumerations here"); 10408 10409 if (Tag->isInvalidDecl()) 10410 return true; 10411 10412 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag); 10413 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass(); 10414 if (!Pattern) { 10415 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type) 10416 << Context.getTypeDeclType(Record); 10417 Diag(Record->getLocation(), diag::note_nontemplate_decl_here); 10418 return true; 10419 } 10420 10421 // C++0x [temp.explicit]p2: 10422 // If the explicit instantiation is for a class or member class, the 10423 // elaborated-type-specifier in the declaration shall include a 10424 // simple-template-id. 10425 // 10426 // C++98 has the same restriction, just worded differently. 10427 if (!ScopeSpecifierHasTemplateId(SS)) 10428 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id) 10429 << Record << SS.getRange(); 10430 10431 // C++0x [temp.explicit]p2: 10432 // There are two forms of explicit instantiation: an explicit instantiation 10433 // definition and an explicit instantiation declaration. An explicit 10434 // instantiation declaration begins with the extern keyword. [...] 10435 TemplateSpecializationKind TSK 10436 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition 10437 : TSK_ExplicitInstantiationDeclaration; 10438 10439 CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK); 10440 10441 // Verify that it is okay to explicitly instantiate here. 10442 CXXRecordDecl *PrevDecl 10443 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl()); 10444 if (!PrevDecl && Record->getDefinition()) 10445 PrevDecl = Record; 10446 if (PrevDecl) { 10447 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo(); 10448 bool HasNoEffect = false; 10449 assert(MSInfo && "No member specialization information?"); 10450 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK, 10451 PrevDecl, 10452 MSInfo->getTemplateSpecializationKind(), 10453 MSInfo->getPointOfInstantiation(), 10454 HasNoEffect)) 10455 return true; 10456 if (HasNoEffect) 10457 return TagD; 10458 } 10459 10460 CXXRecordDecl *RecordDef 10461 = cast_or_null<CXXRecordDecl>(Record->getDefinition()); 10462 if (!RecordDef) { 10463 // C++ [temp.explicit]p3: 10464 // A definition of a member class of a class template shall be in scope 10465 // at the point of an explicit instantiation of the member class. 10466 CXXRecordDecl *Def 10467 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition()); 10468 if (!Def) { 10469 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member) 10470 << 0 << Record->getDeclName() << Record->getDeclContext(); 10471 Diag(Pattern->getLocation(), diag::note_forward_declaration) 10472 << Pattern; 10473 return true; 10474 } else { 10475 if (InstantiateClass(NameLoc, Record, Def, 10476 getTemplateInstantiationArgs(Record), 10477 TSK)) 10478 return true; 10479 10480 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition()); 10481 if (!RecordDef) 10482 return true; 10483 } 10484 } 10485 10486 // Instantiate all of the members of the class. 10487 InstantiateClassMembers(NameLoc, RecordDef, 10488 getTemplateInstantiationArgs(Record), TSK); 10489 10490 if (TSK == TSK_ExplicitInstantiationDefinition) 10491 MarkVTableUsed(NameLoc, RecordDef, true); 10492 10493 // FIXME: We don't have any representation for explicit instantiations of 10494 // member classes. Such a representation is not needed for compilation, but it 10495 // should be available for clients that want to see all of the declarations in 10496 // the source code. 10497 return TagD; 10498 } 10499 10500 DeclResult Sema::ActOnExplicitInstantiation(Scope *S, 10501 SourceLocation ExternLoc, 10502 SourceLocation TemplateLoc, 10503 Declarator &D) { 10504 // Explicit instantiations always require a name. 10505 // TODO: check if/when DNInfo should replace Name. 10506 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 10507 DeclarationName Name = NameInfo.getName(); 10508 if (!Name) { 10509 if (!D.isInvalidType()) 10510 Diag(D.getDeclSpec().getBeginLoc(), 10511 diag::err_explicit_instantiation_requires_name) 10512 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 10513 10514 return true; 10515 } 10516 10517 // The scope passed in may not be a decl scope. Zip up the scope tree until 10518 // we find one that is. 10519 while ((S->getFlags() & Scope::DeclScope) == 0 || 10520 (S->getFlags() & Scope::TemplateParamScope) != 0) 10521 S = S->getParent(); 10522 10523 // Determine the type of the declaration. 10524 TypeSourceInfo *T = GetTypeForDeclarator(D, S); 10525 QualType R = T->getType(); 10526 if (R.isNull()) 10527 return true; 10528 10529 // C++ [dcl.stc]p1: 10530 // A storage-class-specifier shall not be specified in [...] an explicit 10531 // instantiation (14.7.2) directive. 10532 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 10533 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef) 10534 << Name; 10535 return true; 10536 } else if (D.getDeclSpec().getStorageClassSpec() 10537 != DeclSpec::SCS_unspecified) { 10538 // Complain about then remove the storage class specifier. 10539 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class) 10540 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 10541 10542 D.getMutableDeclSpec().ClearStorageClassSpecs(); 10543 } 10544 10545 // C++0x [temp.explicit]p1: 10546 // [...] An explicit instantiation of a function template shall not use the 10547 // inline or constexpr specifiers. 10548 // Presumably, this also applies to member functions of class templates as 10549 // well. 10550 if (D.getDeclSpec().isInlineSpecified()) 10551 Diag(D.getDeclSpec().getInlineSpecLoc(), 10552 getLangOpts().CPlusPlus11 ? 10553 diag::err_explicit_instantiation_inline : 10554 diag::warn_explicit_instantiation_inline_0x) 10555 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 10556 if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType()) 10557 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is 10558 // not already specified. 10559 Diag(D.getDeclSpec().getConstexprSpecLoc(), 10560 diag::err_explicit_instantiation_constexpr); 10561 10562 // A deduction guide is not on the list of entities that can be explicitly 10563 // instantiated. 10564 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 10565 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized) 10566 << /*explicit instantiation*/ 0; 10567 return true; 10568 } 10569 10570 // C++0x [temp.explicit]p2: 10571 // There are two forms of explicit instantiation: an explicit instantiation 10572 // definition and an explicit instantiation declaration. An explicit 10573 // instantiation declaration begins with the extern keyword. [...] 10574 TemplateSpecializationKind TSK 10575 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition 10576 : TSK_ExplicitInstantiationDeclaration; 10577 10578 LookupResult Previous(*this, NameInfo, LookupOrdinaryName); 10579 LookupParsedName(Previous, S, &D.getCXXScopeSpec()); 10580 10581 if (!R->isFunctionType()) { 10582 // C++ [temp.explicit]p1: 10583 // A [...] static data member of a class template can be explicitly 10584 // instantiated from the member definition associated with its class 10585 // template. 10586 // C++1y [temp.explicit]p1: 10587 // A [...] variable [...] template specialization can be explicitly 10588 // instantiated from its template. 10589 if (Previous.isAmbiguous()) 10590 return true; 10591 10592 VarDecl *Prev = Previous.getAsSingle<VarDecl>(); 10593 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>(); 10594 10595 if (!PrevTemplate) { 10596 if (!Prev || !Prev->isStaticDataMember()) { 10597 // We expect to see a static data member here. 10598 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known) 10599 << Name; 10600 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end(); 10601 P != PEnd; ++P) 10602 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here); 10603 return true; 10604 } 10605 10606 if (!Prev->getInstantiatedFromStaticDataMember()) { 10607 // FIXME: Check for explicit specialization? 10608 Diag(D.getIdentifierLoc(), 10609 diag::err_explicit_instantiation_data_member_not_instantiated) 10610 << Prev; 10611 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here); 10612 // FIXME: Can we provide a note showing where this was declared? 10613 return true; 10614 } 10615 } else { 10616 // Explicitly instantiate a variable template. 10617 10618 // C++1y [dcl.spec.auto]p6: 10619 // ... A program that uses auto or decltype(auto) in a context not 10620 // explicitly allowed in this section is ill-formed. 10621 // 10622 // This includes auto-typed variable template instantiations. 10623 if (R->isUndeducedType()) { 10624 Diag(T->getTypeLoc().getBeginLoc(), 10625 diag::err_auto_not_allowed_var_inst); 10626 return true; 10627 } 10628 10629 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 10630 // C++1y [temp.explicit]p3: 10631 // If the explicit instantiation is for a variable, the unqualified-id 10632 // in the declaration shall be a template-id. 10633 Diag(D.getIdentifierLoc(), 10634 diag::err_explicit_instantiation_without_template_id) 10635 << PrevTemplate; 10636 Diag(PrevTemplate->getLocation(), 10637 diag::note_explicit_instantiation_here); 10638 return true; 10639 } 10640 10641 // Translate the parser's template argument list into our AST format. 10642 TemplateArgumentListInfo TemplateArgs = 10643 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId); 10644 10645 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc, 10646 D.getIdentifierLoc(), TemplateArgs); 10647 if (Res.isInvalid()) 10648 return true; 10649 10650 if (!Res.isUsable()) { 10651 // We somehow specified dependent template arguments in an explicit 10652 // instantiation. This should probably only happen during error 10653 // recovery. 10654 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent); 10655 return true; 10656 } 10657 10658 // Ignore access control bits, we don't need them for redeclaration 10659 // checking. 10660 Prev = cast<VarDecl>(Res.get()); 10661 } 10662 10663 // C++0x [temp.explicit]p2: 10664 // If the explicit instantiation is for a member function, a member class 10665 // or a static data member of a class template specialization, the name of 10666 // the class template specialization in the qualified-id for the member 10667 // name shall be a simple-template-id. 10668 // 10669 // C++98 has the same restriction, just worded differently. 10670 // 10671 // This does not apply to variable template specializations, where the 10672 // template-id is in the unqualified-id instead. 10673 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate) 10674 Diag(D.getIdentifierLoc(), 10675 diag::ext_explicit_instantiation_without_qualified_id) 10676 << Prev << D.getCXXScopeSpec().getRange(); 10677 10678 CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK); 10679 10680 // Verify that it is okay to explicitly instantiate here. 10681 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind(); 10682 SourceLocation POI = Prev->getPointOfInstantiation(); 10683 bool HasNoEffect = false; 10684 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev, 10685 PrevTSK, POI, HasNoEffect)) 10686 return true; 10687 10688 if (!HasNoEffect) { 10689 // Instantiate static data member or variable template. 10690 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc()); 10691 // Merge attributes. 10692 ProcessDeclAttributeList(S, Prev, D.getDeclSpec().getAttributes()); 10693 if (TSK == TSK_ExplicitInstantiationDefinition) 10694 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev); 10695 } 10696 10697 // Check the new variable specialization against the parsed input. 10698 if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) { 10699 Diag(T->getTypeLoc().getBeginLoc(), 10700 diag::err_invalid_var_template_spec_type) 10701 << 0 << PrevTemplate << R << Prev->getType(); 10702 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here) 10703 << 2 << PrevTemplate->getDeclName(); 10704 return true; 10705 } 10706 10707 // FIXME: Create an ExplicitInstantiation node? 10708 return (Decl*) nullptr; 10709 } 10710 10711 // If the declarator is a template-id, translate the parser's template 10712 // argument list into our AST format. 10713 bool HasExplicitTemplateArgs = false; 10714 TemplateArgumentListInfo TemplateArgs; 10715 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 10716 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId); 10717 HasExplicitTemplateArgs = true; 10718 } 10719 10720 // C++ [temp.explicit]p1: 10721 // A [...] function [...] can be explicitly instantiated from its template. 10722 // A member function [...] of a class template can be explicitly 10723 // instantiated from the member definition associated with its class 10724 // template. 10725 UnresolvedSet<8> TemplateMatches; 10726 FunctionDecl *NonTemplateMatch = nullptr; 10727 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc()); 10728 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end(); 10729 P != PEnd; ++P) { 10730 NamedDecl *Prev = *P; 10731 if (!HasExplicitTemplateArgs) { 10732 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) { 10733 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(), 10734 /*AdjustExceptionSpec*/true); 10735 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) { 10736 if (Method->getPrimaryTemplate()) { 10737 TemplateMatches.addDecl(Method, P.getAccess()); 10738 } else { 10739 // FIXME: Can this assert ever happen? Needs a test. 10740 assert(!NonTemplateMatch && "Multiple NonTemplateMatches"); 10741 NonTemplateMatch = Method; 10742 } 10743 } 10744 } 10745 } 10746 10747 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev); 10748 if (!FunTmpl) 10749 continue; 10750 10751 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10752 FunctionDecl *Specialization = nullptr; 10753 if (TemplateDeductionResult TDK 10754 = DeduceTemplateArguments(FunTmpl, 10755 (HasExplicitTemplateArgs ? &TemplateArgs 10756 : nullptr), 10757 R, Specialization, Info)) { 10758 // Keep track of almost-matches. 10759 FailedCandidates.addCandidate() 10760 .set(P.getPair(), FunTmpl->getTemplatedDecl(), 10761 MakeDeductionFailureInfo(Context, TDK, Info)); 10762 (void)TDK; 10763 continue; 10764 } 10765 10766 // Target attributes are part of the cuda function signature, so 10767 // the cuda target of the instantiated function must match that of its 10768 // template. Given that C++ template deduction does not take 10769 // target attributes into account, we reject candidates here that 10770 // have a different target. 10771 if (LangOpts.CUDA && 10772 IdentifyCUDATarget(Specialization, 10773 /* IgnoreImplicitHDAttr = */ true) != 10774 IdentifyCUDATarget(D.getDeclSpec().getAttributes())) { 10775 FailedCandidates.addCandidate().set( 10776 P.getPair(), FunTmpl->getTemplatedDecl(), 10777 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info)); 10778 continue; 10779 } 10780 10781 TemplateMatches.addDecl(Specialization, P.getAccess()); 10782 } 10783 10784 FunctionDecl *Specialization = NonTemplateMatch; 10785 if (!Specialization) { 10786 // Find the most specialized function template specialization. 10787 UnresolvedSetIterator Result = getMostSpecialized( 10788 TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates, 10789 D.getIdentifierLoc(), 10790 PDiag(diag::err_explicit_instantiation_not_known) << Name, 10791 PDiag(diag::err_explicit_instantiation_ambiguous) << Name, 10792 PDiag(diag::note_explicit_instantiation_candidate)); 10793 10794 if (Result == TemplateMatches.end()) 10795 return true; 10796 10797 // Ignore access control bits, we don't need them for redeclaration checking. 10798 Specialization = cast<FunctionDecl>(*Result); 10799 } 10800 10801 // C++11 [except.spec]p4 10802 // In an explicit instantiation an exception-specification may be specified, 10803 // but is not required. 10804 // If an exception-specification is specified in an explicit instantiation 10805 // directive, it shall be compatible with the exception-specifications of 10806 // other declarations of that function. 10807 if (auto *FPT = R->getAs<FunctionProtoType>()) 10808 if (FPT->hasExceptionSpec()) { 10809 unsigned DiagID = 10810 diag::err_mismatched_exception_spec_explicit_instantiation; 10811 if (getLangOpts().MicrosoftExt) 10812 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation; 10813 bool Result = CheckEquivalentExceptionSpec( 10814 PDiag(DiagID) << Specialization->getType(), 10815 PDiag(diag::note_explicit_instantiation_here), 10816 Specialization->getType()->getAs<FunctionProtoType>(), 10817 Specialization->getLocation(), FPT, D.getBeginLoc()); 10818 // In Microsoft mode, mismatching exception specifications just cause a 10819 // warning. 10820 if (!getLangOpts().MicrosoftExt && Result) 10821 return true; 10822 } 10823 10824 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) { 10825 Diag(D.getIdentifierLoc(), 10826 diag::err_explicit_instantiation_member_function_not_instantiated) 10827 << Specialization 10828 << (Specialization->getTemplateSpecializationKind() == 10829 TSK_ExplicitSpecialization); 10830 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here); 10831 return true; 10832 } 10833 10834 FunctionDecl *PrevDecl = Specialization->getPreviousDecl(); 10835 if (!PrevDecl && Specialization->isThisDeclarationADefinition()) 10836 PrevDecl = Specialization; 10837 10838 if (PrevDecl) { 10839 bool HasNoEffect = false; 10840 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, 10841 PrevDecl, 10842 PrevDecl->getTemplateSpecializationKind(), 10843 PrevDecl->getPointOfInstantiation(), 10844 HasNoEffect)) 10845 return true; 10846 10847 // FIXME: We may still want to build some representation of this 10848 // explicit specialization. 10849 if (HasNoEffect) 10850 return (Decl*) nullptr; 10851 } 10852 10853 // HACK: libc++ has a bug where it attempts to explicitly instantiate the 10854 // functions 10855 // valarray<size_t>::valarray(size_t) and 10856 // valarray<size_t>::~valarray() 10857 // that it declared to have internal linkage with the internal_linkage 10858 // attribute. Ignore the explicit instantiation declaration in this case. 10859 if (Specialization->hasAttr<InternalLinkageAttr>() && 10860 TSK == TSK_ExplicitInstantiationDeclaration) { 10861 if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext())) 10862 if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") && 10863 RD->isInStdNamespace()) 10864 return (Decl*) nullptr; 10865 } 10866 10867 ProcessDeclAttributeList(S, Specialization, D.getDeclSpec().getAttributes()); 10868 10869 // In MSVC mode, dllimported explicit instantiation definitions are treated as 10870 // instantiation declarations. 10871 if (TSK == TSK_ExplicitInstantiationDefinition && 10872 Specialization->hasAttr<DLLImportAttr>() && 10873 Context.getTargetInfo().getCXXABI().isMicrosoft()) 10874 TSK = TSK_ExplicitInstantiationDeclaration; 10875 10876 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc()); 10877 10878 if (Specialization->isDefined()) { 10879 // Let the ASTConsumer know that this function has been explicitly 10880 // instantiated now, and its linkage might have changed. 10881 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization)); 10882 } else if (TSK == TSK_ExplicitInstantiationDefinition) 10883 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization); 10884 10885 // C++0x [temp.explicit]p2: 10886 // If the explicit instantiation is for a member function, a member class 10887 // or a static data member of a class template specialization, the name of 10888 // the class template specialization in the qualified-id for the member 10889 // name shall be a simple-template-id. 10890 // 10891 // C++98 has the same restriction, just worded differently. 10892 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate(); 10893 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl && 10894 D.getCXXScopeSpec().isSet() && 10895 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec())) 10896 Diag(D.getIdentifierLoc(), 10897 diag::ext_explicit_instantiation_without_qualified_id) 10898 << Specialization << D.getCXXScopeSpec().getRange(); 10899 10900 CheckExplicitInstantiation( 10901 *this, 10902 FunTmpl ? (NamedDecl *)FunTmpl 10903 : Specialization->getInstantiatedFromMemberFunction(), 10904 D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK); 10905 10906 // FIXME: Create some kind of ExplicitInstantiationDecl here. 10907 return (Decl*) nullptr; 10908 } 10909 10910 TypeResult 10911 Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 10912 const CXXScopeSpec &SS, IdentifierInfo *Name, 10913 SourceLocation TagLoc, SourceLocation NameLoc) { 10914 // This has to hold, because SS is expected to be defined. 10915 assert(Name && "Expected a name in a dependent tag"); 10916 10917 NestedNameSpecifier *NNS = SS.getScopeRep(); 10918 if (!NNS) 10919 return true; 10920 10921 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 10922 10923 if (TUK == TUK_Declaration || TUK == TUK_Definition) { 10924 Diag(NameLoc, diag::err_dependent_tag_decl) 10925 << (TUK == TUK_Definition) << llvm::to_underlying(Kind) 10926 << SS.getRange(); 10927 return true; 10928 } 10929 10930 // Create the resulting type. 10931 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 10932 QualType Result = Context.getDependentNameType(Kwd, NNS, Name); 10933 10934 // Create type-source location information for this type. 10935 TypeLocBuilder TLB; 10936 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result); 10937 TL.setElaboratedKeywordLoc(TagLoc); 10938 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 10939 TL.setNameLoc(NameLoc); 10940 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result)); 10941 } 10942 10943 TypeResult Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, 10944 const CXXScopeSpec &SS, 10945 const IdentifierInfo &II, 10946 SourceLocation IdLoc, 10947 ImplicitTypenameContext IsImplicitTypename) { 10948 if (SS.isInvalid()) 10949 return true; 10950 10951 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent()) 10952 Diag(TypenameLoc, 10953 getLangOpts().CPlusPlus11 ? 10954 diag::warn_cxx98_compat_typename_outside_of_template : 10955 diag::ext_typename_outside_of_template) 10956 << FixItHint::CreateRemoval(TypenameLoc); 10957 10958 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 10959 TypeSourceInfo *TSI = nullptr; 10960 QualType T = 10961 CheckTypenameType((TypenameLoc.isValid() || 10962 IsImplicitTypename == ImplicitTypenameContext::Yes) 10963 ? ElaboratedTypeKeyword::Typename 10964 : ElaboratedTypeKeyword::None, 10965 TypenameLoc, QualifierLoc, II, IdLoc, &TSI, 10966 /*DeducedTSTContext=*/true); 10967 if (T.isNull()) 10968 return true; 10969 return CreateParsedType(T, TSI); 10970 } 10971 10972 TypeResult 10973 Sema::ActOnTypenameType(Scope *S, 10974 SourceLocation TypenameLoc, 10975 const CXXScopeSpec &SS, 10976 SourceLocation TemplateKWLoc, 10977 TemplateTy TemplateIn, 10978 IdentifierInfo *TemplateII, 10979 SourceLocation TemplateIILoc, 10980 SourceLocation LAngleLoc, 10981 ASTTemplateArgsPtr TemplateArgsIn, 10982 SourceLocation RAngleLoc) { 10983 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent()) 10984 Diag(TypenameLoc, 10985 getLangOpts().CPlusPlus11 ? 10986 diag::warn_cxx98_compat_typename_outside_of_template : 10987 diag::ext_typename_outside_of_template) 10988 << FixItHint::CreateRemoval(TypenameLoc); 10989 10990 // Strangely, non-type results are not ignored by this lookup, so the 10991 // program is ill-formed if it finds an injected-class-name. 10992 if (TypenameLoc.isValid()) { 10993 auto *LookupRD = 10994 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false)); 10995 if (LookupRD && LookupRD->getIdentifier() == TemplateII) { 10996 Diag(TemplateIILoc, 10997 diag::ext_out_of_line_qualified_id_type_names_constructor) 10998 << TemplateII << 0 /*injected-class-name used as template name*/ 10999 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/); 11000 } 11001 } 11002 11003 // Translate the parser's template argument list in our AST format. 11004 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); 11005 translateTemplateArguments(TemplateArgsIn, TemplateArgs); 11006 11007 TemplateName Template = TemplateIn.get(); 11008 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) { 11009 // Construct a dependent template specialization type. 11010 assert(DTN && "dependent template has non-dependent name?"); 11011 assert(DTN->getQualifier() == SS.getScopeRep()); 11012 QualType T = Context.getDependentTemplateSpecializationType( 11013 ElaboratedTypeKeyword::Typename, DTN->getQualifier(), 11014 DTN->getIdentifier(), TemplateArgs.arguments()); 11015 11016 // Create source-location information for this type. 11017 TypeLocBuilder Builder; 11018 DependentTemplateSpecializationTypeLoc SpecTL 11019 = Builder.push<DependentTemplateSpecializationTypeLoc>(T); 11020 SpecTL.setElaboratedKeywordLoc(TypenameLoc); 11021 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context)); 11022 SpecTL.setTemplateKeywordLoc(TemplateKWLoc); 11023 SpecTL.setTemplateNameLoc(TemplateIILoc); 11024 SpecTL.setLAngleLoc(LAngleLoc); 11025 SpecTL.setRAngleLoc(RAngleLoc); 11026 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 11027 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo()); 11028 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 11029 } 11030 11031 QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs); 11032 if (T.isNull()) 11033 return true; 11034 11035 // Provide source-location information for the template specialization type. 11036 TypeLocBuilder Builder; 11037 TemplateSpecializationTypeLoc SpecTL 11038 = Builder.push<TemplateSpecializationTypeLoc>(T); 11039 SpecTL.setTemplateKeywordLoc(TemplateKWLoc); 11040 SpecTL.setTemplateNameLoc(TemplateIILoc); 11041 SpecTL.setLAngleLoc(LAngleLoc); 11042 SpecTL.setRAngleLoc(RAngleLoc); 11043 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 11044 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo()); 11045 11046 T = Context.getElaboratedType(ElaboratedTypeKeyword::Typename, 11047 SS.getScopeRep(), T); 11048 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T); 11049 TL.setElaboratedKeywordLoc(TypenameLoc); 11050 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 11051 11052 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T); 11053 return CreateParsedType(T, TSI); 11054 } 11055 11056 11057 /// Determine whether this failed name lookup should be treated as being 11058 /// disabled by a usage of std::enable_if. 11059 static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II, 11060 SourceRange &CondRange, Expr *&Cond) { 11061 // We must be looking for a ::type... 11062 if (!II.isStr("type")) 11063 return false; 11064 11065 // ... within an explicitly-written template specialization... 11066 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType()) 11067 return false; 11068 TypeLoc EnableIfTy = NNS.getTypeLoc(); 11069 TemplateSpecializationTypeLoc EnableIfTSTLoc = 11070 EnableIfTy.getAs<TemplateSpecializationTypeLoc>(); 11071 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0) 11072 return false; 11073 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr(); 11074 11075 // ... which names a complete class template declaration... 11076 const TemplateDecl *EnableIfDecl = 11077 EnableIfTST->getTemplateName().getAsTemplateDecl(); 11078 if (!EnableIfDecl || EnableIfTST->isIncompleteType()) 11079 return false; 11080 11081 // ... called "enable_if". 11082 const IdentifierInfo *EnableIfII = 11083 EnableIfDecl->getDeclName().getAsIdentifierInfo(); 11084 if (!EnableIfII || !EnableIfII->isStr("enable_if")) 11085 return false; 11086 11087 // Assume the first template argument is the condition. 11088 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange(); 11089 11090 // Dig out the condition. 11091 Cond = nullptr; 11092 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind() 11093 != TemplateArgument::Expression) 11094 return true; 11095 11096 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression(); 11097 11098 // Ignore Boolean literals; they add no value. 11099 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts())) 11100 Cond = nullptr; 11101 11102 return true; 11103 } 11104 11105 QualType 11106 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword, 11107 SourceLocation KeywordLoc, 11108 NestedNameSpecifierLoc QualifierLoc, 11109 const IdentifierInfo &II, 11110 SourceLocation IILoc, 11111 TypeSourceInfo **TSI, 11112 bool DeducedTSTContext) { 11113 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc, 11114 DeducedTSTContext); 11115 if (T.isNull()) 11116 return QualType(); 11117 11118 *TSI = Context.CreateTypeSourceInfo(T); 11119 if (isa<DependentNameType>(T)) { 11120 DependentNameTypeLoc TL = 11121 (*TSI)->getTypeLoc().castAs<DependentNameTypeLoc>(); 11122 TL.setElaboratedKeywordLoc(KeywordLoc); 11123 TL.setQualifierLoc(QualifierLoc); 11124 TL.setNameLoc(IILoc); 11125 } else { 11126 ElaboratedTypeLoc TL = (*TSI)->getTypeLoc().castAs<ElaboratedTypeLoc>(); 11127 TL.setElaboratedKeywordLoc(KeywordLoc); 11128 TL.setQualifierLoc(QualifierLoc); 11129 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IILoc); 11130 } 11131 return T; 11132 } 11133 11134 /// Build the type that describes a C++ typename specifier, 11135 /// e.g., "typename T::type". 11136 QualType 11137 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword, 11138 SourceLocation KeywordLoc, 11139 NestedNameSpecifierLoc QualifierLoc, 11140 const IdentifierInfo &II, 11141 SourceLocation IILoc, bool DeducedTSTContext) { 11142 CXXScopeSpec SS; 11143 SS.Adopt(QualifierLoc); 11144 11145 DeclContext *Ctx = nullptr; 11146 if (QualifierLoc) { 11147 Ctx = computeDeclContext(SS); 11148 if (!Ctx) { 11149 // If the nested-name-specifier is dependent and couldn't be 11150 // resolved to a type, build a typename type. 11151 assert(QualifierLoc.getNestedNameSpecifier()->isDependent()); 11152 return Context.getDependentNameType(Keyword, 11153 QualifierLoc.getNestedNameSpecifier(), 11154 &II); 11155 } 11156 11157 // If the nested-name-specifier refers to the current instantiation, 11158 // the "typename" keyword itself is superfluous. In C++03, the 11159 // program is actually ill-formed. However, DR 382 (in C++0x CD1) 11160 // allows such extraneous "typename" keywords, and we retroactively 11161 // apply this DR to C++03 code with only a warning. In any case we continue. 11162 11163 if (RequireCompleteDeclContext(SS, Ctx)) 11164 return QualType(); 11165 } 11166 11167 DeclarationName Name(&II); 11168 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName); 11169 if (Ctx) 11170 LookupQualifiedName(Result, Ctx, SS); 11171 else 11172 LookupName(Result, CurScope); 11173 unsigned DiagID = 0; 11174 Decl *Referenced = nullptr; 11175 switch (Result.getResultKind()) { 11176 case LookupResult::NotFound: { 11177 // If we're looking up 'type' within a template named 'enable_if', produce 11178 // a more specific diagnostic. 11179 SourceRange CondRange; 11180 Expr *Cond = nullptr; 11181 if (Ctx && isEnableIf(QualifierLoc, II, CondRange, Cond)) { 11182 // If we have a condition, narrow it down to the specific failed 11183 // condition. 11184 if (Cond) { 11185 Expr *FailedCond; 11186 std::string FailedDescription; 11187 std::tie(FailedCond, FailedDescription) = 11188 findFailedBooleanCondition(Cond); 11189 11190 Diag(FailedCond->getExprLoc(), 11191 diag::err_typename_nested_not_found_requirement) 11192 << FailedDescription 11193 << FailedCond->getSourceRange(); 11194 return QualType(); 11195 } 11196 11197 Diag(CondRange.getBegin(), 11198 diag::err_typename_nested_not_found_enable_if) 11199 << Ctx << CondRange; 11200 return QualType(); 11201 } 11202 11203 DiagID = Ctx ? diag::err_typename_nested_not_found 11204 : diag::err_unknown_typename; 11205 break; 11206 } 11207 11208 case LookupResult::FoundUnresolvedValue: { 11209 // We found a using declaration that is a value. Most likely, the using 11210 // declaration itself is meant to have the 'typename' keyword. 11211 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(), 11212 IILoc); 11213 Diag(IILoc, diag::err_typename_refers_to_using_value_decl) 11214 << Name << Ctx << FullRange; 11215 if (UnresolvedUsingValueDecl *Using 11216 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){ 11217 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc(); 11218 Diag(Loc, diag::note_using_value_decl_missing_typename) 11219 << FixItHint::CreateInsertion(Loc, "typename "); 11220 } 11221 } 11222 // Fall through to create a dependent typename type, from which we can recover 11223 // better. 11224 [[fallthrough]]; 11225 11226 case LookupResult::NotFoundInCurrentInstantiation: 11227 // Okay, it's a member of an unknown instantiation. 11228 return Context.getDependentNameType(Keyword, 11229 QualifierLoc.getNestedNameSpecifier(), 11230 &II); 11231 11232 case LookupResult::Found: 11233 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) { 11234 // C++ [class.qual]p2: 11235 // In a lookup in which function names are not ignored and the 11236 // nested-name-specifier nominates a class C, if the name specified 11237 // after the nested-name-specifier, when looked up in C, is the 11238 // injected-class-name of C [...] then the name is instead considered 11239 // to name the constructor of class C. 11240 // 11241 // Unlike in an elaborated-type-specifier, function names are not ignored 11242 // in typename-specifier lookup. However, they are ignored in all the 11243 // contexts where we form a typename type with no keyword (that is, in 11244 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers). 11245 // 11246 // FIXME: That's not strictly true: mem-initializer-id lookup does not 11247 // ignore functions, but that appears to be an oversight. 11248 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx); 11249 auto *FoundRD = dyn_cast<CXXRecordDecl>(Type); 11250 if (Keyword == ElaboratedTypeKeyword::Typename && LookupRD && FoundRD && 11251 FoundRD->isInjectedClassName() && 11252 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 11253 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor) 11254 << &II << 1 << 0 /*'typename' keyword used*/; 11255 11256 // We found a type. Build an ElaboratedType, since the 11257 // typename-specifier was just sugar. 11258 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 11259 return Context.getElaboratedType(Keyword, 11260 QualifierLoc.getNestedNameSpecifier(), 11261 Context.getTypeDeclType(Type)); 11262 } 11263 11264 // C++ [dcl.type.simple]p2: 11265 // A type-specifier of the form 11266 // typename[opt] nested-name-specifier[opt] template-name 11267 // is a placeholder for a deduced class type [...]. 11268 if (getLangOpts().CPlusPlus17) { 11269 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) { 11270 if (!DeducedTSTContext) { 11271 QualType T(QualifierLoc 11272 ? QualifierLoc.getNestedNameSpecifier()->getAsType() 11273 : nullptr, 0); 11274 if (!T.isNull()) 11275 Diag(IILoc, diag::err_dependent_deduced_tst) 11276 << (int)getTemplateNameKindForDiagnostics(TemplateName(TD)) << T; 11277 else 11278 Diag(IILoc, diag::err_deduced_tst) 11279 << (int)getTemplateNameKindForDiagnostics(TemplateName(TD)); 11280 NoteTemplateLocation(*TD); 11281 return QualType(); 11282 } 11283 return Context.getElaboratedType( 11284 Keyword, QualifierLoc.getNestedNameSpecifier(), 11285 Context.getDeducedTemplateSpecializationType(TemplateName(TD), 11286 QualType(), false)); 11287 } 11288 } 11289 11290 DiagID = Ctx ? diag::err_typename_nested_not_type 11291 : diag::err_typename_not_type; 11292 Referenced = Result.getFoundDecl(); 11293 break; 11294 11295 case LookupResult::FoundOverloaded: 11296 DiagID = Ctx ? diag::err_typename_nested_not_type 11297 : diag::err_typename_not_type; 11298 Referenced = *Result.begin(); 11299 break; 11300 11301 case LookupResult::Ambiguous: 11302 return QualType(); 11303 } 11304 11305 // If we get here, it's because name lookup did not find a 11306 // type. Emit an appropriate diagnostic and return an error. 11307 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(), 11308 IILoc); 11309 if (Ctx) 11310 Diag(IILoc, DiagID) << FullRange << Name << Ctx; 11311 else 11312 Diag(IILoc, DiagID) << FullRange << Name; 11313 if (Referenced) 11314 Diag(Referenced->getLocation(), 11315 Ctx ? diag::note_typename_member_refers_here 11316 : diag::note_typename_refers_here) 11317 << Name; 11318 return QualType(); 11319 } 11320 11321 namespace { 11322 // See Sema::RebuildTypeInCurrentInstantiation 11323 class CurrentInstantiationRebuilder 11324 : public TreeTransform<CurrentInstantiationRebuilder> { 11325 SourceLocation Loc; 11326 DeclarationName Entity; 11327 11328 public: 11329 typedef TreeTransform<CurrentInstantiationRebuilder> inherited; 11330 11331 CurrentInstantiationRebuilder(Sema &SemaRef, 11332 SourceLocation Loc, 11333 DeclarationName Entity) 11334 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef), 11335 Loc(Loc), Entity(Entity) { } 11336 11337 /// Determine whether the given type \p T has already been 11338 /// transformed. 11339 /// 11340 /// For the purposes of type reconstruction, a type has already been 11341 /// transformed if it is NULL or if it is not dependent. 11342 bool AlreadyTransformed(QualType T) { 11343 return T.isNull() || !T->isInstantiationDependentType(); 11344 } 11345 11346 /// Returns the location of the entity whose type is being 11347 /// rebuilt. 11348 SourceLocation getBaseLocation() { return Loc; } 11349 11350 /// Returns the name of the entity whose type is being rebuilt. 11351 DeclarationName getBaseEntity() { return Entity; } 11352 11353 /// Sets the "base" location and entity when that 11354 /// information is known based on another transformation. 11355 void setBase(SourceLocation Loc, DeclarationName Entity) { 11356 this->Loc = Loc; 11357 this->Entity = Entity; 11358 } 11359 11360 ExprResult TransformLambdaExpr(LambdaExpr *E) { 11361 // Lambdas never need to be transformed. 11362 return E; 11363 } 11364 }; 11365 } // end anonymous namespace 11366 11367 /// Rebuilds a type within the context of the current instantiation. 11368 /// 11369 /// The type \p T is part of the type of an out-of-line member definition of 11370 /// a class template (or class template partial specialization) that was parsed 11371 /// and constructed before we entered the scope of the class template (or 11372 /// partial specialization thereof). This routine will rebuild that type now 11373 /// that we have entered the declarator's scope, which may produce different 11374 /// canonical types, e.g., 11375 /// 11376 /// \code 11377 /// template<typename T> 11378 /// struct X { 11379 /// typedef T* pointer; 11380 /// pointer data(); 11381 /// }; 11382 /// 11383 /// template<typename T> 11384 /// typename X<T>::pointer X<T>::data() { ... } 11385 /// \endcode 11386 /// 11387 /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType, 11388 /// since we do not know that we can look into X<T> when we parsed the type. 11389 /// This function will rebuild the type, performing the lookup of "pointer" 11390 /// in X<T> and returning an ElaboratedType whose canonical type is the same 11391 /// as the canonical type of T*, allowing the return types of the out-of-line 11392 /// definition and the declaration to match. 11393 TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, 11394 SourceLocation Loc, 11395 DeclarationName Name) { 11396 if (!T || !T->getType()->isInstantiationDependentType()) 11397 return T; 11398 11399 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name); 11400 return Rebuilder.TransformType(T); 11401 } 11402 11403 ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) { 11404 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(), 11405 DeclarationName()); 11406 return Rebuilder.TransformExpr(E); 11407 } 11408 11409 bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) { 11410 if (SS.isInvalid()) 11411 return true; 11412 11413 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 11414 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(), 11415 DeclarationName()); 11416 NestedNameSpecifierLoc Rebuilt 11417 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc); 11418 if (!Rebuilt) 11419 return true; 11420 11421 SS.Adopt(Rebuilt); 11422 return false; 11423 } 11424 11425 /// Rebuild the template parameters now that we know we're in a current 11426 /// instantiation. 11427 bool Sema::RebuildTemplateParamsInCurrentInstantiation( 11428 TemplateParameterList *Params) { 11429 for (unsigned I = 0, N = Params->size(); I != N; ++I) { 11430 Decl *Param = Params->getParam(I); 11431 11432 // There is nothing to rebuild in a type parameter. 11433 if (isa<TemplateTypeParmDecl>(Param)) 11434 continue; 11435 11436 // Rebuild the template parameter list of a template template parameter. 11437 if (TemplateTemplateParmDecl *TTP 11438 = dyn_cast<TemplateTemplateParmDecl>(Param)) { 11439 if (RebuildTemplateParamsInCurrentInstantiation( 11440 TTP->getTemplateParameters())) 11441 return true; 11442 11443 continue; 11444 } 11445 11446 // Rebuild the type of a non-type template parameter. 11447 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param); 11448 TypeSourceInfo *NewTSI 11449 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(), 11450 NTTP->getLocation(), 11451 NTTP->getDeclName()); 11452 if (!NewTSI) 11453 return true; 11454 11455 if (NewTSI->getType()->isUndeducedType()) { 11456 // C++17 [temp.dep.expr]p3: 11457 // An id-expression is type-dependent if it contains 11458 // - an identifier associated by name lookup with a non-type 11459 // template-parameter declared with a type that contains a 11460 // placeholder type (7.1.7.4), 11461 NewTSI = SubstAutoTypeSourceInfoDependent(NewTSI); 11462 } 11463 11464 if (NewTSI != NTTP->getTypeSourceInfo()) { 11465 NTTP->setTypeSourceInfo(NewTSI); 11466 NTTP->setType(NewTSI->getType()); 11467 } 11468 } 11469 11470 return false; 11471 } 11472 11473 /// Produces a formatted string that describes the binding of 11474 /// template parameters to template arguments. 11475 std::string 11476 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params, 11477 const TemplateArgumentList &Args) { 11478 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size()); 11479 } 11480 11481 std::string 11482 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params, 11483 const TemplateArgument *Args, 11484 unsigned NumArgs) { 11485 SmallString<128> Str; 11486 llvm::raw_svector_ostream Out(Str); 11487 11488 if (!Params || Params->size() == 0 || NumArgs == 0) 11489 return std::string(); 11490 11491 for (unsigned I = 0, N = Params->size(); I != N; ++I) { 11492 if (I >= NumArgs) 11493 break; 11494 11495 if (I == 0) 11496 Out << "[with "; 11497 else 11498 Out << ", "; 11499 11500 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) { 11501 Out << Id->getName(); 11502 } else { 11503 Out << '$' << I; 11504 } 11505 11506 Out << " = "; 11507 Args[I].print(getPrintingPolicy(), Out, 11508 TemplateParameterList::shouldIncludeTypeForArgument( 11509 getPrintingPolicy(), Params, I)); 11510 } 11511 11512 Out << ']'; 11513 return std::string(Out.str()); 11514 } 11515 11516 void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, 11517 CachedTokens &Toks) { 11518 if (!FD) 11519 return; 11520 11521 auto LPT = std::make_unique<LateParsedTemplate>(); 11522 11523 // Take tokens to avoid allocations 11524 LPT->Toks.swap(Toks); 11525 LPT->D = FnD; 11526 LPT->FPO = getCurFPFeatures(); 11527 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT))); 11528 11529 FD->setLateTemplateParsed(true); 11530 } 11531 11532 void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) { 11533 if (!FD) 11534 return; 11535 FD->setLateTemplateParsed(false); 11536 } 11537 11538 bool Sema::IsInsideALocalClassWithinATemplateFunction() { 11539 DeclContext *DC = CurContext; 11540 11541 while (DC) { 11542 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) { 11543 const FunctionDecl *FD = RD->isLocalClass(); 11544 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate); 11545 } else if (DC->isTranslationUnit() || DC->isNamespace()) 11546 return false; 11547 11548 DC = DC->getParent(); 11549 } 11550 return false; 11551 } 11552 11553 namespace { 11554 /// Walk the path from which a declaration was instantiated, and check 11555 /// that every explicit specialization along that path is visible. This enforces 11556 /// C++ [temp.expl.spec]/6: 11557 /// 11558 /// If a template, a member template or a member of a class template is 11559 /// explicitly specialized then that specialization shall be declared before 11560 /// the first use of that specialization that would cause an implicit 11561 /// instantiation to take place, in every translation unit in which such a 11562 /// use occurs; no diagnostic is required. 11563 /// 11564 /// and also C++ [temp.class.spec]/1: 11565 /// 11566 /// A partial specialization shall be declared before the first use of a 11567 /// class template specialization that would make use of the partial 11568 /// specialization as the result of an implicit or explicit instantiation 11569 /// in every translation unit in which such a use occurs; no diagnostic is 11570 /// required. 11571 class ExplicitSpecializationVisibilityChecker { 11572 Sema &S; 11573 SourceLocation Loc; 11574 llvm::SmallVector<Module *, 8> Modules; 11575 Sema::AcceptableKind Kind; 11576 11577 public: 11578 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc, 11579 Sema::AcceptableKind Kind) 11580 : S(S), Loc(Loc), Kind(Kind) {} 11581 11582 void check(NamedDecl *ND) { 11583 if (auto *FD = dyn_cast<FunctionDecl>(ND)) 11584 return checkImpl(FD); 11585 if (auto *RD = dyn_cast<CXXRecordDecl>(ND)) 11586 return checkImpl(RD); 11587 if (auto *VD = dyn_cast<VarDecl>(ND)) 11588 return checkImpl(VD); 11589 if (auto *ED = dyn_cast<EnumDecl>(ND)) 11590 return checkImpl(ED); 11591 } 11592 11593 private: 11594 void diagnose(NamedDecl *D, bool IsPartialSpec) { 11595 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization 11596 : Sema::MissingImportKind::ExplicitSpecialization; 11597 const bool Recover = true; 11598 11599 // If we got a custom set of modules (because only a subset of the 11600 // declarations are interesting), use them, otherwise let 11601 // diagnoseMissingImport intelligently pick some. 11602 if (Modules.empty()) 11603 S.diagnoseMissingImport(Loc, D, Kind, Recover); 11604 else 11605 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover); 11606 } 11607 11608 bool CheckMemberSpecialization(const NamedDecl *D) { 11609 return Kind == Sema::AcceptableKind::Visible 11610 ? S.hasVisibleMemberSpecialization(D) 11611 : S.hasReachableMemberSpecialization(D); 11612 } 11613 11614 bool CheckExplicitSpecialization(const NamedDecl *D) { 11615 return Kind == Sema::AcceptableKind::Visible 11616 ? S.hasVisibleExplicitSpecialization(D) 11617 : S.hasReachableExplicitSpecialization(D); 11618 } 11619 11620 bool CheckDeclaration(const NamedDecl *D) { 11621 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D) 11622 : S.hasReachableDeclaration(D); 11623 } 11624 11625 // Check a specific declaration. There are three problematic cases: 11626 // 11627 // 1) The declaration is an explicit specialization of a template 11628 // specialization. 11629 // 2) The declaration is an explicit specialization of a member of an 11630 // templated class. 11631 // 3) The declaration is an instantiation of a template, and that template 11632 // is an explicit specialization of a member of a templated class. 11633 // 11634 // We don't need to go any deeper than that, as the instantiation of the 11635 // surrounding class / etc is not triggered by whatever triggered this 11636 // instantiation, and thus should be checked elsewhere. 11637 template<typename SpecDecl> 11638 void checkImpl(SpecDecl *Spec) { 11639 bool IsHiddenExplicitSpecialization = false; 11640 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) { 11641 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo() 11642 ? !CheckMemberSpecialization(Spec) 11643 : !CheckExplicitSpecialization(Spec); 11644 } else { 11645 checkInstantiated(Spec); 11646 } 11647 11648 if (IsHiddenExplicitSpecialization) 11649 diagnose(Spec->getMostRecentDecl(), false); 11650 } 11651 11652 void checkInstantiated(FunctionDecl *FD) { 11653 if (auto *TD = FD->getPrimaryTemplate()) 11654 checkTemplate(TD); 11655 } 11656 11657 void checkInstantiated(CXXRecordDecl *RD) { 11658 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD); 11659 if (!SD) 11660 return; 11661 11662 auto From = SD->getSpecializedTemplateOrPartial(); 11663 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>()) 11664 checkTemplate(TD); 11665 else if (auto *TD = 11666 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) { 11667 if (!CheckDeclaration(TD)) 11668 diagnose(TD, true); 11669 checkTemplate(TD); 11670 } 11671 } 11672 11673 void checkInstantiated(VarDecl *RD) { 11674 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD); 11675 if (!SD) 11676 return; 11677 11678 auto From = SD->getSpecializedTemplateOrPartial(); 11679 if (auto *TD = From.dyn_cast<VarTemplateDecl *>()) 11680 checkTemplate(TD); 11681 else if (auto *TD = 11682 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) { 11683 if (!CheckDeclaration(TD)) 11684 diagnose(TD, true); 11685 checkTemplate(TD); 11686 } 11687 } 11688 11689 void checkInstantiated(EnumDecl *FD) {} 11690 11691 template<typename TemplDecl> 11692 void checkTemplate(TemplDecl *TD) { 11693 if (TD->isMemberSpecialization()) { 11694 if (!CheckMemberSpecialization(TD)) 11695 diagnose(TD->getMostRecentDecl(), false); 11696 } 11697 } 11698 }; 11699 } // end anonymous namespace 11700 11701 void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) { 11702 if (!getLangOpts().Modules) 11703 return; 11704 11705 ExplicitSpecializationVisibilityChecker(*this, Loc, 11706 Sema::AcceptableKind::Visible) 11707 .check(Spec); 11708 } 11709 11710 void Sema::checkSpecializationReachability(SourceLocation Loc, 11711 NamedDecl *Spec) { 11712 if (!getLangOpts().CPlusPlusModules) 11713 return checkSpecializationVisibility(Loc, Spec); 11714 11715 ExplicitSpecializationVisibilityChecker(*this, Loc, 11716 Sema::AcceptableKind::Reachable) 11717 .check(Spec); 11718 } 11719 11720 /// Returns the top most location responsible for the definition of \p N. 11721 /// If \p N is a a template specialization, this is the location 11722 /// of the top of the instantiation stack. 11723 /// Otherwise, the location of \p N is returned. 11724 SourceLocation Sema::getTopMostPointOfInstantiation(const NamedDecl *N) const { 11725 if (!getLangOpts().CPlusPlus || CodeSynthesisContexts.empty()) 11726 return N->getLocation(); 11727 if (const auto *FD = dyn_cast<FunctionDecl>(N)) { 11728 if (!FD->isFunctionTemplateSpecialization()) 11729 return FD->getLocation(); 11730 } else if (!isa<ClassTemplateSpecializationDecl, 11731 VarTemplateSpecializationDecl>(N)) { 11732 return N->getLocation(); 11733 } 11734 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) { 11735 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid()) 11736 continue; 11737 return CSC.PointOfInstantiation; 11738 } 11739 return N->getLocation(); 11740 } 11741