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