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