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