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