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