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