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