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