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