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