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