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