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