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