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