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