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