1 //===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //===----------------------------------------------------------------------===//
9 // This file implements semantic analysis for C++ templates.
10 //===----------------------------------------------------------------------===//
12 #include "TreeTransform.h"
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/DeclFriend.h"
16 #include "clang/AST/DeclTemplate.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/RecursiveASTVisitor.h"
20 #include "clang/AST/TypeVisitor.h"
21 #include "clang/Basic/Builtins.h"
22 #include "clang/Basic/LangOptions.h"
23 #include "clang/Basic/PartialDiagnostic.h"
24 #include "clang/Basic/TargetInfo.h"
25 #include "clang/Sema/DeclSpec.h"
26 #include "clang/Sema/Lookup.h"
27 #include "clang/Sema/ParsedTemplate.h"
28 #include "clang/Sema/Scope.h"
29 #include "clang/Sema/SemaInternal.h"
30 #include "clang/Sema/Template.h"
31 #include "clang/Sema/TemplateDeduction.h"
32 #include "llvm/ADT/SmallBitVector.h"
33 #include "llvm/ADT/SmallString.h"
34 #include "llvm/ADT/StringExtras.h"
37 using namespace clang;
40 // Exported for use by Parser.
42 clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
44 if (!N) return SourceRange();
45 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
49 /// \brief [temp.constr.decl]p2: A template's associated constraints are
50 /// defined as a single constraint-expression derived from the introduced
51 /// constraint-expressions [ ... ].
53 /// \param Params The template parameter list and optional requires-clause.
55 /// \param FD The underlying templated function declaration for a function
57 static Expr *formAssociatedConstraints(TemplateParameterList *Params,
61 static Expr *clang::formAssociatedConstraints(TemplateParameterList *Params,
63 // FIXME: Concepts: collect additional introduced constraint-expressions
64 assert(!FD && "Cannot collect constraints from function declaration yet.");
65 return Params->getRequiresClause();
68 /// \brief Determine whether the declaration found is acceptable as the name
69 /// of a template and, if so, return that template declaration. Otherwise,
71 static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
73 bool AllowFunctionTemplates) {
74 NamedDecl *D = Orig->getUnderlyingDecl();
76 if (isa<TemplateDecl>(D)) {
77 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
83 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
84 // C++ [temp.local]p1:
85 // Like normal (non-template) classes, class templates have an
86 // injected-class-name (Clause 9). The injected-class-name
87 // can be used with or without a template-argument-list. When
88 // it is used without a template-argument-list, it is
89 // equivalent to the injected-class-name followed by the
90 // template-parameters of the class template enclosed in
91 // <>. When it is used with a template-argument-list, it
92 // refers to the specified class template specialization,
93 // which could be the current specialization or another
95 if (Record->isInjectedClassName()) {
96 Record = cast<CXXRecordDecl>(Record->getDeclContext());
97 if (Record->getDescribedClassTemplate())
98 return Record->getDescribedClassTemplate();
100 if (ClassTemplateSpecializationDecl *Spec
101 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
102 return Spec->getSpecializedTemplate();
111 void Sema::FilterAcceptableTemplateNames(LookupResult &R,
112 bool AllowFunctionTemplates) {
113 // The set of class templates we've already seen.
114 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
115 LookupResult::Filter filter = R.makeFilter();
116 while (filter.hasNext()) {
117 NamedDecl *Orig = filter.next();
118 NamedDecl *Repl = isAcceptableTemplateName(Context, Orig,
119 AllowFunctionTemplates);
122 else if (Repl != Orig) {
124 // C++ [temp.local]p3:
125 // A lookup that finds an injected-class-name (10.2) can result in an
126 // ambiguity in certain cases (for example, if it is found in more than
127 // one base class). If all of the injected-class-names that are found
128 // refer to specializations of the same class template, and if the name
129 // is used as a template-name, the reference refers to the class
130 // template itself and not a specialization thereof, and is not
132 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
133 if (!ClassTemplates.insert(ClassTmpl).second) {
138 // FIXME: we promote access to public here as a workaround to
139 // the fact that LookupResult doesn't let us remember that we
140 // found this template through a particular injected class name,
141 // which means we end up doing nasty things to the invariants.
142 // Pretending that access is public is *much* safer.
143 filter.replace(Repl, AS_public);
149 bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
150 bool AllowFunctionTemplates) {
151 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
152 if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
158 TemplateNameKind Sema::isTemplateName(Scope *S,
160 bool hasTemplateKeyword,
162 ParsedType ObjectTypePtr,
163 bool EnteringContext,
164 TemplateTy &TemplateResult,
165 bool &MemberOfUnknownSpecialization) {
166 assert(getLangOpts().CPlusPlus && "No template names in C!");
168 DeclarationName TName;
169 MemberOfUnknownSpecialization = false;
171 switch (Name.getKind()) {
172 case UnqualifiedId::IK_Identifier:
173 TName = DeclarationName(Name.Identifier);
176 case UnqualifiedId::IK_OperatorFunctionId:
177 TName = Context.DeclarationNames.getCXXOperatorName(
178 Name.OperatorFunctionId.Operator);
181 case UnqualifiedId::IK_LiteralOperatorId:
182 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
186 return TNK_Non_template;
189 QualType ObjectType = ObjectTypePtr.get();
191 LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
192 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
193 MemberOfUnknownSpecialization);
194 if (R.empty()) return TNK_Non_template;
195 if (R.isAmbiguous()) {
196 // Suppress diagnostics; we'll redo this lookup later.
197 R.suppressDiagnostics();
199 // FIXME: we might have ambiguous templates, in which case we
200 // should at least parse them properly!
201 return TNK_Non_template;
204 TemplateName Template;
205 TemplateNameKind TemplateKind;
207 unsigned ResultCount = R.end() - R.begin();
208 if (ResultCount > 1) {
209 // We assume that we'll preserve the qualifier from a function
210 // template name in other ways.
211 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
212 TemplateKind = TNK_Function_template;
214 // We'll do this lookup again later.
215 R.suppressDiagnostics();
217 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
219 if (SS.isSet() && !SS.isInvalid()) {
220 NestedNameSpecifier *Qualifier = SS.getScopeRep();
221 Template = Context.getQualifiedTemplateName(Qualifier,
222 hasTemplateKeyword, TD);
224 Template = TemplateName(TD);
227 if (isa<FunctionTemplateDecl>(TD)) {
228 TemplateKind = TNK_Function_template;
230 // We'll do this lookup again later.
231 R.suppressDiagnostics();
233 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
234 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
235 isa<BuiltinTemplateDecl>(TD));
237 isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template;
241 TemplateResult = TemplateTy::make(Template);
245 bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
246 SourceLocation NameLoc,
247 ParsedTemplateTy *Template) {
249 bool MemberOfUnknownSpecialization = false;
251 // We could use redeclaration lookup here, but we don't need to: the
252 // syntactic form of a deduction guide is enough to identify it even
253 // if we can't look up the template name at all.
254 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
255 LookupTemplateName(R, S, SS, /*ObjectType*/QualType(),
256 /*EnteringContext*/false, MemberOfUnknownSpecialization);
258 if (R.empty()) return false;
259 if (R.isAmbiguous()) {
260 // FIXME: Diagnose an ambiguity if we find at least one template.
261 R.suppressDiagnostics();
265 // We only treat template-names that name type templates as valid deduction
267 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
268 if (!TD || !getAsTypeTemplateDecl(TD))
272 *Template = TemplateTy::make(TemplateName(TD));
276 bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
277 SourceLocation IILoc,
279 const CXXScopeSpec *SS,
280 TemplateTy &SuggestedTemplate,
281 TemplateNameKind &SuggestedKind) {
282 // We can't recover unless there's a dependent scope specifier preceding the
284 // FIXME: Typo correction?
285 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
286 computeDeclContext(*SS))
289 // The code is missing a 'template' keyword prior to the dependent template
291 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
292 Diag(IILoc, diag::err_template_kw_missing)
293 << Qualifier << II.getName()
294 << FixItHint::CreateInsertion(IILoc, "template ");
296 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
297 SuggestedKind = TNK_Dependent_template_name;
301 void Sema::LookupTemplateName(LookupResult &Found,
302 Scope *S, CXXScopeSpec &SS,
304 bool EnteringContext,
305 bool &MemberOfUnknownSpecialization) {
306 // Determine where to perform name lookup
307 MemberOfUnknownSpecialization = false;
308 DeclContext *LookupCtx = nullptr;
309 bool isDependent = false;
310 if (!ObjectType.isNull()) {
311 // This nested-name-specifier occurs in a member access expression, e.g.,
312 // x->B::f, and we are looking into the type of the object.
313 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
314 LookupCtx = computeDeclContext(ObjectType);
315 isDependent = ObjectType->isDependentType();
316 assert((isDependent || !ObjectType->isIncompleteType() ||
317 ObjectType->castAs<TagType>()->isBeingDefined()) &&
318 "Caller should have completed object type");
320 // Template names cannot appear inside an Objective-C class or object type.
321 if (ObjectType->isObjCObjectOrInterfaceType()) {
325 } else if (SS.isSet()) {
326 // This nested-name-specifier occurs after another nested-name-specifier,
327 // so long into the context associated with the prior nested-name-specifier.
328 LookupCtx = computeDeclContext(SS, EnteringContext);
329 isDependent = isDependentScopeSpecifier(SS);
331 // The declaration context must be complete.
332 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
336 bool ObjectTypeSearchedInScope = false;
337 bool AllowFunctionTemplatesInLookup = true;
339 // Perform "qualified" name lookup into the declaration context we
340 // computed, which is either the type of the base of a member access
341 // expression or the declaration context associated with a prior
342 // nested-name-specifier.
343 LookupQualifiedName(Found, LookupCtx);
344 if (!ObjectType.isNull() && Found.empty()) {
345 // C++ [basic.lookup.classref]p1:
346 // In a class member access expression (5.2.5), if the . or -> token is
347 // immediately followed by an identifier followed by a <, the
348 // identifier must be looked up to determine whether the < is the
349 // beginning of a template argument list (14.2) or a less-than operator.
350 // The identifier is first looked up in the class of the object
351 // expression. If the identifier is not found, it is then looked up in
352 // the context of the entire postfix-expression and shall name a class
353 // or function template.
354 if (S) LookupName(Found, S);
355 ObjectTypeSearchedInScope = true;
356 AllowFunctionTemplatesInLookup = false;
358 } else if (isDependent && (!S || ObjectType.isNull())) {
359 // We cannot look into a dependent object type or nested nme
361 MemberOfUnknownSpecialization = true;
364 // Perform unqualified name lookup in the current scope.
365 LookupName(Found, S);
367 if (!ObjectType.isNull())
368 AllowFunctionTemplatesInLookup = false;
371 if (Found.empty() && !isDependent) {
372 // If we did not find any names, attempt to correct any typos.
373 DeclarationName Name = Found.getLookupName();
375 // Simple filter callback that, for keywords, only accepts the C++ *_cast
376 auto FilterCCC = llvm::make_unique<CorrectionCandidateCallback>();
377 FilterCCC->WantTypeSpecifiers = false;
378 FilterCCC->WantExpressionKeywords = false;
379 FilterCCC->WantRemainingKeywords = false;
380 FilterCCC->WantCXXNamedCasts = true;
381 if (TypoCorrection Corrected = CorrectTypo(
382 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS,
383 std::move(FilterCCC), CTK_ErrorRecovery, LookupCtx)) {
384 Found.setLookupName(Corrected.getCorrection());
385 if (auto *ND = Corrected.getFoundDecl())
387 FilterAcceptableTemplateNames(Found);
388 if (!Found.empty()) {
390 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
391 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
392 Name.getAsString() == CorrectedStr;
393 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
394 << Name << LookupCtx << DroppedSpecifier
397 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
401 Found.setLookupName(Name);
405 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
408 MemberOfUnknownSpecialization = true;
412 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
413 !getLangOpts().CPlusPlus11) {
414 // C++03 [basic.lookup.classref]p1:
415 // [...] If the lookup in the class of the object expression finds a
416 // template, the name is also looked up in the context of the entire
417 // postfix-expression and [...]
419 // Note: C++11 does not perform this second lookup.
420 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
422 LookupName(FoundOuter, S);
423 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
425 if (FoundOuter.empty()) {
426 // - if the name is not found, the name found in the class of the
427 // object expression is used, otherwise
428 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
429 FoundOuter.isAmbiguous()) {
430 // - if the name is found in the context of the entire
431 // postfix-expression and does not name a class template, the name
432 // found in the class of the object expression is used, otherwise
434 } else if (!Found.isSuppressingDiagnostics()) {
435 // - if the name found is a class template, it must refer to the same
436 // entity as the one found in the class of the object expression,
437 // otherwise the program is ill-formed.
438 if (!Found.isSingleResult() ||
439 Found.getFoundDecl()->getCanonicalDecl()
440 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
441 Diag(Found.getNameLoc(),
442 diag::ext_nested_name_member_ref_lookup_ambiguous)
443 << Found.getLookupName()
445 Diag(Found.getRepresentativeDecl()->getLocation(),
446 diag::note_ambig_member_ref_object_type)
448 Diag(FoundOuter.getFoundDecl()->getLocation(),
449 diag::note_ambig_member_ref_scope);
451 // Recover by taking the template that we found in the object
452 // expression's type.
458 void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
460 SourceLocation Greater) {
461 if (TemplateName.isInvalid())
464 DeclarationNameInfo NameInfo;
466 LookupNameKind LookupKind;
468 DeclContext *LookupCtx = nullptr;
469 NamedDecl *Found = nullptr;
471 // Figure out what name we looked up.
472 if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
473 NameInfo = ME->getMemberNameInfo();
474 SS.Adopt(ME->getQualifierLoc());
475 LookupKind = LookupMemberName;
476 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
477 Found = ME->getMemberDecl();
479 auto *DRE = cast<DeclRefExpr>(TemplateName.get());
480 NameInfo = DRE->getNameInfo();
481 SS.Adopt(DRE->getQualifierLoc());
482 LookupKind = LookupOrdinaryName;
483 Found = DRE->getFoundDecl();
486 // Try to correct the name by looking for templates and C++ named casts.
487 struct TemplateCandidateFilter : CorrectionCandidateCallback {
488 TemplateCandidateFilter() {
489 WantTypeSpecifiers = false;
490 WantExpressionKeywords = false;
491 WantRemainingKeywords = false;
492 WantCXXNamedCasts = true;
494 bool ValidateCandidate(const TypoCorrection &Candidate) override {
495 if (auto *ND = Candidate.getCorrectionDecl())
496 return isAcceptableTemplateName(ND->getASTContext(), ND, true);
497 return Candidate.isKeyword();
501 DeclarationName Name = NameInfo.getName();
502 if (TypoCorrection Corrected =
503 CorrectTypo(NameInfo, LookupKind, S, &SS,
504 llvm::make_unique<TemplateCandidateFilter>(),
505 CTK_ErrorRecovery, LookupCtx)) {
506 auto *ND = Corrected.getFoundDecl();
508 ND = isAcceptableTemplateName(Context, ND,
509 /*AllowFunctionTemplates*/ true);
510 if (ND || Corrected.isKeyword()) {
512 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
513 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
514 Name.getAsString() == CorrectedStr;
515 diagnoseTypo(Corrected,
516 PDiag(diag::err_non_template_in_member_template_id_suggest)
517 << Name << LookupCtx << DroppedSpecifier
518 << SS.getRange(), false);
520 diagnoseTypo(Corrected,
521 PDiag(diag::err_non_template_in_template_id_suggest)
525 Diag(Found->getLocation(),
526 diag::note_non_template_in_template_id_found);
531 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
532 << Name << SourceRange(Less, Greater);
534 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
537 /// ActOnDependentIdExpression - Handle a dependent id-expression that
538 /// was just parsed. This is only possible with an explicit scope
539 /// specifier naming a dependent type.
541 Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
542 SourceLocation TemplateKWLoc,
543 const DeclarationNameInfo &NameInfo,
544 bool isAddressOfOperand,
545 const TemplateArgumentListInfo *TemplateArgs) {
546 DeclContext *DC = getFunctionLevelDeclContext();
548 // C++11 [expr.prim.general]p12:
549 // An id-expression that denotes a non-static data member or non-static
550 // member function of a class can only be used:
552 // - if that id-expression denotes a non-static data member and it
553 // appears in an unevaluated operand.
555 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
556 // CXXDependentScopeMemberExpr. The former can instantiate to either
557 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
558 // always a MemberExpr.
559 bool MightBeCxx11UnevalField =
560 getLangOpts().CPlusPlus11 && isUnevaluatedContext();
562 // Check if the nested name specifier is an enum type.
564 if (NestedNameSpecifier *NNS = SS.getScopeRep())
565 IsEnum = dyn_cast_or_null<EnumType>(NNS->getAsType());
567 if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
568 isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
569 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
571 // Since the 'this' expression is synthesized, we don't need to
572 // perform the double-lookup check.
573 NamedDecl *FirstQualifierInScope = nullptr;
575 return CXXDependentScopeMemberExpr::Create(
576 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
577 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
578 FirstQualifierInScope, NameInfo, TemplateArgs);
581 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
585 Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
586 SourceLocation TemplateKWLoc,
587 const DeclarationNameInfo &NameInfo,
588 const TemplateArgumentListInfo *TemplateArgs) {
589 return DependentScopeDeclRefExpr::Create(
590 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
595 /// Determine whether we would be unable to instantiate this template (because
596 /// it either has no definition, or is in the process of being instantiated).
597 bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
598 NamedDecl *Instantiation,
599 bool InstantiatedFromMember,
600 const NamedDecl *Pattern,
601 const NamedDecl *PatternDef,
602 TemplateSpecializationKind TSK,
603 bool Complain /*= true*/) {
604 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
605 isa<VarDecl>(Instantiation));
607 bool IsEntityBeingDefined = false;
608 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
609 IsEntityBeingDefined = TD->isBeingDefined();
611 if (PatternDef && !IsEntityBeingDefined) {
612 NamedDecl *SuggestedDef = nullptr;
613 if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
614 /*OnlyNeedComplete*/false)) {
615 // If we're allowed to diagnose this and recover, do so.
616 bool Recover = Complain && !isSFINAEContext();
618 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
619 Sema::MissingImportKind::Definition, Recover);
625 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
628 llvm::Optional<unsigned> Note;
629 QualType InstantiationTy;
630 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
631 InstantiationTy = Context.getTypeDeclType(TD);
633 Diag(PointOfInstantiation,
634 diag::err_template_instantiate_within_definition)
635 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
637 // Not much point in noting the template declaration here, since
638 // we're lexically inside it.
639 Instantiation->setInvalidDecl();
640 } else if (InstantiatedFromMember) {
641 if (isa<FunctionDecl>(Instantiation)) {
642 Diag(PointOfInstantiation,
643 diag::err_explicit_instantiation_undefined_member)
644 << /*member function*/ 1 << Instantiation->getDeclName()
645 << Instantiation->getDeclContext();
646 Note = diag::note_explicit_instantiation_here;
648 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
649 Diag(PointOfInstantiation,
650 diag::err_implicit_instantiate_member_undefined)
652 Note = diag::note_member_declared_at;
655 if (isa<FunctionDecl>(Instantiation)) {
656 Diag(PointOfInstantiation,
657 diag::err_explicit_instantiation_undefined_func_template)
659 Note = diag::note_explicit_instantiation_here;
660 } else if (isa<TagDecl>(Instantiation)) {
661 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
662 << (TSK != TSK_ImplicitInstantiation)
664 Note = diag::note_template_decl_here;
666 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
667 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
668 Diag(PointOfInstantiation,
669 diag::err_explicit_instantiation_undefined_var_template)
671 Instantiation->setInvalidDecl();
673 Diag(PointOfInstantiation,
674 diag::err_explicit_instantiation_undefined_member)
675 << /*static data member*/ 2 << Instantiation->getDeclName()
676 << Instantiation->getDeclContext();
677 Note = diag::note_explicit_instantiation_here;
680 if (Note) // Diagnostics were emitted.
681 Diag(Pattern->getLocation(), Note.getValue());
683 // In general, Instantiation isn't marked invalid to get more than one
684 // error for multiple undefined instantiations. But the code that does
685 // explicit declaration -> explicit definition conversion can't handle
686 // invalid declarations, so mark as invalid in that case.
687 if (TSK == TSK_ExplicitInstantiationDeclaration)
688 Instantiation->setInvalidDecl();
692 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
693 /// that the template parameter 'PrevDecl' is being shadowed by a new
694 /// declaration at location Loc. Returns true to indicate that this is
695 /// an error, and false otherwise.
696 void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
697 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
699 // Microsoft Visual C++ permits template parameters to be shadowed.
700 if (getLangOpts().MicrosoftExt)
703 // C++ [temp.local]p4:
704 // A template-parameter shall not be redeclared within its
705 // scope (including nested scopes).
706 Diag(Loc, diag::err_template_param_shadow)
707 << cast<NamedDecl>(PrevDecl)->getDeclName();
708 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
711 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
712 /// the parameter D to reference the templated declaration and return a pointer
713 /// to the template declaration. Otherwise, do nothing to D and return null.
714 TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
715 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
716 D = Temp->getTemplatedDecl();
722 ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
723 SourceLocation EllipsisLoc) const {
724 assert(Kind == Template &&
725 "Only template template arguments can be pack expansions here");
726 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
727 "Template template argument pack expansion without packs");
728 ParsedTemplateArgument Result(*this);
729 Result.EllipsisLoc = EllipsisLoc;
733 static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
734 const ParsedTemplateArgument &Arg) {
736 switch (Arg.getKind()) {
737 case ParsedTemplateArgument::Type: {
739 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
741 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
742 return TemplateArgumentLoc(TemplateArgument(T), DI);
745 case ParsedTemplateArgument::NonType: {
746 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
747 return TemplateArgumentLoc(TemplateArgument(E), E);
750 case ParsedTemplateArgument::Template: {
751 TemplateName Template = Arg.getAsTemplate().get();
752 TemplateArgument TArg;
753 if (Arg.getEllipsisLoc().isValid())
754 TArg = TemplateArgument(Template, Optional<unsigned int>());
757 return TemplateArgumentLoc(TArg,
758 Arg.getScopeSpec().getWithLocInContext(
761 Arg.getEllipsisLoc());
765 llvm_unreachable("Unhandled parsed template argument");
768 /// \brief Translates template arguments as provided by the parser
769 /// into template arguments used by semantic analysis.
770 void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
771 TemplateArgumentListInfo &TemplateArgs) {
772 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
773 TemplateArgs.addArgument(translateTemplateArgument(*this,
777 static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
779 IdentifierInfo *Name) {
780 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
781 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
782 if (PrevDecl && PrevDecl->isTemplateParameter())
783 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
786 /// ActOnTypeParameter - Called when a C++ template type parameter
787 /// (e.g., "typename T") has been parsed. Typename specifies whether
788 /// the keyword "typename" was used to declare the type parameter
789 /// (otherwise, "class" was used), and KeyLoc is the location of the
790 /// "class" or "typename" keyword. ParamName is the name of the
791 /// parameter (NULL indicates an unnamed template parameter) and
792 /// ParamNameLoc is the location of the parameter name (if any).
793 /// If the type parameter has a default argument, it will be added
794 /// later via ActOnTypeParameterDefault.
795 Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
796 SourceLocation EllipsisLoc,
797 SourceLocation KeyLoc,
798 IdentifierInfo *ParamName,
799 SourceLocation ParamNameLoc,
800 unsigned Depth, unsigned Position,
801 SourceLocation EqualLoc,
802 ParsedType DefaultArg) {
803 assert(S->isTemplateParamScope() &&
804 "Template type parameter not in template parameter scope!");
806 SourceLocation Loc = ParamNameLoc;
810 bool IsParameterPack = EllipsisLoc.isValid();
811 TemplateTypeParmDecl *Param
812 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
813 KeyLoc, Loc, Depth, Position, ParamName,
814 Typename, IsParameterPack);
815 Param->setAccess(AS_public);
818 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
820 // Add the template parameter into the current scope.
822 IdResolver.AddDecl(Param);
825 // C++0x [temp.param]p9:
826 // A default template-argument may be specified for any kind of
827 // template-parameter that is not a template parameter pack.
828 if (DefaultArg && IsParameterPack) {
829 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
830 DefaultArg = nullptr;
833 // Handle the default argument, if provided.
835 TypeSourceInfo *DefaultTInfo;
836 GetTypeFromParser(DefaultArg, &DefaultTInfo);
838 assert(DefaultTInfo && "expected source information for type");
840 // Check for unexpanded parameter packs.
841 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
842 UPPC_DefaultArgument))
845 // Check the template argument itself.
846 if (CheckTemplateArgument(Param, DefaultTInfo)) {
847 Param->setInvalidDecl();
851 Param->setDefaultArgument(DefaultTInfo);
857 /// \brief Check that the type of a non-type template parameter is
860 /// \returns the (possibly-promoted) parameter type if valid;
861 /// otherwise, produces a diagnostic and returns a NULL type.
862 QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
863 SourceLocation Loc) {
864 if (TSI->getType()->isUndeducedType()) {
865 // C++1z [temp.dep.expr]p3:
866 // An id-expression is type-dependent if it contains
867 // - an identifier associated by name lookup with a non-type
868 // template-parameter declared with a type that contains a
869 // placeholder type (7.1.7.4),
870 TSI = SubstAutoTypeSourceInfo(TSI, Context.DependentTy);
873 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
876 QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
877 SourceLocation Loc) {
878 // We don't allow variably-modified types as the type of non-type template
880 if (T->isVariablyModifiedType()) {
881 Diag(Loc, diag::err_variably_modified_nontype_template_param)
886 // C++ [temp.param]p4:
888 // A non-type template-parameter shall have one of the following
889 // (optionally cv-qualified) types:
891 // -- integral or enumeration type,
892 if (T->isIntegralOrEnumerationType() ||
893 // -- pointer to object or pointer to function,
894 T->isPointerType() ||
895 // -- reference to object or reference to function,
896 T->isReferenceType() ||
897 // -- pointer to member,
898 T->isMemberPointerType() ||
899 // -- std::nullptr_t.
900 T->isNullPtrType() ||
901 // If T is a dependent type, we can't do the check now, so we
902 // assume that it is well-formed.
903 T->isDependentType() ||
904 // Allow use of auto in template parameter declarations.
905 T->isUndeducedType()) {
906 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
907 // are ignored when determining its type.
908 return T.getUnqualifiedType();
911 // C++ [temp.param]p8:
913 // A non-type template-parameter of type "array of T" or
914 // "function returning T" is adjusted to be of type "pointer to
915 // T" or "pointer to function returning T", respectively.
916 else if (T->isArrayType() || T->isFunctionType())
917 return Context.getDecayedType(T);
919 Diag(Loc, diag::err_template_nontype_parm_bad_type)
925 Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
928 SourceLocation EqualLoc,
930 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
932 if (TInfo->getType()->isUndeducedType()) {
933 Diag(D.getIdentifierLoc(),
934 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
935 << QualType(TInfo->getType()->getContainedAutoType(), 0);
938 assert(S->isTemplateParamScope() &&
939 "Non-type template parameter not in template parameter scope!");
940 bool Invalid = false;
942 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
944 T = Context.IntTy; // Recover with an 'int' type.
948 IdentifierInfo *ParamName = D.getIdentifier();
949 bool IsParameterPack = D.hasEllipsis();
950 NonTypeTemplateParmDecl *Param
951 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
953 D.getIdentifierLoc(),
954 Depth, Position, ParamName, T,
955 IsParameterPack, TInfo);
956 Param->setAccess(AS_public);
959 Param->setInvalidDecl();
962 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
965 // Add the template parameter into the current scope.
967 IdResolver.AddDecl(Param);
970 // C++0x [temp.param]p9:
971 // A default template-argument may be specified for any kind of
972 // template-parameter that is not a template parameter pack.
973 if (Default && IsParameterPack) {
974 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
978 // Check the well-formedness of the default template argument, if provided.
980 // Check for unexpanded parameter packs.
981 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
984 TemplateArgument Converted;
985 ExprResult DefaultRes =
986 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
987 if (DefaultRes.isInvalid()) {
988 Param->setInvalidDecl();
991 Default = DefaultRes.get();
993 Param->setDefaultArgument(Default);
999 /// ActOnTemplateTemplateParameter - Called when a C++ template template
1000 /// parameter (e.g. T in template <template \<typename> class T> class array)
1001 /// has been parsed. S is the current scope.
1002 Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
1003 SourceLocation TmpLoc,
1004 TemplateParameterList *Params,
1005 SourceLocation EllipsisLoc,
1006 IdentifierInfo *Name,
1007 SourceLocation NameLoc,
1010 SourceLocation EqualLoc,
1011 ParsedTemplateArgument Default) {
1012 assert(S->isTemplateParamScope() &&
1013 "Template template parameter not in template parameter scope!");
1015 // Construct the parameter object.
1016 bool IsParameterPack = EllipsisLoc.isValid();
1017 TemplateTemplateParmDecl *Param =
1018 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1019 NameLoc.isInvalid()? TmpLoc : NameLoc,
1020 Depth, Position, IsParameterPack,
1022 Param->setAccess(AS_public);
1024 // If the template template parameter has a name, then link the identifier
1025 // into the scope and lookup mechanisms.
1027 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1030 IdResolver.AddDecl(Param);
1033 if (Params->size() == 0) {
1034 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1035 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1036 Param->setInvalidDecl();
1039 // C++0x [temp.param]p9:
1040 // A default template-argument may be specified for any kind of
1041 // template-parameter that is not a template parameter pack.
1042 if (IsParameterPack && !Default.isInvalid()) {
1043 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1044 Default = ParsedTemplateArgument();
1047 if (!Default.isInvalid()) {
1048 // Check only that we have a template template argument. We don't want to
1049 // try to check well-formedness now, because our template template parameter
1050 // might have dependent types in its template parameters, which we wouldn't
1051 // be able to match now.
1053 // If none of the template template parameter's template arguments mention
1054 // other template parameters, we could actually perform more checking here.
1055 // However, it isn't worth doing.
1056 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
1057 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1058 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1059 << DefaultArg.getSourceRange();
1063 // Check for unexpanded parameter packs.
1064 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
1065 DefaultArg.getArgument().getAsTemplate(),
1066 UPPC_DefaultArgument))
1069 Param->setDefaultArgument(Context, DefaultArg);
1075 /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
1076 /// constrained by RequiresClause, that contains the template parameters in
1078 TemplateParameterList *
1079 Sema::ActOnTemplateParameterList(unsigned Depth,
1080 SourceLocation ExportLoc,
1081 SourceLocation TemplateLoc,
1082 SourceLocation LAngleLoc,
1083 ArrayRef<NamedDecl *> Params,
1084 SourceLocation RAngleLoc,
1085 Expr *RequiresClause) {
1086 if (ExportLoc.isValid())
1087 Diag(ExportLoc, diag::warn_template_export_unsupported);
1089 return TemplateParameterList::Create(
1090 Context, TemplateLoc, LAngleLoc,
1091 llvm::makeArrayRef(Params.data(), Params.size()),
1092 RAngleLoc, RequiresClause);
1095 static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
1097 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
1101 Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
1102 SourceLocation KWLoc, CXXScopeSpec &SS,
1103 IdentifierInfo *Name, SourceLocation NameLoc,
1104 AttributeList *Attr,
1105 TemplateParameterList *TemplateParams,
1106 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1107 SourceLocation FriendLoc,
1108 unsigned NumOuterTemplateParamLists,
1109 TemplateParameterList** OuterTemplateParamLists,
1110 SkipBodyInfo *SkipBody) {
1111 assert(TemplateParams && TemplateParams->size() > 0 &&
1112 "No template parameters");
1113 assert(TUK != TUK_Reference && "Can only declare or define class templates");
1114 bool Invalid = false;
1116 // Check that we can declare a template here.
1117 if (CheckTemplateDeclScope(S, TemplateParams))
1120 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1121 assert(Kind != TTK_Enum && "can't build template of enumerated type");
1123 // There is no such thing as an unnamed class template.
1125 Diag(KWLoc, diag::err_template_unnamed_class);
1129 // Find any previous declaration with this name. For a friend with no
1130 // scope explicitly specified, we only look for tag declarations (per
1131 // C++11 [basic.lookup.elab]p2).
1132 DeclContext *SemanticContext;
1133 LookupResult Previous(*this, Name, NameLoc,
1134 (SS.isEmpty() && TUK == TUK_Friend)
1135 ? LookupTagName : LookupOrdinaryName,
1136 forRedeclarationInCurContext());
1137 if (SS.isNotEmpty() && !SS.isInvalid()) {
1138 SemanticContext = computeDeclContext(SS, true);
1139 if (!SemanticContext) {
1140 // FIXME: Horrible, horrible hack! We can't currently represent this
1141 // in the AST, and historically we have just ignored such friend
1142 // class templates, so don't complain here.
1143 Diag(NameLoc, TUK == TUK_Friend
1144 ? diag::warn_template_qualified_friend_ignored
1145 : diag::err_template_qualified_declarator_no_match)
1146 << SS.getScopeRep() << SS.getRange();
1147 return TUK != TUK_Friend;
1150 if (RequireCompleteDeclContext(SS, SemanticContext))
1153 // If we're adding a template to a dependent context, we may need to
1154 // rebuilding some of the types used within the template parameter list,
1155 // now that we know what the current instantiation is.
1156 if (SemanticContext->isDependentContext()) {
1157 ContextRAII SavedContext(*this, SemanticContext);
1158 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1160 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
1161 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
1163 LookupQualifiedName(Previous, SemanticContext);
1165 SemanticContext = CurContext;
1167 // C++14 [class.mem]p14:
1168 // If T is the name of a class, then each of the following shall have a
1169 // name different from T:
1170 // -- every member template of class T
1171 if (TUK != TUK_Friend &&
1172 DiagnoseClassNameShadow(SemanticContext,
1173 DeclarationNameInfo(Name, NameLoc)))
1176 LookupName(Previous, S);
1179 if (Previous.isAmbiguous())
1182 NamedDecl *PrevDecl = nullptr;
1183 if (Previous.begin() != Previous.end())
1184 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1186 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1187 // Maybe we will complain about the shadowed template parameter.
1188 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1189 // Just pretend that we didn't see the previous declaration.
1193 // If there is a previous declaration with the same name, check
1194 // whether this is a valid redeclaration.
1195 ClassTemplateDecl *PrevClassTemplate =
1196 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1198 // We may have found the injected-class-name of a class template,
1199 // class template partial specialization, or class template specialization.
1200 // In these cases, grab the template that is being defined or specialized.
1201 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
1202 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1203 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1205 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1206 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1208 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1209 ->getSpecializedTemplate();
1213 if (TUK == TUK_Friend) {
1214 // C++ [namespace.memdef]p3:
1215 // [...] When looking for a prior declaration of a class or a function
1216 // declared as a friend, and when the name of the friend class or
1217 // function is neither a qualified name nor a template-id, scopes outside
1218 // the innermost enclosing namespace scope are not considered.
1220 DeclContext *OutermostContext = CurContext;
1221 while (!OutermostContext->isFileContext())
1222 OutermostContext = OutermostContext->getLookupParent();
1225 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1226 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1227 SemanticContext = PrevDecl->getDeclContext();
1229 // Declarations in outer scopes don't matter. However, the outermost
1230 // context we computed is the semantic context for our new
1232 PrevDecl = PrevClassTemplate = nullptr;
1233 SemanticContext = OutermostContext;
1235 // Check that the chosen semantic context doesn't already contain a
1236 // declaration of this name as a non-tag type.
1237 Previous.clear(LookupOrdinaryName);
1238 DeclContext *LookupContext = SemanticContext;
1239 while (LookupContext->isTransparentContext())
1240 LookupContext = LookupContext->getLookupParent();
1241 LookupQualifiedName(Previous, LookupContext);
1243 if (Previous.isAmbiguous())
1246 if (Previous.begin() != Previous.end())
1247 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1250 } else if (PrevDecl &&
1251 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1253 PrevDecl = PrevClassTemplate = nullptr;
1255 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1256 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1258 !(PrevClassTemplate &&
1259 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1260 SemanticContext->getRedeclContext()))) {
1261 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1262 Diag(Shadow->getTargetDecl()->getLocation(),
1263 diag::note_using_decl_target);
1264 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1265 // Recover by ignoring the old declaration.
1266 PrevDecl = PrevClassTemplate = nullptr;
1270 // TODO Memory management; associated constraints are not always stored.
1271 Expr *const CurAC = formAssociatedConstraints(TemplateParams, nullptr);
1273 if (PrevClassTemplate) {
1274 // Ensure that the template parameter lists are compatible. Skip this check
1275 // for a friend in a dependent context: the template parameter list itself
1276 // could be dependent.
1277 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1278 !TemplateParameterListsAreEqual(TemplateParams,
1279 PrevClassTemplate->getTemplateParameters(),
1284 // Check for matching associated constraints on redeclarations.
1285 const Expr *const PrevAC = PrevClassTemplate->getAssociatedConstraints();
1286 const bool RedeclACMismatch = [&] {
1287 if (!(CurAC || PrevAC))
1288 return false; // Nothing to check; no mismatch.
1289 if (CurAC && PrevAC) {
1290 llvm::FoldingSetNodeID CurACInfo, PrevACInfo;
1291 CurAC->Profile(CurACInfo, Context, /*Canonical=*/true);
1292 PrevAC->Profile(PrevACInfo, Context, /*Canonical=*/true);
1293 if (CurACInfo == PrevACInfo)
1294 return false; // All good; no mismatch.
1299 if (RedeclACMismatch) {
1300 Diag(CurAC ? CurAC->getLocStart() : NameLoc,
1301 diag::err_template_different_associated_constraints);
1302 Diag(PrevAC ? PrevAC->getLocStart() : PrevClassTemplate->getLocation(),
1303 diag::note_template_prev_declaration) << /*declaration*/0;
1307 // C++ [temp.class]p4:
1308 // In a redeclaration, partial specialization, explicit
1309 // specialization or explicit instantiation of a class template,
1310 // the class-key shall agree in kind with the original class
1311 // template declaration (7.1.5.3).
1312 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
1313 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
1314 TUK == TUK_Definition, KWLoc, Name)) {
1315 Diag(KWLoc, diag::err_use_with_wrong_tag)
1317 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
1318 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
1319 Kind = PrevRecordDecl->getTagKind();
1322 // Check for redefinition of this class template.
1323 if (TUK == TUK_Definition) {
1324 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
1325 // If we have a prior definition that is not visible, treat this as
1326 // simply making that previous definition visible.
1327 NamedDecl *Hidden = nullptr;
1328 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
1329 SkipBody->ShouldSkip = true;
1330 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1331 assert(Tmpl && "original definition of a class template is not a "
1333 makeMergedDefinitionVisible(Hidden);
1334 makeMergedDefinitionVisible(Tmpl);
1338 Diag(NameLoc, diag::err_redefinition) << Name;
1339 Diag(Def->getLocation(), diag::note_previous_definition);
1340 // FIXME: Would it make sense to try to "forget" the previous
1341 // definition, as part of error recovery?
1345 } else if (PrevDecl) {
1347 // A class template shall not have the same name as any other
1348 // template, class, function, object, enumeration, enumerator,
1349 // namespace, or type in the same scope (3.3), except as specified
1351 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1352 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1356 // Check the template parameter list of this declaration, possibly
1357 // merging in the template parameter list from the previous class
1358 // template declaration. Skip this check for a friend in a dependent
1359 // context, because the template parameter list might be dependent.
1360 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1361 CheckTemplateParameterList(
1363 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1365 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1366 SemanticContext->isDependentContext())
1367 ? TPC_ClassTemplateMember
1368 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1369 : TPC_ClassTemplate))
1373 // If the name of the template was qualified, we must be defining the
1374 // template out-of-line.
1375 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1376 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
1377 : diag::err_member_decl_does_not_match)
1378 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
1383 // If this is a templated friend in a dependent context we should not put it
1384 // on the redecl chain. In some cases, the templated friend can be the most
1385 // recent declaration tricking the template instantiator to make substitutions
1387 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
1388 bool ShouldAddRedecl
1389 = !(TUK == TUK_Friend && CurContext->isDependentContext());
1391 CXXRecordDecl *NewClass =
1392 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
1393 PrevClassTemplate && ShouldAddRedecl ?
1394 PrevClassTemplate->getTemplatedDecl() : nullptr,
1395 /*DelayTypeCreation=*/true);
1396 SetNestedNameSpecifier(NewClass, SS);
1397 if (NumOuterTemplateParamLists > 0)
1398 NewClass->setTemplateParameterListsInfo(
1399 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1400 NumOuterTemplateParamLists));
1402 // Add alignment attributes if necessary; these attributes are checked when
1403 // the ASTContext lays out the structure.
1404 if (TUK == TUK_Definition) {
1405 AddAlignmentAttributesForRecord(NewClass);
1406 AddMsStructLayoutForRecord(NewClass);
1409 // Attach the associated constraints when the declaration will not be part of
1411 Expr *const ACtoAttach =
1412 PrevClassTemplate && ShouldAddRedecl ? nullptr : CurAC;
1414 ClassTemplateDecl *NewTemplate
1415 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1416 DeclarationName(Name), TemplateParams,
1417 NewClass, ACtoAttach);
1419 if (ShouldAddRedecl)
1420 NewTemplate->setPreviousDecl(PrevClassTemplate);
1422 NewClass->setDescribedClassTemplate(NewTemplate);
1424 if (ModulePrivateLoc.isValid())
1425 NewTemplate->setModulePrivate();
1427 // Build the type for the class template declaration now.
1428 QualType T = NewTemplate->getInjectedClassNameSpecialization();
1429 T = Context.getInjectedClassNameType(NewClass, T);
1430 assert(T->isDependentType() && "Class template type is not dependent?");
1433 // If we are providing an explicit specialization of a member that is a
1434 // class template, make a note of that.
1435 if (PrevClassTemplate &&
1436 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1437 PrevClassTemplate->setMemberSpecialization();
1439 // Set the access specifier.
1440 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
1441 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
1443 // Set the lexical context of these templates
1444 NewClass->setLexicalDeclContext(CurContext);
1445 NewTemplate->setLexicalDeclContext(CurContext);
1447 if (TUK == TUK_Definition)
1448 NewClass->startDefinition();
1451 ProcessDeclAttributeList(S, NewClass, Attr);
1453 if (PrevClassTemplate)
1454 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1456 AddPushedVisibilityAttribute(NewClass);
1458 if (TUK != TUK_Friend) {
1459 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1461 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1462 Outer = Outer->getParent();
1463 PushOnScopeChains(NewTemplate, Outer);
1465 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
1466 NewTemplate->setAccess(PrevClassTemplate->getAccess());
1467 NewClass->setAccess(PrevClassTemplate->getAccess());
1470 NewTemplate->setObjectOfFriendDecl();
1472 // Friend templates are visible in fairly strange ways.
1473 if (!CurContext->isDependentContext()) {
1474 DeclContext *DC = SemanticContext->getRedeclContext();
1475 DC->makeDeclVisibleInContext(NewTemplate);
1476 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1477 PushOnScopeChains(NewTemplate, EnclosingScope,
1478 /* AddToContext = */ false);
1481 FriendDecl *Friend = FriendDecl::Create(
1482 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
1483 Friend->setAccess(AS_public);
1484 CurContext->addDecl(Friend);
1487 if (PrevClassTemplate)
1488 CheckRedeclarationModuleOwnership(NewTemplate, PrevClassTemplate);
1491 NewTemplate->setInvalidDecl();
1492 NewClass->setInvalidDecl();
1495 ActOnDocumentableDecl(NewTemplate);
1501 /// Transform to convert portions of a constructor declaration into the
1502 /// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
1503 struct ConvertConstructorToDeductionGuideTransform {
1504 ConvertConstructorToDeductionGuideTransform(Sema &S,
1505 ClassTemplateDecl *Template)
1506 : SemaRef(S), Template(Template) {}
1509 ClassTemplateDecl *Template;
1511 DeclContext *DC = Template->getDeclContext();
1512 CXXRecordDecl *Primary = Template->getTemplatedDecl();
1513 DeclarationName DeductionGuideName =
1514 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template);
1516 QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
1518 // Index adjustment to apply to convert depth-1 template parameters into
1519 // depth-0 template parameters.
1520 unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
1522 /// Transform a constructor declaration into a deduction guide.
1523 NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
1524 CXXConstructorDecl *CD) {
1525 SmallVector<TemplateArgument, 16> SubstArgs;
1527 LocalInstantiationScope Scope(SemaRef);
1529 // C++ [over.match.class.deduct]p1:
1530 // -- For each constructor of the class template designated by the
1531 // template-name, a function template with the following properties:
1533 // -- The template parameters are the template parameters of the class
1534 // template followed by the template parameters (including default
1535 // template arguments) of the constructor, if any.
1536 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
1538 TemplateParameterList *InnerParams = FTD->getTemplateParameters();
1539 SmallVector<NamedDecl *, 16> AllParams;
1540 AllParams.reserve(TemplateParams->size() + InnerParams->size());
1541 AllParams.insert(AllParams.begin(),
1542 TemplateParams->begin(), TemplateParams->end());
1543 SubstArgs.reserve(InnerParams->size());
1545 // Later template parameters could refer to earlier ones, so build up
1546 // a list of substituted template arguments as we go.
1547 for (NamedDecl *Param : *InnerParams) {
1548 MultiLevelTemplateArgumentList Args;
1549 Args.addOuterTemplateArguments(SubstArgs);
1550 Args.addOuterRetainedLevel();
1551 NamedDecl *NewParam = transformTemplateParameter(Param, Args);
1554 AllParams.push_back(NewParam);
1555 SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
1556 SemaRef.Context.getInjectedTemplateArg(NewParam)));
1558 TemplateParams = TemplateParameterList::Create(
1559 SemaRef.Context, InnerParams->getTemplateLoc(),
1560 InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
1561 /*FIXME: RequiresClause*/ nullptr);
1564 // If we built a new template-parameter-list, track that we need to
1565 // substitute references to the old parameters into references to the
1567 MultiLevelTemplateArgumentList Args;
1569 Args.addOuterTemplateArguments(SubstArgs);
1570 Args.addOuterRetainedLevel();
1573 FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc()
1574 .getAsAdjusted<FunctionProtoTypeLoc>();
1575 assert(FPTL && "no prototype for constructor declaration");
1577 // Transform the type of the function, adjusting the return type and
1578 // replacing references to the old parameters with references to the
1581 SmallVector<ParmVarDecl*, 8> Params;
1582 QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args);
1583 if (NewType.isNull())
1585 TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
1587 return buildDeductionGuide(TemplateParams, CD->isExplicit(), NewTInfo,
1588 CD->getLocStart(), CD->getLocation(),
1592 /// Build a deduction guide with the specified parameter types.
1593 NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
1594 SourceLocation Loc = Template->getLocation();
1596 // Build the requested type.
1597 FunctionProtoType::ExtProtoInfo EPI;
1598 EPI.HasTrailingReturn = true;
1599 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
1600 DeductionGuideName, EPI);
1601 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
1603 FunctionProtoTypeLoc FPTL =
1604 TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
1606 // Build the parameters, needed during deduction / substitution.
1607 SmallVector<ParmVarDecl*, 4> Params;
1608 for (auto T : ParamTypes) {
1609 ParmVarDecl *NewParam = ParmVarDecl::Create(
1610 SemaRef.Context, DC, Loc, Loc, nullptr, T,
1611 SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
1612 NewParam->setScopeInfo(0, Params.size());
1613 FPTL.setParam(Params.size(), NewParam);
1614 Params.push_back(NewParam);
1617 return buildDeductionGuide(Template->getTemplateParameters(), false, TSI,
1622 /// Transform a constructor template parameter into a deduction guide template
1623 /// parameter, rebuilding any internal references to earlier parameters and
1624 /// renumbering as we go.
1625 NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
1626 MultiLevelTemplateArgumentList &Args) {
1627 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
1628 // TemplateTypeParmDecl's index cannot be changed after creation, so
1629 // substitute it directly.
1630 auto *NewTTP = TemplateTypeParmDecl::Create(
1631 SemaRef.Context, DC, TTP->getLocStart(), TTP->getLocation(),
1632 /*Depth*/0, Depth1IndexAdjustment + TTP->getIndex(),
1633 TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
1634 TTP->isParameterPack());
1635 if (TTP->hasDefaultArgument()) {
1636 TypeSourceInfo *InstantiatedDefaultArg =
1637 SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
1638 TTP->getDefaultArgumentLoc(), TTP->getDeclName());
1639 if (InstantiatedDefaultArg)
1640 NewTTP->setDefaultArgument(InstantiatedDefaultArg);
1642 SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam,
1647 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
1648 return transformTemplateParameterImpl(TTP, Args);
1650 return transformTemplateParameterImpl(
1651 cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
1653 template<typename TemplateParmDecl>
1655 transformTemplateParameterImpl(TemplateParmDecl *OldParam,
1656 MultiLevelTemplateArgumentList &Args) {
1657 // Ask the template instantiator to do the heavy lifting for us, then adjust
1658 // the index of the parameter once it's done.
1660 cast_or_null<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
1661 assert(NewParam->getDepth() == 0 && "unexpected template param depth");
1662 NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
1666 QualType transformFunctionProtoType(TypeLocBuilder &TLB,
1667 FunctionProtoTypeLoc TL,
1668 SmallVectorImpl<ParmVarDecl*> &Params,
1669 MultiLevelTemplateArgumentList &Args) {
1670 SmallVector<QualType, 4> ParamTypes;
1671 const FunctionProtoType *T = TL.getTypePtr();
1673 // -- The types of the function parameters are those of the constructor.
1674 for (auto *OldParam : TL.getParams()) {
1675 ParmVarDecl *NewParam = transformFunctionTypeParam(OldParam, Args);
1678 ParamTypes.push_back(NewParam->getType());
1679 Params.push_back(NewParam);
1682 // -- The return type is the class template specialization designated by
1683 // the template-name and template arguments corresponding to the
1684 // template parameters obtained from the class template.
1686 // We use the injected-class-name type of the primary template instead.
1687 // This has the convenient property that it is different from any type that
1688 // the user can write in a deduction-guide (because they cannot enter the
1689 // context of the template), so implicit deduction guides can never collide
1690 // with explicit ones.
1691 QualType ReturnType = DeducedType;
1692 TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
1694 // Resolving a wording defect, we also inherit the variadicness of the
1696 FunctionProtoType::ExtProtoInfo EPI;
1697 EPI.Variadic = T->isVariadic();
1698 EPI.HasTrailingReturn = true;
1700 QualType Result = SemaRef.BuildFunctionType(
1701 ReturnType, ParamTypes, TL.getLocStart(), DeductionGuideName, EPI);
1702 if (Result.isNull())
1705 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
1706 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
1707 NewTL.setLParenLoc(TL.getLParenLoc());
1708 NewTL.setRParenLoc(TL.getRParenLoc());
1709 NewTL.setExceptionSpecRange(SourceRange());
1710 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
1711 for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
1712 NewTL.setParam(I, Params[I]);
1718 transformFunctionTypeParam(ParmVarDecl *OldParam,
1719 MultiLevelTemplateArgumentList &Args) {
1720 TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
1721 TypeSourceInfo *NewDI;
1722 if (!Args.getNumLevels())
1724 else if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
1725 // Expand out the one and only element in each inner pack.
1726 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
1728 SemaRef.SubstType(PackTL.getPatternLoc(), Args,
1729 OldParam->getLocation(), OldParam->getDeclName());
1730 if (!NewDI) return nullptr;
1732 SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
1733 PackTL.getTypePtr()->getNumExpansions());
1735 NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
1736 OldParam->getDeclName());
1740 // Canonicalize the type. This (for instance) replaces references to
1741 // typedef members of the current instantiations with the definitions of
1742 // those typedefs, avoiding triggering instantiation of the deduced type
1743 // during deduction.
1744 // FIXME: It would be preferable to retain type sugar and source
1745 // information here (and handle this in substitution instead).
1746 NewDI = SemaRef.Context.getTrivialTypeSourceInfo(
1747 SemaRef.Context.getCanonicalType(NewDI->getType()),
1748 OldParam->getLocation());
1750 // Resolving a wording defect, we also inherit default arguments from the
1752 ExprResult NewDefArg;
1753 if (OldParam->hasDefaultArg()) {
1754 NewDefArg = Args.getNumLevels()
1755 ? SemaRef.SubstExpr(OldParam->getDefaultArg(), Args)
1756 : OldParam->getDefaultArg();
1757 if (NewDefArg.isInvalid())
1761 ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
1762 OldParam->getInnerLocStart(),
1763 OldParam->getLocation(),
1764 OldParam->getIdentifier(),
1767 OldParam->getStorageClass(),
1769 NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
1770 OldParam->getFunctionScopeIndex());
1774 NamedDecl *buildDeductionGuide(TemplateParameterList *TemplateParams,
1775 bool Explicit, TypeSourceInfo *TInfo,
1776 SourceLocation LocStart, SourceLocation Loc,
1777 SourceLocation LocEnd) {
1778 DeclarationNameInfo Name(DeductionGuideName, Loc);
1779 ArrayRef<ParmVarDecl *> Params =
1780 TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
1782 // Build the implicit deduction guide template.
1784 CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, Explicit,
1785 Name, TInfo->getType(), TInfo, LocEnd);
1786 Guide->setImplicit();
1787 Guide->setParams(Params);
1789 for (auto *Param : Params)
1790 Param->setDeclContext(Guide);
1792 auto *GuideTemplate = FunctionTemplateDecl::Create(
1793 SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
1794 GuideTemplate->setImplicit();
1795 Guide->setDescribedFunctionTemplate(GuideTemplate);
1797 if (isa<CXXRecordDecl>(DC)) {
1798 Guide->setAccess(AS_public);
1799 GuideTemplate->setAccess(AS_public);
1802 DC->addDecl(GuideTemplate);
1803 return GuideTemplate;
1808 void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
1809 SourceLocation Loc) {
1810 DeclContext *DC = Template->getDeclContext();
1811 if (DC->isDependentContext())
1814 ConvertConstructorToDeductionGuideTransform Transform(
1815 *this, cast<ClassTemplateDecl>(Template));
1816 if (!isCompleteType(Loc, Transform.DeducedType))
1819 // Check whether we've already declared deduction guides for this template.
1820 // FIXME: Consider storing a flag on the template to indicate this.
1821 auto Existing = DC->lookup(Transform.DeductionGuideName);
1822 for (auto *D : Existing)
1823 if (D->isImplicit())
1826 // In case we were expanding a pack when we attempted to declare deduction
1827 // guides, turn off pack expansion for everything we're about to do.
1828 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1829 // Create a template instantiation record to track the "instantiation" of
1830 // constructors into deduction guides.
1831 // FIXME: Add a kind for this to give more meaningful diagnostics. But can
1832 // this substitution process actually fail?
1833 InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
1835 // Convert declared constructors into deduction guide templates.
1836 // FIXME: Skip constructors for which deduction must necessarily fail (those
1837 // for which some class template parameter without a default argument never
1838 // appears in a deduced context).
1839 bool AddedAny = false;
1840 for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
1841 D = D->getUnderlyingDecl();
1842 if (D->isInvalidDecl() || D->isImplicit())
1844 D = cast<NamedDecl>(D->getCanonicalDecl());
1846 auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
1848 dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
1849 // Class-scope explicit specializations (MS extension) do not result in
1850 // deduction guides.
1851 if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
1854 Transform.transformConstructor(FTD, CD);
1858 // C++17 [over.match.class.deduct]
1859 // -- If C is not defined or does not declare any constructors, an
1860 // additional function template derived as above from a hypothetical
1863 Transform.buildSimpleDeductionGuide(None);
1865 // -- An additional function template derived as above from a hypothetical
1866 // constructor C(C), called the copy deduction candidate.
1867 cast<CXXDeductionGuideDecl>(
1868 cast<FunctionTemplateDecl>(
1869 Transform.buildSimpleDeductionGuide(Transform.DeducedType))
1870 ->getTemplatedDecl())
1871 ->setIsCopyDeductionCandidate();
1874 /// \brief Diagnose the presence of a default template argument on a
1875 /// template parameter, which is ill-formed in certain contexts.
1877 /// \returns true if the default template argument should be dropped.
1878 static bool DiagnoseDefaultTemplateArgument(Sema &S,
1879 Sema::TemplateParamListContext TPC,
1880 SourceLocation ParamLoc,
1881 SourceRange DefArgRange) {
1883 case Sema::TPC_ClassTemplate:
1884 case Sema::TPC_VarTemplate:
1885 case Sema::TPC_TypeAliasTemplate:
1888 case Sema::TPC_FunctionTemplate:
1889 case Sema::TPC_FriendFunctionTemplateDefinition:
1890 // C++ [temp.param]p9:
1891 // A default template-argument shall not be specified in a
1892 // function template declaration or a function template
1894 // If a friend function template declaration specifies a default
1895 // template-argument, that declaration shall be a definition and shall be
1896 // the only declaration of the function template in the translation unit.
1897 // (C++98/03 doesn't have this wording; see DR226).
1898 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
1899 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1900 : diag::ext_template_parameter_default_in_function_template)
1904 case Sema::TPC_ClassTemplateMember:
1905 // C++0x [temp.param]p9:
1906 // A default template-argument shall not be specified in the
1907 // template-parameter-lists of the definition of a member of a
1908 // class template that appears outside of the member's class.
1909 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1913 case Sema::TPC_FriendClassTemplate:
1914 case Sema::TPC_FriendFunctionTemplate:
1915 // C++ [temp.param]p9:
1916 // A default template-argument shall not be specified in a
1917 // friend template declaration.
1918 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1922 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1923 // for friend function templates if there is only a single
1924 // declaration (and it is a definition). Strange!
1927 llvm_unreachable("Invalid TemplateParamListContext!");
1930 /// \brief Check for unexpanded parameter packs within the template parameters
1931 /// of a template template parameter, recursively.
1932 static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1933 TemplateTemplateParmDecl *TTP) {
1934 // A template template parameter which is a parameter pack is also a pack
1936 if (TTP->isParameterPack())
1939 TemplateParameterList *Params = TTP->getTemplateParameters();
1940 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1941 NamedDecl *P = Params->getParam(I);
1942 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
1943 if (!NTTP->isParameterPack() &&
1944 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
1945 NTTP->getTypeSourceInfo(),
1946 Sema::UPPC_NonTypeTemplateParameterType))
1952 if (TemplateTemplateParmDecl *InnerTTP
1953 = dyn_cast<TemplateTemplateParmDecl>(P))
1954 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1961 /// \brief Checks the validity of a template parameter list, possibly
1962 /// considering the template parameter list from a previous
1965 /// If an "old" template parameter list is provided, it must be
1966 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
1967 /// template parameter list.
1969 /// \param NewParams Template parameter list for a new template
1970 /// declaration. This template parameter list will be updated with any
1971 /// default arguments that are carried through from the previous
1972 /// template parameter list.
1974 /// \param OldParams If provided, template parameter list from a
1975 /// previous declaration of the same template. Default template
1976 /// arguments will be merged from the old template parameter list to
1977 /// the new template parameter list.
1979 /// \param TPC Describes the context in which we are checking the given
1980 /// template parameter list.
1982 /// \returns true if an error occurred, false otherwise.
1983 bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
1984 TemplateParameterList *OldParams,
1985 TemplateParamListContext TPC) {
1986 bool Invalid = false;
1988 // C++ [temp.param]p10:
1989 // The set of default template-arguments available for use with a
1990 // template declaration or definition is obtained by merging the
1991 // default arguments from the definition (if in scope) and all
1992 // declarations in scope in the same way default function
1993 // arguments are (8.3.6).
1994 bool SawDefaultArgument = false;
1995 SourceLocation PreviousDefaultArgLoc;
1997 // Dummy initialization to avoid warnings.
1998 TemplateParameterList::iterator OldParam = NewParams->end();
2000 OldParam = OldParams->begin();
2002 bool RemoveDefaultArguments = false;
2003 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2004 NewParamEnd = NewParams->end();
2005 NewParam != NewParamEnd; ++NewParam) {
2006 // Variables used to diagnose redundant default arguments
2007 bool RedundantDefaultArg = false;
2008 SourceLocation OldDefaultLoc;
2009 SourceLocation NewDefaultLoc;
2011 // Variable used to diagnose missing default arguments
2012 bool MissingDefaultArg = false;
2014 // Variable used to diagnose non-final parameter packs
2015 bool SawParameterPack = false;
2017 if (TemplateTypeParmDecl *NewTypeParm
2018 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2019 // Check the presence of a default argument here.
2020 if (NewTypeParm->hasDefaultArgument() &&
2021 DiagnoseDefaultTemplateArgument(*this, TPC,
2022 NewTypeParm->getLocation(),
2023 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
2025 NewTypeParm->removeDefaultArgument();
2027 // Merge default arguments for template type parameters.
2028 TemplateTypeParmDecl *OldTypeParm
2029 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2030 if (NewTypeParm->isParameterPack()) {
2031 assert(!NewTypeParm->hasDefaultArgument() &&
2032 "Parameter packs can't have a default argument!");
2033 SawParameterPack = true;
2034 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2035 NewTypeParm->hasDefaultArgument()) {
2036 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2037 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2038 SawDefaultArgument = true;
2039 RedundantDefaultArg = true;
2040 PreviousDefaultArgLoc = NewDefaultLoc;
2041 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2042 // Merge the default argument from the old declaration to the
2044 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2045 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2046 } else if (NewTypeParm->hasDefaultArgument()) {
2047 SawDefaultArgument = true;
2048 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2049 } else if (SawDefaultArgument)
2050 MissingDefaultArg = true;
2051 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2052 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2053 // Check for unexpanded parameter packs.
2054 if (!NewNonTypeParm->isParameterPack() &&
2055 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2056 NewNonTypeParm->getTypeSourceInfo(),
2057 UPPC_NonTypeTemplateParameterType)) {
2062 // Check the presence of a default argument here.
2063 if (NewNonTypeParm->hasDefaultArgument() &&
2064 DiagnoseDefaultTemplateArgument(*this, TPC,
2065 NewNonTypeParm->getLocation(),
2066 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
2067 NewNonTypeParm->removeDefaultArgument();
2070 // Merge default arguments for non-type template parameters
2071 NonTypeTemplateParmDecl *OldNonTypeParm
2072 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2073 if (NewNonTypeParm->isParameterPack()) {
2074 assert(!NewNonTypeParm->hasDefaultArgument() &&
2075 "Parameter packs can't have a default argument!");
2076 if (!NewNonTypeParm->isPackExpansion())
2077 SawParameterPack = true;
2078 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2079 NewNonTypeParm->hasDefaultArgument()) {
2080 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2081 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2082 SawDefaultArgument = true;
2083 RedundantDefaultArg = true;
2084 PreviousDefaultArgLoc = NewDefaultLoc;
2085 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2086 // Merge the default argument from the old declaration to the
2088 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2089 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2090 } else if (NewNonTypeParm->hasDefaultArgument()) {
2091 SawDefaultArgument = true;
2092 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2093 } else if (SawDefaultArgument)
2094 MissingDefaultArg = true;
2096 TemplateTemplateParmDecl *NewTemplateParm
2097 = cast<TemplateTemplateParmDecl>(*NewParam);
2099 // Check for unexpanded parameter packs, recursively.
2100 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2105 // Check the presence of a default argument here.
2106 if (NewTemplateParm->hasDefaultArgument() &&
2107 DiagnoseDefaultTemplateArgument(*this, TPC,
2108 NewTemplateParm->getLocation(),
2109 NewTemplateParm->getDefaultArgument().getSourceRange()))
2110 NewTemplateParm->removeDefaultArgument();
2112 // Merge default arguments for template template parameters
2113 TemplateTemplateParmDecl *OldTemplateParm
2114 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2115 if (NewTemplateParm->isParameterPack()) {
2116 assert(!NewTemplateParm->hasDefaultArgument() &&
2117 "Parameter packs can't have a default argument!");
2118 if (!NewTemplateParm->isPackExpansion())
2119 SawParameterPack = true;
2120 } else if (OldTemplateParm &&
2121 hasVisibleDefaultArgument(OldTemplateParm) &&
2122 NewTemplateParm->hasDefaultArgument()) {
2123 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2124 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2125 SawDefaultArgument = true;
2126 RedundantDefaultArg = true;
2127 PreviousDefaultArgLoc = NewDefaultLoc;
2128 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2129 // Merge the default argument from the old declaration to the
2131 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2132 PreviousDefaultArgLoc
2133 = OldTemplateParm->getDefaultArgument().getLocation();
2134 } else if (NewTemplateParm->hasDefaultArgument()) {
2135 SawDefaultArgument = true;
2136 PreviousDefaultArgLoc
2137 = NewTemplateParm->getDefaultArgument().getLocation();
2138 } else if (SawDefaultArgument)
2139 MissingDefaultArg = true;
2142 // C++11 [temp.param]p11:
2143 // If a template parameter of a primary class template or alias template
2144 // is a template parameter pack, it shall be the last template parameter.
2145 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2146 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2147 TPC == TPC_TypeAliasTemplate)) {
2148 Diag((*NewParam)->getLocation(),
2149 diag::err_template_param_pack_must_be_last_template_parameter);
2153 if (RedundantDefaultArg) {
2154 // C++ [temp.param]p12:
2155 // A template-parameter shall not be given default arguments
2156 // by two different declarations in the same scope.
2157 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2158 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2160 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
2161 // C++ [temp.param]p11:
2162 // If a template-parameter of a class template has a default
2163 // template-argument, each subsequent template-parameter shall either
2164 // have a default template-argument supplied or be a template parameter
2166 Diag((*NewParam)->getLocation(),
2167 diag::err_template_param_default_arg_missing);
2168 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2170 RemoveDefaultArguments = true;
2173 // If we have an old template parameter list that we're merging
2174 // in, move on to the next parameter.
2179 // We were missing some default arguments at the end of the list, so remove
2180 // all of the default arguments.
2181 if (RemoveDefaultArguments) {
2182 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2183 NewParamEnd = NewParams->end();
2184 NewParam != NewParamEnd; ++NewParam) {
2185 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2186 TTP->removeDefaultArgument();
2187 else if (NonTypeTemplateParmDecl *NTTP
2188 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2189 NTTP->removeDefaultArgument();
2191 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2200 /// A class which looks for a use of a certain level of template
2202 struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
2203 typedef RecursiveASTVisitor<DependencyChecker> super;
2207 // Whether we're looking for a use of a template parameter that makes the
2208 // overall construct type-dependent / a dependent type. This is strictly
2209 // best-effort for now; we may fail to match at all for a dependent type
2210 // in some cases if this is set.
2211 bool IgnoreNonTypeDependent;
2214 SourceLocation MatchLoc;
2216 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2217 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2220 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2221 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2222 NamedDecl *ND = Params->getParam(0);
2223 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2224 Depth = PD->getDepth();
2225 } else if (NonTypeTemplateParmDecl *PD =
2226 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2227 Depth = PD->getDepth();
2229 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2233 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2234 if (ParmDepth >= Depth) {
2242 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2243 // Prune out non-type-dependent expressions if requested. This can
2244 // sometimes result in us failing to find a template parameter reference
2245 // (if a value-dependent expression creates a dependent type), but this
2246 // mode is best-effort only.
2247 if (auto *E = dyn_cast_or_null<Expr>(S))
2248 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2250 return super::TraverseStmt(S, Q);
2253 bool TraverseTypeLoc(TypeLoc TL) {
2254 if (IgnoreNonTypeDependent && !TL.isNull() &&
2255 !TL.getType()->isDependentType())
2257 return super::TraverseTypeLoc(TL);
2260 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2261 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2264 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
2265 // For a best-effort search, keep looking until we find a location.
2266 return IgnoreNonTypeDependent || !Matches(T->getDepth());
2269 bool TraverseTemplateName(TemplateName N) {
2270 if (TemplateTemplateParmDecl *PD =
2271 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2272 if (Matches(PD->getDepth()))
2274 return super::TraverseTemplateName(N);
2277 bool VisitDeclRefExpr(DeclRefExpr *E) {
2278 if (NonTypeTemplateParmDecl *PD =
2279 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2280 if (Matches(PD->getDepth(), E->getExprLoc()))
2282 return super::VisitDeclRefExpr(E);
2285 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2286 return TraverseType(T->getReplacementType());
2290 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
2291 return TraverseTemplateArgument(T->getArgumentPack());
2294 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
2295 return TraverseType(T->getInjectedSpecializationType());
2298 } // end anonymous namespace
2300 /// Determines whether a given type depends on the given parameter
2303 DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
2304 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2305 Checker.TraverseType(T);
2306 return Checker.Match;
2309 // Find the source range corresponding to the named type in the given
2310 // nested-name-specifier, if any.
2311 static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2313 const CXXScopeSpec &SS) {
2314 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2315 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2316 if (const Type *CurType = NNS->getAsType()) {
2317 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2318 return NNSLoc.getTypeLoc().getSourceRange();
2322 NNSLoc = NNSLoc.getPrefix();
2325 return SourceRange();
2328 /// \brief Match the given template parameter lists to the given scope
2329 /// specifier, returning the template parameter list that applies to the
2332 /// \param DeclStartLoc the start of the declaration that has a scope
2333 /// specifier or a template parameter list.
2335 /// \param DeclLoc The location of the declaration itself.
2337 /// \param SS the scope specifier that will be matched to the given template
2338 /// parameter lists. This scope specifier precedes a qualified name that is
2341 /// \param TemplateId The template-id following the scope specifier, if there
2342 /// is one. Used to check for a missing 'template<>'.
2344 /// \param ParamLists the template parameter lists, from the outermost to the
2345 /// innermost template parameter lists.
2347 /// \param IsFriend Whether to apply the slightly different rules for
2348 /// matching template parameters to scope specifiers in friend
2351 /// \param IsMemberSpecialization will be set true if the scope specifier
2352 /// denotes a fully-specialized type, and therefore this is a declaration of
2353 /// a member specialization.
2355 /// \returns the template parameter list, if any, that corresponds to the
2356 /// name that is preceded by the scope specifier @p SS. This template
2357 /// parameter list may have template parameters (if we're declaring a
2358 /// template) or may have no template parameters (if we're declaring a
2359 /// template specialization), or may be NULL (if what we're declaring isn't
2360 /// itself a template).
2361 TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2362 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2363 TemplateIdAnnotation *TemplateId,
2364 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2365 bool &IsMemberSpecialization, bool &Invalid) {
2366 IsMemberSpecialization = false;
2369 // The sequence of nested types to which we will match up the template
2370 // parameter lists. We first build this list by starting with the type named
2371 // by the nested-name-specifier and walking out until we run out of types.
2372 SmallVector<QualType, 4> NestedTypes;
2374 if (SS.getScopeRep()) {
2375 if (CXXRecordDecl *Record
2376 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2377 T = Context.getTypeDeclType(Record);
2379 T = QualType(SS.getScopeRep()->getAsType(), 0);
2382 // If we found an explicit specialization that prevents us from needing
2383 // 'template<>' headers, this will be set to the location of that
2384 // explicit specialization.
2385 SourceLocation ExplicitSpecLoc;
2387 while (!T.isNull()) {
2388 NestedTypes.push_back(T);
2390 // Retrieve the parent of a record type.
2391 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2392 // If this type is an explicit specialization, we're done.
2393 if (ClassTemplateSpecializationDecl *Spec
2394 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2395 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
2396 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2397 ExplicitSpecLoc = Spec->getLocation();
2400 } else if (Record->getTemplateSpecializationKind()
2401 == TSK_ExplicitSpecialization) {
2402 ExplicitSpecLoc = Record->getLocation();
2406 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2407 T = Context.getTypeDeclType(Parent);
2413 if (const TemplateSpecializationType *TST
2414 = T->getAs<TemplateSpecializationType>()) {
2415 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2416 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2417 T = Context.getTypeDeclType(Parent);
2424 // Look one step prior in a dependent template specialization type.
2425 if (const DependentTemplateSpecializationType *DependentTST
2426 = T->getAs<DependentTemplateSpecializationType>()) {
2427 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2428 T = QualType(NNS->getAsType(), 0);
2434 // Look one step prior in a dependent name type.
2435 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2436 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2437 T = QualType(NNS->getAsType(), 0);
2443 // Retrieve the parent of an enumeration type.
2444 if (const EnumType *EnumT = T->getAs<EnumType>()) {
2445 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2447 EnumDecl *Enum = EnumT->getDecl();
2449 // Get to the parent type.
2450 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2451 T = Context.getTypeDeclType(Parent);
2459 // Reverse the nested types list, since we want to traverse from the outermost
2460 // to the innermost while checking template-parameter-lists.
2461 std::reverse(NestedTypes.begin(), NestedTypes.end());
2463 // C++0x [temp.expl.spec]p17:
2464 // A member or a member template may be nested within many
2465 // enclosing class templates. In an explicit specialization for
2466 // such a member, the member declaration shall be preceded by a
2467 // template<> for each enclosing class template that is
2468 // explicitly specialized.
2469 bool SawNonEmptyTemplateParameterList = false;
2471 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2472 if (SawNonEmptyTemplateParameterList) {
2473 Diag(DeclLoc, diag::err_specialize_member_of_template)
2474 << !Recovery << Range;
2476 IsMemberSpecialization = false;
2483 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2484 // Check that we can have an explicit specialization here.
2485 if (CheckExplicitSpecialization(Range, true))
2488 // We don't have a template header, but we should.
2489 SourceLocation ExpectedTemplateLoc;
2490 if (!ParamLists.empty())
2491 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2493 ExpectedTemplateLoc = DeclStartLoc;
2495 Diag(DeclLoc, diag::err_template_spec_needs_header)
2497 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2501 unsigned ParamIdx = 0;
2502 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2504 T = NestedTypes[TypeIdx];
2506 // Whether we expect a 'template<>' header.
2507 bool NeedEmptyTemplateHeader = false;
2509 // Whether we expect a template header with parameters.
2510 bool NeedNonemptyTemplateHeader = false;
2512 // For a dependent type, the set of template parameters that we
2514 TemplateParameterList *ExpectedTemplateParams = nullptr;
2516 // C++0x [temp.expl.spec]p15:
2517 // A member or a member template may be nested within many enclosing
2518 // class templates. In an explicit specialization for such a member, the
2519 // member declaration shall be preceded by a template<> for each
2520 // enclosing class template that is explicitly specialized.
2521 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2522 if (ClassTemplatePartialSpecializationDecl *Partial
2523 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2524 ExpectedTemplateParams = Partial->getTemplateParameters();
2525 NeedNonemptyTemplateHeader = true;
2526 } else if (Record->isDependentType()) {
2527 if (Record->getDescribedClassTemplate()) {
2528 ExpectedTemplateParams = Record->getDescribedClassTemplate()
2529 ->getTemplateParameters();
2530 NeedNonemptyTemplateHeader = true;
2532 } else if (ClassTemplateSpecializationDecl *Spec
2533 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2534 // C++0x [temp.expl.spec]p4:
2535 // Members of an explicitly specialized class template are defined
2536 // in the same manner as members of normal classes, and not using
2537 // the template<> syntax.
2538 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2539 NeedEmptyTemplateHeader = true;
2542 } else if (Record->getTemplateSpecializationKind()) {
2543 if (Record->getTemplateSpecializationKind()
2544 != TSK_ExplicitSpecialization &&
2545 TypeIdx == NumTypes - 1)
2546 IsMemberSpecialization = true;
2550 } else if (const TemplateSpecializationType *TST
2551 = T->getAs<TemplateSpecializationType>()) {
2552 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2553 ExpectedTemplateParams = Template->getTemplateParameters();
2554 NeedNonemptyTemplateHeader = true;
2556 } else if (T->getAs<DependentTemplateSpecializationType>()) {
2557 // FIXME: We actually could/should check the template arguments here
2558 // against the corresponding template parameter list.
2559 NeedNonemptyTemplateHeader = false;
2562 // C++ [temp.expl.spec]p16:
2563 // In an explicit specialization declaration for a member of a class
2564 // template or a member template that ap- pears in namespace scope, the
2565 // member template and some of its enclosing class templates may remain
2566 // unspecialized, except that the declaration shall not explicitly
2567 // specialize a class member template if its en- closing class templates
2568 // are not explicitly specialized as well.
2569 if (ParamIdx < ParamLists.size()) {
2570 if (ParamLists[ParamIdx]->size() == 0) {
2571 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2575 SawNonEmptyTemplateParameterList = true;
2578 if (NeedEmptyTemplateHeader) {
2579 // If we're on the last of the types, and we need a 'template<>' header
2580 // here, then it's a member specialization.
2581 if (TypeIdx == NumTypes - 1)
2582 IsMemberSpecialization = true;
2584 if (ParamIdx < ParamLists.size()) {
2585 if (ParamLists[ParamIdx]->size() > 0) {
2586 // The header has template parameters when it shouldn't. Complain.
2587 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2588 diag::err_template_param_list_matches_nontemplate)
2590 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2591 ParamLists[ParamIdx]->getRAngleLoc())
2592 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2597 // Consume this template header.
2603 if (DiagnoseMissingExplicitSpecialization(
2604 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
2610 if (NeedNonemptyTemplateHeader) {
2611 // In friend declarations we can have template-ids which don't
2612 // depend on the corresponding template parameter lists. But
2613 // assume that empty parameter lists are supposed to match this
2615 if (IsFriend && T->isDependentType()) {
2616 if (ParamIdx < ParamLists.size() &&
2617 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
2618 ExpectedTemplateParams = nullptr;
2623 if (ParamIdx < ParamLists.size()) {
2624 // Check the template parameter list, if we can.
2625 if (ExpectedTemplateParams &&
2626 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
2627 ExpectedTemplateParams,
2628 true, TPL_TemplateMatch))
2632 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
2633 TPC_ClassTemplateMember))
2640 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2642 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2648 // If there were at least as many template-ids as there were template
2649 // parameter lists, then there are no template parameter lists remaining for
2650 // the declaration itself.
2651 if (ParamIdx >= ParamLists.size()) {
2652 if (TemplateId && !IsFriend) {
2653 // We don't have a template header for the declaration itself, but we
2655 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2656 TemplateId->RAngleLoc));
2658 // Fabricate an empty template parameter list for the invented header.
2659 return TemplateParameterList::Create(Context, SourceLocation(),
2660 SourceLocation(), None,
2661 SourceLocation(), nullptr);
2667 // If there were too many template parameter lists, complain about that now.
2668 if (ParamIdx < ParamLists.size() - 1) {
2669 bool HasAnyExplicitSpecHeader = false;
2670 bool AllExplicitSpecHeaders = true;
2671 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
2672 if (ParamLists[I]->size() == 0)
2673 HasAnyExplicitSpecHeader = true;
2675 AllExplicitSpecHeaders = false;
2678 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2679 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
2680 : diag::err_template_spec_extra_headers)
2681 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
2682 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
2684 // If there was a specialization somewhere, such that 'template<>' is
2685 // not required, and there were any 'template<>' headers, note where the
2686 // specialization occurred.
2687 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
2688 Diag(ExplicitSpecLoc,
2689 diag::note_explicit_template_spec_does_not_need_header)
2690 << NestedTypes.back();
2692 // We have a template parameter list with no corresponding scope, which
2693 // means that the resulting template declaration can't be instantiated
2694 // properly (we'll end up with dependent nodes when we shouldn't).
2695 if (!AllExplicitSpecHeaders)
2699 // C++ [temp.expl.spec]p16:
2700 // In an explicit specialization declaration for a member of a class
2701 // template or a member template that ap- pears in namespace scope, the
2702 // member template and some of its enclosing class templates may remain
2703 // unspecialized, except that the declaration shall not explicitly
2704 // specialize a class member template if its en- closing class templates
2705 // are not explicitly specialized as well.
2706 if (ParamLists.back()->size() == 0 &&
2707 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2711 // Return the last template parameter list, which corresponds to the
2712 // entity being declared.
2713 return ParamLists.back();
2716 void Sema::NoteAllFoundTemplates(TemplateName Name) {
2717 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2718 Diag(Template->getLocation(), diag::note_template_declared_here)
2719 << (isa<FunctionTemplateDecl>(Template)
2721 : isa<ClassTemplateDecl>(Template)
2723 : isa<VarTemplateDecl>(Template)
2725 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2726 << Template->getDeclName();
2730 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
2731 for (OverloadedTemplateStorage::iterator I = OST->begin(),
2734 Diag((*I)->getLocation(), diag::note_template_declared_here)
2735 << 0 << (*I)->getDeclName();
2742 checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
2743 const SmallVectorImpl<TemplateArgument> &Converted,
2744 SourceLocation TemplateLoc,
2745 TemplateArgumentListInfo &TemplateArgs) {
2746 ASTContext &Context = SemaRef.getASTContext();
2747 switch (BTD->getBuiltinTemplateKind()) {
2748 case BTK__make_integer_seq: {
2749 // Specializations of __make_integer_seq<S, T, N> are treated like
2750 // S<T, 0, ..., N-1>.
2752 // C++14 [inteseq.intseq]p1:
2753 // T shall be an integer type.
2754 if (!Converted[1].getAsType()->isIntegralType(Context)) {
2755 SemaRef.Diag(TemplateArgs[1].getLocation(),
2756 diag::err_integer_sequence_integral_element_type);
2760 // C++14 [inteseq.make]p1:
2761 // If N is negative the program is ill-formed.
2762 TemplateArgument NumArgsArg = Converted[2];
2763 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2765 SemaRef.Diag(TemplateArgs[2].getLocation(),
2766 diag::err_integer_sequence_negative_length);
2770 QualType ArgTy = NumArgsArg.getIntegralType();
2771 TemplateArgumentListInfo SyntheticTemplateArgs;
2772 // The type argument gets reused as the first template argument in the
2773 // synthetic template argument list.
2774 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2775 // Expand N into 0 ... N-1.
2776 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2778 TemplateArgument TA(Context, I, ArgTy);
2779 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
2780 TA, ArgTy, TemplateArgs[2].getLocation()));
2782 // The first template argument will be reused as the template decl that
2783 // our synthetic template arguments will be applied to.
2784 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2785 TemplateLoc, SyntheticTemplateArgs);
2788 case BTK__type_pack_element:
2789 // Specializations of
2790 // __type_pack_element<Index, T_1, ..., T_N>
2791 // are treated like T_Index.
2792 assert(Converted.size() == 2 &&
2793 "__type_pack_element should be given an index and a parameter pack");
2795 // If the Index is out of bounds, the program is ill-formed.
2796 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
2797 llvm::APSInt Index = IndexArg.getAsIntegral();
2798 assert(Index >= 0 && "the index used with __type_pack_element should be of "
2799 "type std::size_t, and hence be non-negative");
2800 if (Index >= Ts.pack_size()) {
2801 SemaRef.Diag(TemplateArgs[0].getLocation(),
2802 diag::err_type_pack_element_out_of_bounds);
2806 // We simply return the type at index `Index`.
2807 auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
2808 return Nth->getAsType();
2810 llvm_unreachable("unexpected BuiltinTemplateDecl!");
2813 /// Determine whether this alias template is "enable_if_t".
2814 static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
2815 return AliasTemplate->getName().equals("enable_if_t");
2818 /// Collect all of the separable terms in the given condition, which
2819 /// might be a conjunction.
2821 /// FIXME: The right answer is to convert the logical expression into
2822 /// disjunctive normal form, so we can find the first failed term
2823 /// within each possible clause.
2824 static void collectConjunctionTerms(Expr *Clause,
2825 SmallVectorImpl<Expr *> &Terms) {
2826 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
2827 if (BinOp->getOpcode() == BO_LAnd) {
2828 collectConjunctionTerms(BinOp->getLHS(), Terms);
2829 collectConjunctionTerms(BinOp->getRHS(), Terms);
2835 Terms.push_back(Clause);
2838 // The ranges-v3 library uses an odd pattern of a top-level "||" with
2839 // a left-hand side that is value-dependent but never true. Identify
2840 // the idiom and ignore that term.
2841 static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
2843 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
2844 if (!BinOp) return Cond;
2846 if (BinOp->getOpcode() != BO_LOr) return Cond;
2848 // With an inner '==' that has a literal on the right-hand side.
2849 Expr *LHS = BinOp->getLHS();
2850 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
2851 if (!InnerBinOp) return Cond;
2853 if (InnerBinOp->getOpcode() != BO_EQ ||
2854 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
2857 // If the inner binary operation came from a macro expansion named
2858 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
2859 // of the '||', which is the real, user-provided condition.
2860 SourceLocation Loc = InnerBinOp->getExprLoc();
2861 if (!Loc.isMacroID()) return Cond;
2863 StringRef MacroName = PP.getImmediateMacroName(Loc);
2864 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
2865 return BinOp->getRHS();
2870 std::pair<Expr *, std::string>
2871 Sema::findFailedBooleanCondition(Expr *Cond, bool AllowTopLevelCond) {
2872 Cond = lookThroughRangesV3Condition(PP, Cond);
2874 // Separate out all of the terms in a conjunction.
2875 SmallVector<Expr *, 4> Terms;
2876 collectConjunctionTerms(Cond, Terms);
2878 // Determine which term failed.
2879 Expr *FailedCond = nullptr;
2880 for (Expr *Term : Terms) {
2881 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
2883 // Literals are uninteresting.
2884 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
2885 isa<IntegerLiteral>(TermAsWritten))
2888 // The initialization of the parameter from the argument is
2889 // a constant-evaluated context.
2890 EnterExpressionEvaluationContext ConstantEvaluated(
2891 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
2894 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
2896 FailedCond = TermAsWritten;
2902 if (!AllowTopLevelCond)
2903 return { nullptr, "" };
2905 FailedCond = Cond->IgnoreParenImpCasts();
2908 std::string Description;
2910 llvm::raw_string_ostream Out(Description);
2911 FailedCond->printPretty(Out, nullptr, getPrintingPolicy());
2913 return { FailedCond, Description };
2916 QualType Sema::CheckTemplateIdType(TemplateName Name,
2917 SourceLocation TemplateLoc,
2918 TemplateArgumentListInfo &TemplateArgs) {
2919 DependentTemplateName *DTN
2920 = Name.getUnderlying().getAsDependentTemplateName();
2921 if (DTN && DTN->isIdentifier())
2922 // When building a template-id where the template-name is dependent,
2923 // assume the template is a type template. Either our assumption is
2924 // correct, or the code is ill-formed and will be diagnosed when the
2925 // dependent name is substituted.
2926 return Context.getDependentTemplateSpecializationType(ETK_None,
2927 DTN->getQualifier(),
2928 DTN->getIdentifier(),
2931 TemplateDecl *Template = Name.getAsTemplateDecl();
2932 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2933 isa<VarTemplateDecl>(Template)) {
2934 // We might have a substituted template template parameter pack. If so,
2935 // build a template specialization type for it.
2936 if (Name.getAsSubstTemplateTemplateParmPack())
2937 return Context.getTemplateSpecializationType(Name, TemplateArgs);
2939 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2941 NoteAllFoundTemplates(Name);
2945 // Check that the template argument list is well-formed for this
2947 SmallVector<TemplateArgument, 4> Converted;
2948 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
2954 bool InstantiationDependent = false;
2955 if (TypeAliasTemplateDecl *AliasTemplate =
2956 dyn_cast<TypeAliasTemplateDecl>(Template)) {
2957 // Find the canonical type for this type alias template specialization.
2958 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2959 if (Pattern->isInvalidDecl())
2962 TemplateArgumentList StackTemplateArgs(TemplateArgumentList::OnStack,
2965 // Only substitute for the innermost template argument list.
2966 MultiLevelTemplateArgumentList TemplateArgLists;
2967 TemplateArgLists.addOuterTemplateArguments(&StackTemplateArgs);
2968 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2969 for (unsigned I = 0; I < Depth; ++I)
2970 TemplateArgLists.addOuterTemplateArguments(None);
2972 LocalInstantiationScope Scope(*this);
2973 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
2974 if (Inst.isInvalid())
2977 CanonType = SubstType(Pattern->getUnderlyingType(),
2978 TemplateArgLists, AliasTemplate->getLocation(),
2979 AliasTemplate->getDeclName());
2980 if (CanonType.isNull()) {
2981 // If this was enable_if and we failed to find the nested type
2982 // within enable_if in a SFINAE context, dig out the specific
2983 // enable_if condition that failed and present that instead.
2984 if (isEnableIfAliasTemplate(AliasTemplate)) {
2985 if (auto DeductionInfo = isSFINAEContext()) {
2986 if (*DeductionInfo &&
2987 (*DeductionInfo)->hasSFINAEDiagnostic() &&
2988 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
2989 diag::err_typename_nested_not_found_enable_if &&
2990 TemplateArgs[0].getArgument().getKind()
2991 == TemplateArgument::Expression) {
2993 std::string FailedDescription;
2994 std::tie(FailedCond, FailedDescription) =
2995 findFailedBooleanCondition(
2996 TemplateArgs[0].getSourceExpression(),
2997 /*AllowTopLevelCond=*/true);
2999 // Remove the old SFINAE diagnostic.
3000 PartialDiagnosticAt OldDiag =
3001 {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3002 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3004 // Add a new SFINAE diagnostic specifying which condition
3006 (*DeductionInfo)->addSFINAEDiagnostic(
3008 PDiag(diag::err_typename_nested_not_found_requirement)
3009 << FailedDescription
3010 << FailedCond->getSourceRange());
3017 } else if (Name.isDependent() ||
3018 TemplateSpecializationType::anyDependentTemplateArguments(
3019 TemplateArgs, InstantiationDependent)) {
3020 // This class template specialization is a dependent
3021 // type. Therefore, its canonical type is another class template
3022 // specialization type that contains all of the converted
3023 // arguments in canonical form. This ensures that, e.g., A<T> and
3024 // A<T, T> have identical types when A is declared as:
3026 // template<typename T, typename U = T> struct A;
3027 CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
3029 // This might work out to be a current instantiation, in which
3030 // case the canonical type needs to be the InjectedClassNameType.
3032 // TODO: in theory this could be a simple hashtable lookup; most
3033 // changes to CurContext don't change the set of current
3035 if (isa<ClassTemplateDecl>(Template)) {
3036 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3037 // If we get out to a namespace, we're done.
3038 if (Ctx->isFileContext()) break;
3040 // If this isn't a record, keep looking.
3041 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3042 if (!Record) continue;
3044 // Look for one of the two cases with InjectedClassNameTypes
3045 // and check whether it's the same template.
3046 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3047 !Record->getDescribedClassTemplate())
3050 // Fetch the injected class name type and check whether its
3051 // injected type is equal to the type we just built.
3052 QualType ICNT = Context.getTypeDeclType(Record);
3053 QualType Injected = cast<InjectedClassNameType>(ICNT)
3054 ->getInjectedSpecializationType();
3056 if (CanonType != Injected->getCanonicalTypeInternal())
3059 // If so, the canonical type of this TST is the injected
3060 // class name type of the record we just found.
3061 assert(ICNT.isCanonical());
3066 } else if (ClassTemplateDecl *ClassTemplate
3067 = dyn_cast<ClassTemplateDecl>(Template)) {
3068 // Find the class template specialization declaration that
3069 // corresponds to these arguments.
3070 void *InsertPos = nullptr;
3071 ClassTemplateSpecializationDecl *Decl
3072 = ClassTemplate->findSpecialization(Converted, InsertPos);
3074 // This is the first time we have referenced this class template
3075 // specialization. Create the canonical declaration and add it to
3076 // the set of specializations.
3077 Decl = ClassTemplateSpecializationDecl::Create(Context,
3078 ClassTemplate->getTemplatedDecl()->getTagKind(),
3079 ClassTemplate->getDeclContext(),
3080 ClassTemplate->getTemplatedDecl()->getLocStart(),
3081 ClassTemplate->getLocation(),
3083 Converted, nullptr);
3084 ClassTemplate->AddSpecialization(Decl, InsertPos);
3085 if (ClassTemplate->isOutOfLine())
3086 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3089 if (Decl->getSpecializationKind() == TSK_Undeclared) {
3090 MultiLevelTemplateArgumentList TemplateArgLists;
3091 TemplateArgLists.addOuterTemplateArguments(Converted);
3092 InstantiateAttrsForDecl(TemplateArgLists, ClassTemplate->getTemplatedDecl(),
3096 // Diagnose uses of this specialization.
3097 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3099 CanonType = Context.getTypeDeclType(Decl);
3100 assert(isa<RecordType>(CanonType) &&
3101 "type of non-dependent specialization is not a RecordType");
3102 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3103 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
3107 // Build the fully-sugared type for this class template
3108 // specialization, which refers back to the class template
3109 // specialization we created or found.
3110 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
3114 Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3115 TemplateTy TemplateD, IdentifierInfo *TemplateII,
3116 SourceLocation TemplateIILoc,
3117 SourceLocation LAngleLoc,
3118 ASTTemplateArgsPtr TemplateArgsIn,
3119 SourceLocation RAngleLoc,
3120 bool IsCtorOrDtorName, bool IsClassName) {
3124 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3125 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3127 // C++ [temp.res]p3:
3128 // A qualified-id that refers to a type and in which the
3129 // nested-name-specifier depends on a template-parameter (14.6.2)
3130 // shall be prefixed by the keyword typename to indicate that the
3131 // qualified-id denotes a type, forming an
3132 // elaborated-type-specifier (7.1.5.3).
3133 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
3134 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
3135 << SS.getScopeRep() << TemplateII->getName();
3136 // Recover as if 'typename' were specified.
3137 // FIXME: This is not quite correct recovery as we don't transform SS
3138 // into the corresponding dependent form (and we don't diagnose missing
3139 // 'template' keywords within SS as a result).
3140 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3141 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3142 TemplateArgsIn, RAngleLoc);
3145 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3146 // it's not actually allowed to be used as a type in most cases. Because
3147 // we annotate it before we know whether it's valid, we have to check for
3149 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
3150 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3152 TemplateKWLoc.isInvalid()
3153 ? diag::err_out_of_line_qualified_id_type_names_constructor
3154 : diag::ext_out_of_line_qualified_id_type_names_constructor)
3155 << TemplateII << 0 /*injected-class-name used as template name*/
3156 << 1 /*if any keyword was present, it was 'template'*/;
3160 TemplateName Template = TemplateD.get();
3162 // Translate the parser's template argument list in our AST format.
3163 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3164 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3166 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3168 = Context.getDependentTemplateSpecializationType(ETK_None,
3169 DTN->getQualifier(),
3170 DTN->getIdentifier(),
3172 // Build type-source information.
3174 DependentTemplateSpecializationTypeLoc SpecTL
3175 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3176 SpecTL.setElaboratedKeywordLoc(SourceLocation());
3177 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3178 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3179 SpecTL.setTemplateNameLoc(TemplateIILoc);
3180 SpecTL.setLAngleLoc(LAngleLoc);
3181 SpecTL.setRAngleLoc(RAngleLoc);
3182 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3183 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3184 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3187 QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
3188 if (Result.isNull())
3191 // Build type-source information.
3193 TemplateSpecializationTypeLoc SpecTL
3194 = TLB.push<TemplateSpecializationTypeLoc>(Result);
3195 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3196 SpecTL.setTemplateNameLoc(TemplateIILoc);
3197 SpecTL.setLAngleLoc(LAngleLoc);
3198 SpecTL.setRAngleLoc(RAngleLoc);
3199 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3200 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3202 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
3203 // constructor or destructor name (in such a case, the scope specifier
3204 // will be attached to the enclosing Decl or Expr node).
3205 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
3206 // Create an elaborated-type-specifier containing the nested-name-specifier.
3207 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
3208 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
3209 ElabTL.setElaboratedKeywordLoc(SourceLocation());
3210 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3213 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
3216 TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
3217 TypeSpecifierType TagSpec,
3218 SourceLocation TagLoc,
3220 SourceLocation TemplateKWLoc,
3221 TemplateTy TemplateD,
3222 SourceLocation TemplateLoc,
3223 SourceLocation LAngleLoc,
3224 ASTTemplateArgsPtr TemplateArgsIn,
3225 SourceLocation RAngleLoc) {
3226 TemplateName Template = TemplateD.get();
3228 // Translate the parser's template argument list in our AST format.
3229 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3230 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3232 // Determine the tag kind
3233 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3234 ElaboratedTypeKeyword Keyword
3235 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
3237 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3238 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
3239 DTN->getQualifier(),
3240 DTN->getIdentifier(),
3243 // Build type-source information.
3245 DependentTemplateSpecializationTypeLoc SpecTL
3246 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3247 SpecTL.setElaboratedKeywordLoc(TagLoc);
3248 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3249 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3250 SpecTL.setTemplateNameLoc(TemplateLoc);
3251 SpecTL.setLAngleLoc(LAngleLoc);
3252 SpecTL.setRAngleLoc(RAngleLoc);
3253 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3254 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3255 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3258 if (TypeAliasTemplateDecl *TAT =
3259 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3260 // C++0x [dcl.type.elab]p2:
3261 // If the identifier resolves to a typedef-name or the simple-template-id
3262 // resolves to an alias template specialization, the
3263 // elaborated-type-specifier is ill-formed.
3264 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3265 << TAT << NTK_TypeAliasTemplate << TagKind;
3266 Diag(TAT->getLocation(), diag::note_declared_at);
3269 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3270 if (Result.isNull())
3271 return TypeResult(true);
3273 // Check the tag kind
3274 if (const RecordType *RT = Result->getAs<RecordType>()) {
3275 RecordDecl *D = RT->getDecl();
3277 IdentifierInfo *Id = D->getIdentifier();
3278 assert(Id && "templated class must have an identifier");
3280 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
3282 Diag(TagLoc, diag::err_use_with_wrong_tag)
3284 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
3285 Diag(D->getLocation(), diag::note_previous_use);
3289 // Provide source-location information for the template specialization.
3291 TemplateSpecializationTypeLoc SpecTL
3292 = TLB.push<TemplateSpecializationTypeLoc>(Result);
3293 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3294 SpecTL.setTemplateNameLoc(TemplateLoc);
3295 SpecTL.setLAngleLoc(LAngleLoc);
3296 SpecTL.setRAngleLoc(RAngleLoc);
3297 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3298 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3300 // Construct an elaborated type containing the nested-name-specifier (if any)
3302 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
3303 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
3304 ElabTL.setElaboratedKeywordLoc(TagLoc);
3305 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3306 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
3309 static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3310 NamedDecl *PrevDecl,
3312 bool IsPartialSpecialization);
3314 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
3316 static bool isTemplateArgumentTemplateParameter(
3317 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3318 switch (Arg.getKind()) {
3319 case TemplateArgument::Null:
3320 case TemplateArgument::NullPtr:
3321 case TemplateArgument::Integral:
3322 case TemplateArgument::Declaration:
3323 case TemplateArgument::Pack:
3324 case TemplateArgument::TemplateExpansion:
3327 case TemplateArgument::Type: {
3328 QualType Type = Arg.getAsType();
3329 const TemplateTypeParmType *TPT =
3330 Arg.getAsType()->getAs<TemplateTypeParmType>();
3331 return TPT && !Type.hasQualifiers() &&
3332 TPT->getDepth() == Depth && TPT->getIndex() == Index;
3335 case TemplateArgument::Expression: {
3336 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3337 if (!DRE || !DRE->getDecl())
3339 const NonTypeTemplateParmDecl *NTTP =
3340 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3341 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3344 case TemplateArgument::Template:
3345 const TemplateTemplateParmDecl *TTP =
3346 dyn_cast_or_null<TemplateTemplateParmDecl>(
3347 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
3348 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3350 llvm_unreachable("unexpected kind of template argument");
3353 static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
3354 ArrayRef<TemplateArgument> Args) {
3355 if (Params->size() != Args.size())
3358 unsigned Depth = Params->getDepth();
3360 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3361 TemplateArgument Arg = Args[I];
3363 // If the parameter is a pack expansion, the argument must be a pack
3364 // whose only element is a pack expansion.
3365 if (Params->getParam(I)->isParameterPack()) {
3366 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
3367 !Arg.pack_begin()->isPackExpansion())
3369 Arg = Arg.pack_begin()->getPackExpansionPattern();
3372 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
3379 /// Convert the parser's template argument list representation into our form.
3380 static TemplateArgumentListInfo
3381 makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
3382 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
3383 TemplateId.RAngleLoc);
3384 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
3385 TemplateId.NumArgs);
3386 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
3387 return TemplateArgs;
3390 template<typename PartialSpecDecl>
3391 static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
3392 if (Partial->getDeclContext()->isDependentContext())
3395 // FIXME: Get the TDK from deduction in order to provide better diagnostics
3396 // for non-substitution-failure issues?
3397 TemplateDeductionInfo Info(Partial->getLocation());
3398 if (S.isMoreSpecializedThanPrimary(Partial, Info))
3401 auto *Template = Partial->getSpecializedTemplate();
3402 S.Diag(Partial->getLocation(),
3403 diag::ext_partial_spec_not_more_specialized_than_primary)
3404 << isa<VarTemplateDecl>(Template);
3406 if (Info.hasSFINAEDiagnostic()) {
3407 PartialDiagnosticAt Diag = {SourceLocation(),
3408 PartialDiagnostic::NullDiagnostic()};
3409 Info.takeSFINAEDiagnostic(Diag);
3410 SmallString<128> SFINAEArgString;
3411 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
3413 diag::note_partial_spec_not_more_specialized_than_primary)
3417 S.Diag(Template->getLocation(), diag::note_template_decl_here);
3421 noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
3422 const llvm::SmallBitVector &DeducibleParams) {
3423 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3424 if (!DeducibleParams[I]) {
3425 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3426 if (Param->getDeclName())
3427 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3428 << Param->getDeclName();
3430 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3437 template<typename PartialSpecDecl>
3438 static void checkTemplatePartialSpecialization(Sema &S,
3439 PartialSpecDecl *Partial) {
3440 // C++1z [temp.class.spec]p8: (DR1495)
3441 // - The specialization shall be more specialized than the primary
3442 // template (14.5.5.2).
3443 checkMoreSpecializedThanPrimary(S, Partial);
3445 // C++ [temp.class.spec]p8: (DR1315)
3446 // - Each template-parameter shall appear at least once in the
3447 // template-id outside a non-deduced context.
3448 // C++1z [temp.class.spec.match]p3 (P0127R2)
3449 // If the template arguments of a partial specialization cannot be
3450 // deduced because of the structure of its template-parameter-list
3451 // and the template-id, the program is ill-formed.
3452 auto *TemplateParams = Partial->getTemplateParameters();
3453 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3454 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3455 TemplateParams->getDepth(), DeducibleParams);
3457 if (!DeducibleParams.all()) {
3458 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3459 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
3460 << isa<VarTemplatePartialSpecializationDecl>(Partial)
3461 << (NumNonDeducible > 1)
3462 << SourceRange(Partial->getLocation(),
3463 Partial->getTemplateArgsAsWritten()->RAngleLoc);
3464 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
3468 void Sema::CheckTemplatePartialSpecialization(
3469 ClassTemplatePartialSpecializationDecl *Partial) {
3470 checkTemplatePartialSpecialization(*this, Partial);
3473 void Sema::CheckTemplatePartialSpecialization(
3474 VarTemplatePartialSpecializationDecl *Partial) {
3475 checkTemplatePartialSpecialization(*this, Partial);
3478 void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
3479 // C++1z [temp.param]p11:
3480 // A template parameter of a deduction guide template that does not have a
3481 // default-argument shall be deducible from the parameter-type-list of the
3482 // deduction guide template.
3483 auto *TemplateParams = TD->getTemplateParameters();
3484 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3485 MarkDeducedTemplateParameters(TD, DeducibleParams);
3486 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
3487 // A parameter pack is deducible (to an empty pack).
3488 auto *Param = TemplateParams->getParam(I);
3489 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
3490 DeducibleParams[I] = true;
3493 if (!DeducibleParams.all()) {
3494 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3495 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
3496 << (NumNonDeducible > 1);
3497 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
3501 DeclResult Sema::ActOnVarTemplateSpecialization(
3502 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
3503 TemplateParameterList *TemplateParams, StorageClass SC,
3504 bool IsPartialSpecialization) {
3505 // D must be variable template id.
3506 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
3507 "Variable template specialization is declared with a template it.");
3509 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
3510 TemplateArgumentListInfo TemplateArgs =
3511 makeTemplateArgumentListInfo(*this, *TemplateId);
3512 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
3513 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
3514 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
3516 TemplateName Name = TemplateId->Template.get();
3518 // The template-id must name a variable template.
3519 VarTemplateDecl *VarTemplate =
3520 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
3522 NamedDecl *FnTemplate;
3523 if (auto *OTS = Name.getAsOverloadedTemplate())
3524 FnTemplate = *OTS->begin();
3526 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
3528 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
3529 << FnTemplate->getDeclName();
3530 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
3531 << IsPartialSpecialization;
3534 // Check for unexpanded parameter packs in any of the template arguments.
3535 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3536 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
3537 UPPC_PartialSpecialization))
3540 // Check that the template argument list is well-formed for this
3542 SmallVector<TemplateArgument, 4> Converted;
3543 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
3547 // Find the variable template (partial) specialization declaration that
3548 // corresponds to these arguments.
3549 if (IsPartialSpecialization) {
3550 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
3551 TemplateArgs.size(), Converted))
3554 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
3555 // also do them during instantiation.
3556 bool InstantiationDependent;
3557 if (!Name.isDependent() &&
3558 !TemplateSpecializationType::anyDependentTemplateArguments(
3559 TemplateArgs.arguments(),
3560 InstantiationDependent)) {
3561 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3562 << VarTemplate->getDeclName();
3563 IsPartialSpecialization = false;
3566 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
3568 // C++ [temp.class.spec]p9b3:
3570 // -- The argument list of the specialization shall not be identical
3571 // to the implicit argument list of the primary template.
3572 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
3573 << /*variable template*/ 1
3574 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
3575 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
3576 // FIXME: Recover from this by treating the declaration as a redeclaration
3577 // of the primary template.
3582 void *InsertPos = nullptr;
3583 VarTemplateSpecializationDecl *PrevDecl = nullptr;
3585 if (IsPartialSpecialization)
3586 // FIXME: Template parameter list matters too
3587 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
3589 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
3591 VarTemplateSpecializationDecl *Specialization = nullptr;
3593 // Check whether we can declare a variable template specialization in
3594 // the current scope.
3595 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
3597 IsPartialSpecialization))
3600 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3601 // Since the only prior variable template specialization with these
3602 // arguments was referenced but not declared, reuse that
3603 // declaration node as our own, updating its source location and
3604 // the list of outer template parameters to reflect our new declaration.
3605 Specialization = PrevDecl;
3606 Specialization->setLocation(TemplateNameLoc);
3608 } else if (IsPartialSpecialization) {
3609 // Create a new class template partial specialization declaration node.
3610 VarTemplatePartialSpecializationDecl *PrevPartial =
3611 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
3612 VarTemplatePartialSpecializationDecl *Partial =
3613 VarTemplatePartialSpecializationDecl::Create(
3614 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
3615 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
3616 Converted, TemplateArgs);
3619 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
3620 Specialization = Partial;
3622 // If we are providing an explicit specialization of a member variable
3623 // template specialization, make a note of that.
3624 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3625 PrevPartial->setMemberSpecialization();
3627 CheckTemplatePartialSpecialization(Partial);
3629 // Create a new class template specialization declaration node for
3630 // this explicit specialization or friend declaration.
3631 Specialization = VarTemplateSpecializationDecl::Create(
3632 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
3633 VarTemplate, DI->getType(), DI, SC, Converted);
3634 Specialization->setTemplateArgsInfo(TemplateArgs);
3637 VarTemplate->AddSpecialization(Specialization, InsertPos);
3640 // C++ [temp.expl.spec]p6:
3641 // If a template, a member template or the member of a class template is
3642 // explicitly specialized then that specialization shall be declared
3643 // before the first use of that specialization that would cause an implicit
3644 // instantiation to take place, in every translation unit in which such a
3645 // use occurs; no diagnostic is required.
3646 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3648 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
3649 // Is there any previous explicit specialization declaration?
3650 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3657 SourceRange Range(TemplateNameLoc, RAngleLoc);
3658 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3661 Diag(PrevDecl->getPointOfInstantiation(),
3662 diag::note_instantiation_required_here)
3663 << (PrevDecl->getTemplateSpecializationKind() !=
3664 TSK_ImplicitInstantiation);
3669 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
3670 Specialization->setLexicalDeclContext(CurContext);
3672 // Add the specialization into its lexical context, so that it can
3673 // be seen when iterating through the list of declarations in that
3674 // context. However, specializations are not found by name lookup.
3675 CurContext->addDecl(Specialization);
3677 // Note that this is an explicit specialization.
3678 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
3681 // Check that this isn't a redefinition of this specialization,
3682 // merging with previous declarations.
3683 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
3684 forRedeclarationInCurContext());
3685 PrevSpec.addDecl(PrevDecl);
3686 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
3687 } else if (Specialization->isStaticDataMember() &&
3688 Specialization->isOutOfLine()) {
3689 Specialization->setAccess(VarTemplate->getAccess());
3692 // Link instantiations of static data members back to the template from
3693 // which they were instantiated.
3694 if (Specialization->isStaticDataMember())
3695 Specialization->setInstantiationOfStaticDataMember(
3696 VarTemplate->getTemplatedDecl(),
3697 Specialization->getSpecializationKind());
3699 return Specialization;
3703 /// \brief A partial specialization whose template arguments have matched
3704 /// a given template-id.
3705 struct PartialSpecMatchResult {
3706 VarTemplatePartialSpecializationDecl *Partial;
3707 TemplateArgumentList *Args;
3709 } // end anonymous namespace
3712 Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
3713 SourceLocation TemplateNameLoc,
3714 const TemplateArgumentListInfo &TemplateArgs) {
3715 assert(Template && "A variable template id without template?");
3717 // Check that the template argument list is well-formed for this template.
3718 SmallVector<TemplateArgument, 4> Converted;
3719 if (CheckTemplateArgumentList(
3720 Template, TemplateNameLoc,
3721 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
3725 // Find the variable template specialization declaration that
3726 // corresponds to these arguments.
3727 void *InsertPos = nullptr;
3728 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
3729 Converted, InsertPos)) {
3730 checkSpecializationVisibility(TemplateNameLoc, Spec);
3731 // If we already have a variable template specialization, return it.
3735 // This is the first time we have referenced this variable template
3736 // specialization. Create the canonical declaration and add it to
3737 // the set of specializations, based on the closest partial specialization
3738 // that it represents. That is,
3739 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
3740 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
3742 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
3743 bool AmbiguousPartialSpec = false;
3744 typedef PartialSpecMatchResult MatchResult;
3745 SmallVector<MatchResult, 4> Matched;
3746 SourceLocation PointOfInstantiation = TemplateNameLoc;
3747 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
3748 /*ForTakingAddress=*/false);
3750 // 1. Attempt to find the closest partial specialization that this
3751 // specializes, if any.
3752 // If any of the template arguments is dependent, then this is probably
3753 // a placeholder for an incomplete declarative context; which must be
3754 // complete by instantiation time. Thus, do not search through the partial
3755 // specializations yet.
3756 // TODO: Unify with InstantiateClassTemplateSpecialization()?
3757 // Perhaps better after unification of DeduceTemplateArguments() and
3758 // getMoreSpecializedPartialSpecialization().
3759 bool InstantiationDependent = false;
3760 if (!TemplateSpecializationType::anyDependentTemplateArguments(
3761 TemplateArgs, InstantiationDependent)) {
3763 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
3764 Template->getPartialSpecializations(PartialSpecs);
3766 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3767 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
3768 TemplateDeductionInfo Info(FailedCandidates.getLocation());
3770 if (TemplateDeductionResult Result =
3771 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
3772 // Store the failed-deduction information for use in diagnostics, later.
3773 // TODO: Actually use the failed-deduction info?
3774 FailedCandidates.addCandidate().set(
3775 DeclAccessPair::make(Template, AS_public), Partial,
3776 MakeDeductionFailureInfo(Context, Result, Info));
3779 Matched.push_back(PartialSpecMatchResult());
3780 Matched.back().Partial = Partial;
3781 Matched.back().Args = Info.take();
3785 if (Matched.size() >= 1) {
3786 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
3787 if (Matched.size() == 1) {
3788 // -- If exactly one matching specialization is found, the
3789 // instantiation is generated from that specialization.
3790 // We don't need to do anything for this.
3792 // -- If more than one matching specialization is found, the
3793 // partial order rules (14.5.4.2) are used to determine
3794 // whether one of the specializations is more specialized
3795 // than the others. If none of the specializations is more
3796 // specialized than all of the other matching
3797 // specializations, then the use of the variable template is
3798 // ambiguous and the program is ill-formed.
3799 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
3800 PEnd = Matched.end();
3802 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
3803 PointOfInstantiation) ==
3808 // Determine if the best partial specialization is more specialized than
3810 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
3811 PEnd = Matched.end();
3813 if (P != Best && getMoreSpecializedPartialSpecialization(
3814 P->Partial, Best->Partial,
3815 PointOfInstantiation) != Best->Partial) {
3816 AmbiguousPartialSpec = true;
3822 // Instantiate using the best variable template partial specialization.
3823 InstantiationPattern = Best->Partial;
3824 InstantiationArgs = Best->Args;
3826 // -- If no match is found, the instantiation is generated
3827 // from the primary template.
3828 // InstantiationPattern = Template->getTemplatedDecl();
3832 // 2. Create the canonical declaration.
3833 // Note that we do not instantiate a definition until we see an odr-use
3834 // in DoMarkVarDeclReferenced().
3835 // FIXME: LateAttrs et al.?
3836 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
3837 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
3838 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
3842 if (AmbiguousPartialSpec) {
3843 // Partial ordering did not produce a clear winner. Complain.
3844 Decl->setInvalidDecl();
3845 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
3848 // Print the matching partial specializations.
3849 for (MatchResult P : Matched)
3850 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
3851 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
3856 if (VarTemplatePartialSpecializationDecl *D =
3857 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
3858 Decl->setInstantiationOf(D, InstantiationArgs);
3860 checkSpecializationVisibility(TemplateNameLoc, Decl);
3862 assert(Decl && "No variable template specialization?");
3867 Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
3868 const DeclarationNameInfo &NameInfo,
3869 VarTemplateDecl *Template, SourceLocation TemplateLoc,
3870 const TemplateArgumentListInfo *TemplateArgs) {
3872 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
3874 if (Decl.isInvalid())
3877 VarDecl *Var = cast<VarDecl>(Decl.get());
3878 if (!Var->getTemplateSpecializationKind())
3879 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
3882 // Build an ordinary singleton decl ref.
3883 return BuildDeclarationNameExpr(SS, NameInfo, Var,
3884 /*FoundD=*/nullptr, TemplateArgs);
3887 ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
3888 SourceLocation TemplateKWLoc,
3891 const TemplateArgumentListInfo *TemplateArgs) {
3892 // FIXME: Can we do any checking at this point? I guess we could check the
3893 // template arguments that we have against the template name, if the template
3894 // name refers to a single template. That's not a terribly common case,
3896 // foo<int> could identify a single function unambiguously
3897 // This approach does NOT work, since f<int>(1);
3898 // gets resolved prior to resorting to overload resolution
3899 // i.e., template<class T> void f(double);
3900 // vs template<class T, class U> void f(U);
3902 // These should be filtered out by our callers.
3903 assert(!R.empty() && "empty lookup results when building templateid");
3904 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
3906 // In C++1y, check variable template ids.
3907 bool InstantiationDependent;
3908 if (R.getAsSingle<VarTemplateDecl>() &&
3909 !TemplateSpecializationType::anyDependentTemplateArguments(
3910 *TemplateArgs, InstantiationDependent)) {
3911 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
3912 R.getAsSingle<VarTemplateDecl>(),
3913 TemplateKWLoc, TemplateArgs);
3916 // We don't want lookup warnings at this point.
3917 R.suppressDiagnostics();
3919 UnresolvedLookupExpr *ULE
3920 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3921 SS.getWithLocInContext(Context),
3923 R.getLookupNameInfo(),
3924 RequiresADL, TemplateArgs,
3925 R.begin(), R.end());
3930 // We actually only call this from template instantiation.
3932 Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
3933 SourceLocation TemplateKWLoc,
3934 const DeclarationNameInfo &NameInfo,
3935 const TemplateArgumentListInfo *TemplateArgs) {
3937 assert(TemplateArgs || TemplateKWLoc.isValid());
3939 if (!(DC = computeDeclContext(SS, false)) ||
3940 DC->isDependentContext() ||
3941 RequireCompleteDeclContext(SS, DC))
3942 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
3944 bool MemberOfUnknownSpecialization;
3945 LookupResult R(*this, NameInfo, LookupOrdinaryName);
3946 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
3947 MemberOfUnknownSpecialization);
3949 if (R.isAmbiguous())
3953 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
3954 << NameInfo.getName() << SS.getRange();
3958 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
3959 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
3961 << NameInfo.getName().getAsString() << SS.getRange();
3962 Diag(Temp->getLocation(), diag::note_referenced_class_template);
3966 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
3969 /// \brief Form a dependent template name.
3971 /// This action forms a dependent template name given the template
3972 /// name and its (presumably dependent) scope specifier. For
3973 /// example, given "MetaFun::template apply", the scope specifier \p
3974 /// SS will be "MetaFun::", \p TemplateKWLoc contains the location
3975 /// of the "template" keyword, and "apply" is the \p Name.
3976 TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
3978 SourceLocation TemplateKWLoc,
3979 UnqualifiedId &Name,
3980 ParsedType ObjectType,
3981 bool EnteringContext,
3983 bool AllowInjectedClassName) {
3984 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
3986 getLangOpts().CPlusPlus11 ?
3987 diag::warn_cxx98_compat_template_outside_of_template :
3988 diag::ext_template_outside_of_template)
3989 << FixItHint::CreateRemoval(TemplateKWLoc);
3991 DeclContext *LookupCtx = nullptr;
3993 LookupCtx = computeDeclContext(SS, EnteringContext);
3994 if (!LookupCtx && ObjectType)
3995 LookupCtx = computeDeclContext(ObjectType.get());
3997 // C++0x [temp.names]p5:
3998 // If a name prefixed by the keyword template is not the name of
3999 // a template, the program is ill-formed. [Note: the keyword
4000 // template may not be applied to non-template members of class
4001 // templates. -end note ] [ Note: as is the case with the
4002 // typename prefix, the template prefix is allowed in cases
4003 // where it is not strictly necessary; i.e., when the
4004 // nested-name-specifier or the expression on the left of the ->
4005 // or . is not dependent on a template-parameter, or the use
4006 // does not appear in the scope of a template. -end note]
4008 // Note: C++03 was more strict here, because it banned the use of
4009 // the "template" keyword prior to a template-name that was not a
4010 // dependent name. C++ DR468 relaxed this requirement (the
4011 // "template" keyword is now permitted). We follow the C++0x
4012 // rules, even in C++03 mode with a warning, retroactively applying the DR.
4013 bool MemberOfUnknownSpecialization;
4014 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
4015 ObjectType, EnteringContext, Result,
4016 MemberOfUnknownSpecialization);
4017 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
4018 isa<CXXRecordDecl>(LookupCtx) &&
4019 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
4020 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
4021 // This is a dependent template. Handle it below.
4022 } else if (TNK == TNK_Non_template) {
4023 Diag(Name.getLocStart(),
4024 diag::err_template_kw_refers_to_non_template)
4025 << GetNameFromUnqualifiedId(Name).getName()
4026 << Name.getSourceRange()
4028 return TNK_Non_template;
4030 // We found something; return it.
4031 auto *LookupRD = dyn_cast<CXXRecordDecl>(LookupCtx);
4032 if (!AllowInjectedClassName && SS.isSet() && LookupRD &&
4033 Name.getKind() == UnqualifiedId::IK_Identifier && Name.Identifier &&
4034 LookupRD->getIdentifier() == Name.Identifier) {
4035 // C++14 [class.qual]p2:
4036 // In a lookup in which function names are not ignored and the
4037 // nested-name-specifier nominates a class C, if the name specified
4038 // [...] is the injected-class-name of C, [...] the name is instead
4039 // considered to name the constructor
4041 // We don't get here if naming the constructor would be valid, so we
4042 // just reject immediately and recover by treating the
4043 // injected-class-name as naming the template.
4044 Diag(Name.getLocStart(),
4045 diag::ext_out_of_line_qualified_id_type_names_constructor)
4046 << Name.Identifier << 0 /*injected-class-name used as template name*/
4047 << 1 /*'template' keyword was used*/;
4053 NestedNameSpecifier *Qualifier = SS.getScopeRep();
4055 switch (Name.getKind()) {
4056 case UnqualifiedId::IK_Identifier:
4057 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
4059 return TNK_Dependent_template_name;
4061 case UnqualifiedId::IK_OperatorFunctionId:
4062 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
4063 Name.OperatorFunctionId.Operator));
4064 return TNK_Function_template;
4066 case UnqualifiedId::IK_LiteralOperatorId:
4067 llvm_unreachable("literal operator id cannot have a dependent scope");
4073 Diag(Name.getLocStart(),
4074 diag::err_template_kw_refers_to_non_template)
4075 << GetNameFromUnqualifiedId(Name).getName()
4076 << Name.getSourceRange()
4078 return TNK_Non_template;
4081 bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
4082 TemplateArgumentLoc &AL,
4083 SmallVectorImpl<TemplateArgument> &Converted) {
4084 const TemplateArgument &Arg = AL.getArgument();
4086 TypeSourceInfo *TSI = nullptr;
4088 // Check template type parameter.
4089 switch(Arg.getKind()) {
4090 case TemplateArgument::Type:
4091 // C++ [temp.arg.type]p1:
4092 // A template-argument for a template-parameter which is a
4093 // type shall be a type-id.
4094 ArgType = Arg.getAsType();
4095 TSI = AL.getTypeSourceInfo();
4097 case TemplateArgument::Template: {
4098 // We have a template type parameter but the template argument
4099 // is a template without any arguments.
4100 SourceRange SR = AL.getSourceRange();
4101 TemplateName Name = Arg.getAsTemplate();
4102 Diag(SR.getBegin(), diag::err_template_missing_args)
4103 << (int)getTemplateNameKindForDiagnostics(Name) << Name << SR;
4104 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
4105 Diag(Decl->getLocation(), diag::note_template_decl_here);
4109 case TemplateArgument::Expression: {
4110 // We have a template type parameter but the template argument is an
4111 // expression; see if maybe it is missing the "typename" keyword.
4113 DeclarationNameInfo NameInfo;
4115 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
4116 SS.Adopt(ArgExpr->getQualifierLoc());
4117 NameInfo = ArgExpr->getNameInfo();
4118 } else if (DependentScopeDeclRefExpr *ArgExpr =
4119 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
4120 SS.Adopt(ArgExpr->getQualifierLoc());
4121 NameInfo = ArgExpr->getNameInfo();
4122 } else if (CXXDependentScopeMemberExpr *ArgExpr =
4123 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
4124 if (ArgExpr->isImplicitAccess()) {
4125 SS.Adopt(ArgExpr->getQualifierLoc());
4126 NameInfo = ArgExpr->getMemberNameInfo();
4130 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
4131 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
4132 LookupParsedName(Result, CurScope, &SS);
4134 if (Result.getAsSingle<TypeDecl>() ||
4135 Result.getResultKind() ==
4136 LookupResult::NotFoundInCurrentInstantiation) {
4137 // Suggest that the user add 'typename' before the NNS.
4138 SourceLocation Loc = AL.getSourceRange().getBegin();
4139 Diag(Loc, getLangOpts().MSVCCompat
4140 ? diag::ext_ms_template_type_arg_missing_typename
4141 : diag::err_template_arg_must_be_type_suggest)
4142 << FixItHint::CreateInsertion(Loc, "typename ");
4143 Diag(Param->getLocation(), diag::note_template_param_here);
4145 // Recover by synthesizing a type using the location information that we
4148 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
4150 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
4151 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
4152 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4153 TL.setNameLoc(NameInfo.getLoc());
4154 TSI = TLB.getTypeSourceInfo(Context, ArgType);
4156 // Overwrite our input TemplateArgumentLoc so that we can recover
4158 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
4159 TemplateArgumentLocInfo(TSI));
4168 // We have a template type parameter but the template argument
4170 SourceRange SR = AL.getSourceRange();
4171 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
4172 Diag(Param->getLocation(), diag::note_template_param_here);
4178 if (CheckTemplateArgument(Param, TSI))
4181 // Add the converted template type argument.
4182 ArgType = Context.getCanonicalType(ArgType);
4185 // If an explicitly-specified template argument type is a lifetime type
4186 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
4187 if (getLangOpts().ObjCAutoRefCount &&
4188 ArgType->isObjCLifetimeType() &&
4189 !ArgType.getObjCLifetime()) {
4191 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
4192 ArgType = Context.getQualifiedType(ArgType, Qs);
4195 Converted.push_back(TemplateArgument(ArgType));
4199 /// \brief Substitute template arguments into the default template argument for
4200 /// the given template type parameter.
4202 /// \param SemaRef the semantic analysis object for which we are performing
4203 /// the substitution.
4205 /// \param Template the template that we are synthesizing template arguments
4208 /// \param TemplateLoc the location of the template name that started the
4209 /// template-id we are checking.
4211 /// \param RAngleLoc the location of the right angle bracket ('>') that
4212 /// terminates the template-id.
4214 /// \param Param the template template parameter whose default we are
4215 /// substituting into.
4217 /// \param Converted the list of template arguments provided for template
4218 /// parameters that precede \p Param in the template parameter list.
4219 /// \returns the substituted template argument, or NULL if an error occurred.
4220 static TypeSourceInfo *
4221 SubstDefaultTemplateArgument(Sema &SemaRef,
4222 TemplateDecl *Template,
4223 SourceLocation TemplateLoc,
4224 SourceLocation RAngleLoc,
4225 TemplateTypeParmDecl *Param,
4226 SmallVectorImpl<TemplateArgument> &Converted) {
4227 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
4229 // If the argument type is dependent, instantiate it now based
4230 // on the previously-computed template arguments.
4231 if (ArgType->getType()->isDependentType()) {
4232 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
4233 Param, Template, Converted,
4234 SourceRange(TemplateLoc, RAngleLoc));
4235 if (Inst.isInvalid())
4238 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4240 // Only substitute for the innermost template argument list.
4241 MultiLevelTemplateArgumentList TemplateArgLists;
4242 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4243 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4244 TemplateArgLists.addOuterTemplateArguments(None);
4246 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4248 SemaRef.SubstType(ArgType, TemplateArgLists,
4249 Param->getDefaultArgumentLoc(), Param->getDeclName());
4255 /// \brief Substitute template arguments into the default template argument for
4256 /// the given non-type template parameter.
4258 /// \param SemaRef the semantic analysis object for which we are performing
4259 /// the substitution.
4261 /// \param Template the template that we are synthesizing template arguments
4264 /// \param TemplateLoc the location of the template name that started the
4265 /// template-id we are checking.
4267 /// \param RAngleLoc the location of the right angle bracket ('>') that
4268 /// terminates the template-id.
4270 /// \param Param the non-type template parameter whose default we are
4271 /// substituting into.
4273 /// \param Converted the list of template arguments provided for template
4274 /// parameters that precede \p Param in the template parameter list.
4276 /// \returns the substituted template argument, or NULL if an error occurred.
4278 SubstDefaultTemplateArgument(Sema &SemaRef,
4279 TemplateDecl *Template,
4280 SourceLocation TemplateLoc,
4281 SourceLocation RAngleLoc,
4282 NonTypeTemplateParmDecl *Param,
4283 SmallVectorImpl<TemplateArgument> &Converted) {
4284 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
4285 Param, Template, Converted,
4286 SourceRange(TemplateLoc, RAngleLoc));
4287 if (Inst.isInvalid())
4290 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4292 // Only substitute for the innermost template argument list.
4293 MultiLevelTemplateArgumentList TemplateArgLists;
4294 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4295 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4296 TemplateArgLists.addOuterTemplateArguments(None);
4298 EnterExpressionEvaluationContext ConstantEvaluated(
4299 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4300 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
4303 /// \brief Substitute template arguments into the default template argument for
4304 /// the given template template parameter.
4306 /// \param SemaRef the semantic analysis object for which we are performing
4307 /// the substitution.
4309 /// \param Template the template that we are synthesizing template arguments
4312 /// \param TemplateLoc the location of the template name that started the
4313 /// template-id we are checking.
4315 /// \param RAngleLoc the location of the right angle bracket ('>') that
4316 /// terminates the template-id.
4318 /// \param Param the template template parameter whose default we are
4319 /// substituting into.
4321 /// \param Converted the list of template arguments provided for template
4322 /// parameters that precede \p Param in the template parameter list.
4324 /// \param QualifierLoc Will be set to the nested-name-specifier (with
4325 /// source-location information) that precedes the template name.
4327 /// \returns the substituted template argument, or NULL if an error occurred.
4329 SubstDefaultTemplateArgument(Sema &SemaRef,
4330 TemplateDecl *Template,
4331 SourceLocation TemplateLoc,
4332 SourceLocation RAngleLoc,
4333 TemplateTemplateParmDecl *Param,
4334 SmallVectorImpl<TemplateArgument> &Converted,
4335 NestedNameSpecifierLoc &QualifierLoc) {
4336 Sema::InstantiatingTemplate Inst(
4337 SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
4338 SourceRange(TemplateLoc, RAngleLoc));
4339 if (Inst.isInvalid())
4340 return TemplateName();
4342 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4344 // Only substitute for the innermost template argument list.
4345 MultiLevelTemplateArgumentList TemplateArgLists;
4346 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4347 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4348 TemplateArgLists.addOuterTemplateArguments(None);
4350 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4351 // Substitute into the nested-name-specifier first,
4352 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
4355 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
4357 return TemplateName();
4360 return SemaRef.SubstTemplateName(
4362 Param->getDefaultArgument().getArgument().getAsTemplate(),
4363 Param->getDefaultArgument().getTemplateNameLoc(),
4367 /// \brief If the given template parameter has a default template
4368 /// argument, substitute into that default template argument and
4369 /// return the corresponding template argument.
4371 Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
4372 SourceLocation TemplateLoc,
4373 SourceLocation RAngleLoc,
4375 SmallVectorImpl<TemplateArgument>
4377 bool &HasDefaultArg) {
4378 HasDefaultArg = false;
4380 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
4381 if (!hasVisibleDefaultArgument(TypeParm))
4382 return TemplateArgumentLoc();
4384 HasDefaultArg = true;
4385 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
4391 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4393 return TemplateArgumentLoc();
4396 if (NonTypeTemplateParmDecl *NonTypeParm
4397 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4398 if (!hasVisibleDefaultArgument(NonTypeParm))
4399 return TemplateArgumentLoc();
4401 HasDefaultArg = true;
4402 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
4407 if (Arg.isInvalid())
4408 return TemplateArgumentLoc();
4410 Expr *ArgE = Arg.getAs<Expr>();
4411 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
4414 TemplateTemplateParmDecl *TempTempParm
4415 = cast<TemplateTemplateParmDecl>(Param);
4416 if (!hasVisibleDefaultArgument(TempTempParm))
4417 return TemplateArgumentLoc();
4419 HasDefaultArg = true;
4420 NestedNameSpecifierLoc QualifierLoc;
4421 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
4428 return TemplateArgumentLoc();
4430 return TemplateArgumentLoc(TemplateArgument(TName),
4431 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
4432 TempTempParm->getDefaultArgument().getTemplateNameLoc());
4435 /// Convert a template-argument that we parsed as a type into a template, if
4436 /// possible. C++ permits injected-class-names to perform dual service as
4437 /// template template arguments and as template type arguments.
4438 static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(TypeLoc TLoc) {
4439 // Extract and step over any surrounding nested-name-specifier.
4440 NestedNameSpecifierLoc QualLoc;
4441 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
4442 if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
4443 return TemplateArgumentLoc();
4445 QualLoc = ETLoc.getQualifierLoc();
4446 TLoc = ETLoc.getNamedTypeLoc();
4449 // If this type was written as an injected-class-name, it can be used as a
4450 // template template argument.
4451 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
4452 return TemplateArgumentLoc(InjLoc.getTypePtr()->getTemplateName(),
4453 QualLoc, InjLoc.getNameLoc());
4455 // If this type was written as an injected-class-name, it may have been
4456 // converted to a RecordType during instantiation. If the RecordType is
4457 // *not* wrapped in a TemplateSpecializationType and denotes a class
4458 // template specialization, it must have come from an injected-class-name.
4459 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
4461 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
4462 return TemplateArgumentLoc(TemplateName(CTSD->getSpecializedTemplate()),
4463 QualLoc, RecLoc.getNameLoc());
4465 return TemplateArgumentLoc();
4468 /// \brief Check that the given template argument corresponds to the given
4469 /// template parameter.
4471 /// \param Param The template parameter against which the argument will be
4474 /// \param Arg The template argument, which may be updated due to conversions.
4476 /// \param Template The template in which the template argument resides.
4478 /// \param TemplateLoc The location of the template name for the template
4479 /// whose argument list we're matching.
4481 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
4482 /// the template argument list.
4484 /// \param ArgumentPackIndex The index into the argument pack where this
4485 /// argument will be placed. Only valid if the parameter is a parameter pack.
4487 /// \param Converted The checked, converted argument will be added to the
4488 /// end of this small vector.
4490 /// \param CTAK Describes how we arrived at this particular template argument:
4491 /// explicitly written, deduced, etc.
4493 /// \returns true on error, false otherwise.
4494 bool Sema::CheckTemplateArgument(NamedDecl *Param,
4495 TemplateArgumentLoc &Arg,
4496 NamedDecl *Template,
4497 SourceLocation TemplateLoc,
4498 SourceLocation RAngleLoc,
4499 unsigned ArgumentPackIndex,
4500 SmallVectorImpl<TemplateArgument> &Converted,
4501 CheckTemplateArgumentKind CTAK) {
4502 // Check template type parameters.
4503 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4504 return CheckTemplateTypeArgument(TTP, Arg, Converted);
4506 // Check non-type template parameters.
4507 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4508 // Do substitution on the type of the non-type template parameter
4509 // with the template arguments we've seen thus far. But if the
4510 // template has a dependent context then we cannot substitute yet.
4511 QualType NTTPType = NTTP->getType();
4512 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
4513 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
4515 if (NTTPType->isDependentType() &&
4516 !isa<TemplateTemplateParmDecl>(Template) &&
4517 !Template->getDeclContext()->isDependentContext()) {
4518 // Do substitution on the type of the non-type template parameter.
4519 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
4521 SourceRange(TemplateLoc, RAngleLoc));
4522 if (Inst.isInvalid())
4525 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
4527 NTTPType = SubstType(NTTPType,
4528 MultiLevelTemplateArgumentList(TemplateArgs),
4529 NTTP->getLocation(),
4530 NTTP->getDeclName());
4531 // If that worked, check the non-type template parameter type
4533 if (!NTTPType.isNull())
4534 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
4535 NTTP->getLocation());
4536 if (NTTPType.isNull())
4540 switch (Arg.getArgument().getKind()) {
4541 case TemplateArgument::Null:
4542 llvm_unreachable("Should never see a NULL template argument here");
4544 case TemplateArgument::Expression: {
4545 TemplateArgument Result;
4547 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
4549 if (Res.isInvalid())
4552 // If the resulting expression is new, then use it in place of the
4553 // old expression in the template argument.
4554 if (Res.get() != Arg.getArgument().getAsExpr()) {
4555 TemplateArgument TA(Res.get());
4556 Arg = TemplateArgumentLoc(TA, Res.get());
4559 Converted.push_back(Result);
4563 case TemplateArgument::Declaration:
4564 case TemplateArgument::Integral:
4565 case TemplateArgument::NullPtr:
4566 // We've already checked this template argument, so just copy
4567 // it to the list of converted arguments.
4568 Converted.push_back(Arg.getArgument());
4571 case TemplateArgument::Template:
4572 case TemplateArgument::TemplateExpansion:
4573 // We were given a template template argument. It may not be ill-formed;
4575 if (DependentTemplateName *DTN
4576 = Arg.getArgument().getAsTemplateOrTemplatePattern()
4577 .getAsDependentTemplateName()) {
4578 // We have a template argument such as \c T::template X, which we
4579 // parsed as a template template argument. However, since we now
4580 // know that we need a non-type template argument, convert this
4581 // template name into an expression.
4583 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
4584 Arg.getTemplateNameLoc());
4587 SS.Adopt(Arg.getTemplateQualifierLoc());
4588 // FIXME: the template-template arg was a DependentTemplateName,
4589 // so it was provided with a template keyword. However, its source
4590 // location is not stored in the template argument structure.
4591 SourceLocation TemplateKWLoc;
4592 ExprResult E = DependentScopeDeclRefExpr::Create(
4593 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
4596 // If we parsed the template argument as a pack expansion, create a
4597 // pack expansion expression.
4598 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
4599 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
4604 TemplateArgument Result;
4605 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
4609 Converted.push_back(Result);
4613 // We have a template argument that actually does refer to a class
4614 // template, alias template, or template template parameter, and
4615 // therefore cannot be a non-type template argument.
4616 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
4617 << Arg.getSourceRange();
4619 Diag(Param->getLocation(), diag::note_template_param_here);
4622 case TemplateArgument::Type: {
4623 // We have a non-type template parameter but the template
4624 // argument is a type.
4626 // C++ [temp.arg]p2:
4627 // In a template-argument, an ambiguity between a type-id and
4628 // an expression is resolved to a type-id, regardless of the
4629 // form of the corresponding template-parameter.
4631 // We warn specifically about this case, since it can be rather
4632 // confusing for users.
4633 QualType T = Arg.getArgument().getAsType();
4634 SourceRange SR = Arg.getSourceRange();
4635 if (T->isFunctionType())
4636 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
4638 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
4639 Diag(Param->getLocation(), diag::note_template_param_here);
4643 case TemplateArgument::Pack:
4644 llvm_unreachable("Caller must expand template argument packs");
4651 // Check template template parameters.
4652 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
4654 // Substitute into the template parameter list of the template
4655 // template parameter, since previously-supplied template arguments
4656 // may appear within the template template parameter.
4658 // Set up a template instantiation context.
4659 LocalInstantiationScope Scope(*this);
4660 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
4661 TempParm, Converted,
4662 SourceRange(TemplateLoc, RAngleLoc));
4663 if (Inst.isInvalid())
4666 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4667 TempParm = cast_or_null<TemplateTemplateParmDecl>(
4668 SubstDecl(TempParm, CurContext,
4669 MultiLevelTemplateArgumentList(TemplateArgs)));
4674 // C++1z [temp.local]p1: (DR1004)
4675 // When [the injected-class-name] is used [...] as a template-argument for
4676 // a template template-parameter [...] it refers to the class template
4678 if (Arg.getArgument().getKind() == TemplateArgument::Type) {
4679 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
4680 Arg.getTypeSourceInfo()->getTypeLoc());
4681 if (!ConvertedArg.getArgument().isNull())
4685 switch (Arg.getArgument().getKind()) {
4686 case TemplateArgument::Null:
4687 llvm_unreachable("Should never see a NULL template argument here");
4689 case TemplateArgument::Template:
4690 case TemplateArgument::TemplateExpansion:
4691 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
4694 Converted.push_back(Arg.getArgument());
4697 case TemplateArgument::Expression:
4698 case TemplateArgument::Type:
4699 // We have a template template parameter but the template
4700 // argument does not refer to a template.
4701 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
4702 << getLangOpts().CPlusPlus11;
4705 case TemplateArgument::Declaration:
4706 llvm_unreachable("Declaration argument with template template parameter");
4707 case TemplateArgument::Integral:
4708 llvm_unreachable("Integral argument with template template parameter");
4709 case TemplateArgument::NullPtr:
4710 llvm_unreachable("Null pointer argument with template template parameter");
4712 case TemplateArgument::Pack:
4713 llvm_unreachable("Caller must expand template argument packs");
4719 /// \brief Diagnose an arity mismatch in the
4720 static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
4721 SourceLocation TemplateLoc,
4722 TemplateArgumentListInfo &TemplateArgs) {
4723 TemplateParameterList *Params = Template->getTemplateParameters();
4724 unsigned NumParams = Params->size();
4725 unsigned NumArgs = TemplateArgs.size();
4728 if (NumArgs > NumParams)
4729 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
4730 TemplateArgs.getRAngleLoc());
4731 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
4732 << (NumArgs > NumParams)
4733 << (int)S.getTemplateNameKindForDiagnostics(TemplateName(Template))
4734 << Template << Range;
4735 S.Diag(Template->getLocation(), diag::note_template_decl_here)
4736 << Params->getSourceRange();
4740 /// \brief Check whether the template parameter is a pack expansion, and if so,
4741 /// determine the number of parameters produced by that expansion. For instance:
4744 /// template<typename ...Ts> struct A {
4745 /// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
4749 /// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
4750 /// is not a pack expansion, so returns an empty Optional.
4751 static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
4752 if (NonTypeTemplateParmDecl *NTTP
4753 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4754 if (NTTP->isExpandedParameterPack())
4755 return NTTP->getNumExpansionTypes();
4758 if (TemplateTemplateParmDecl *TTP
4759 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
4760 if (TTP->isExpandedParameterPack())
4761 return TTP->getNumExpansionTemplateParameters();
4767 /// Diagnose a missing template argument.
4768 template<typename TemplateParmDecl>
4769 static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
4771 const TemplateParmDecl *D,
4772 TemplateArgumentListInfo &Args) {
4773 // Dig out the most recent declaration of the template parameter; there may be
4774 // declarations of the template that are more recent than TD.
4775 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
4776 ->getTemplateParameters()
4777 ->getParam(D->getIndex()));
4779 // If there's a default argument that's not visible, diagnose that we're
4780 // missing a module import.
4781 llvm::SmallVector<Module*, 8> Modules;
4782 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
4783 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
4784 D->getDefaultArgumentLoc(), Modules,
4785 Sema::MissingImportKind::DefaultArgument,
4790 // FIXME: If there's a more recent default argument that *is* visible,
4791 // diagnose that it was declared too late.
4793 return diagnoseArityMismatch(S, TD, Loc, Args);
4796 /// \brief Check that the given template argument list is well-formed
4797 /// for specializing the given template.
4798 bool Sema::CheckTemplateArgumentList(
4799 TemplateDecl *Template, SourceLocation TemplateLoc,
4800 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
4801 SmallVectorImpl<TemplateArgument> &Converted,
4802 bool UpdateArgsWithConversions) {
4803 // Make a copy of the template arguments for processing. Only make the
4804 // changes at the end when successful in matching the arguments to the
4806 TemplateArgumentListInfo NewArgs = TemplateArgs;
4808 // Make sure we get the template parameter list from the most
4809 // recentdeclaration, since that is the only one that has is guaranteed to
4810 // have all the default template argument information.
4811 TemplateParameterList *Params =
4812 cast<TemplateDecl>(Template->getMostRecentDecl())
4813 ->getTemplateParameters();
4815 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
4817 // C++ [temp.arg]p1:
4818 // [...] The type and form of each template-argument specified in
4819 // a template-id shall match the type and form specified for the
4820 // corresponding parameter declared by the template in its
4821 // template-parameter-list.
4822 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
4823 SmallVector<TemplateArgument, 2> ArgumentPack;
4824 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
4825 LocalInstantiationScope InstScope(*this, true);
4826 for (TemplateParameterList::iterator Param = Params->begin(),
4827 ParamEnd = Params->end();
4828 Param != ParamEnd; /* increment in loop */) {
4829 // If we have an expanded parameter pack, make sure we don't have too
4831 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
4832 if (*Expansions == ArgumentPack.size()) {
4833 // We're done with this parameter pack. Pack up its arguments and add
4834 // them to the list.
4835 Converted.push_back(
4836 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4837 ArgumentPack.clear();
4839 // This argument is assigned to the next parameter.
4842 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
4843 // Not enough arguments for this parameter pack.
4844 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
4846 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
4848 Diag(Template->getLocation(), diag::note_template_decl_here)
4849 << Params->getSourceRange();
4854 if (ArgIdx < NumArgs) {
4855 // Check the template argument we were given.
4856 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
4857 TemplateLoc, RAngleLoc,
4858 ArgumentPack.size(), Converted))
4861 bool PackExpansionIntoNonPack =
4862 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
4863 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
4864 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
4865 // Core issue 1430: we have a pack expansion as an argument to an
4866 // alias template, and it's not part of a parameter pack. This
4867 // can't be canonicalized, so reject it now.
4868 Diag(NewArgs[ArgIdx].getLocation(),
4869 diag::err_alias_template_expansion_into_fixed_list)
4870 << NewArgs[ArgIdx].getSourceRange();
4871 Diag((*Param)->getLocation(), diag::note_template_param_here);
4875 // We're now done with this argument.
4878 if ((*Param)->isTemplateParameterPack()) {
4879 // The template parameter was a template parameter pack, so take the
4880 // deduced argument and place it on the argument pack. Note that we
4881 // stay on the same template parameter so that we can deduce more
4883 ArgumentPack.push_back(Converted.pop_back_val());
4885 // Move to the next template parameter.
4889 // If we just saw a pack expansion into a non-pack, then directly convert
4890 // the remaining arguments, because we don't know what parameters they'll
4892 if (PackExpansionIntoNonPack) {
4893 if (!ArgumentPack.empty()) {
4894 // If we were part way through filling in an expanded parameter pack,
4895 // fall back to just producing individual arguments.
4896 Converted.insert(Converted.end(),
4897 ArgumentPack.begin(), ArgumentPack.end());
4898 ArgumentPack.clear();
4901 while (ArgIdx < NumArgs) {
4902 Converted.push_back(NewArgs[ArgIdx].getArgument());
4912 // If we're checking a partial template argument list, we're done.
4913 if (PartialTemplateArgs) {
4914 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
4915 Converted.push_back(
4916 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4921 // If we have a template parameter pack with no more corresponding
4922 // arguments, just break out now and we'll fill in the argument pack below.
4923 if ((*Param)->isTemplateParameterPack()) {
4924 assert(!getExpandedPackSize(*Param) &&
4925 "Should have dealt with this already");
4927 // A non-expanded parameter pack before the end of the parameter list
4928 // only occurs for an ill-formed template parameter list, unless we've
4929 // got a partial argument list for a function template, so just bail out.
4930 if (Param + 1 != ParamEnd)
4933 Converted.push_back(
4934 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4935 ArgumentPack.clear();
4941 // Check whether we have a default argument.
4942 TemplateArgumentLoc Arg;
4944 // Retrieve the default template argument from the template
4945 // parameter. For each kind of template parameter, we substitute the
4946 // template arguments provided thus far and any "outer" template arguments
4947 // (when the template parameter was part of a nested template) into
4948 // the default argument.
4949 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
4950 if (!hasVisibleDefaultArgument(TTP))
4951 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
4954 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
4963 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
4965 } else if (NonTypeTemplateParmDecl *NTTP
4966 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
4967 if (!hasVisibleDefaultArgument(NTTP))
4968 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
4971 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
4979 Expr *Ex = E.getAs<Expr>();
4980 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
4982 TemplateTemplateParmDecl *TempParm
4983 = cast<TemplateTemplateParmDecl>(*Param);
4985 if (!hasVisibleDefaultArgument(TempParm))
4986 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
4989 NestedNameSpecifierLoc QualifierLoc;
4990 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
4999 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
5000 TempParm->getDefaultArgument().getTemplateNameLoc());
5003 // Introduce an instantiation record that describes where we are using
5004 // the default template argument. We're not actually instantiating a
5005 // template here, we just create this object to put a note into the
5007 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
5008 SourceRange(TemplateLoc, RAngleLoc));
5009 if (Inst.isInvalid())
5012 // Check the default template argument.
5013 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
5014 RAngleLoc, 0, Converted))
5017 // Core issue 150 (assumed resolution): if this is a template template
5018 // parameter, keep track of the default template arguments from the
5019 // template definition.
5020 if (isTemplateTemplateParameter)
5021 NewArgs.addArgument(Arg);
5023 // Move to the next template parameter and argument.
5028 // If we're performing a partial argument substitution, allow any trailing
5029 // pack expansions; they might be empty. This can happen even if
5030 // PartialTemplateArgs is false (the list of arguments is complete but
5031 // still dependent).
5032 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
5033 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
5034 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
5035 Converted.push_back(NewArgs[ArgIdx++].getArgument());
5038 // If we have any leftover arguments, then there were too many arguments.
5039 // Complain and fail.
5040 if (ArgIdx < NumArgs)
5041 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
5043 // No problems found with the new argument list, propagate changes back
5045 if (UpdateArgsWithConversions)
5046 TemplateArgs = std::move(NewArgs);
5052 class UnnamedLocalNoLinkageFinder
5053 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
5058 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
5061 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
5063 bool Visit(QualType T) {
5064 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
5067 #define TYPE(Class, Parent) \
5068 bool Visit##Class##Type(const Class##Type *);
5069 #define ABSTRACT_TYPE(Class, Parent) \
5070 bool Visit##Class##Type(const Class##Type *) { return false; }
5071 #define NON_CANONICAL_TYPE(Class, Parent) \
5072 bool Visit##Class##Type(const Class##Type *) { return false; }
5073 #include "clang/AST/TypeNodes.def"
5075 bool VisitTagDecl(const TagDecl *Tag);
5076 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
5078 } // end anonymous namespace
5080 bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
5084 bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
5085 return Visit(T->getElementType());
5088 bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
5089 return Visit(T->getPointeeType());
5092 bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
5093 const BlockPointerType* T) {
5094 return Visit(T->getPointeeType());
5097 bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
5098 const LValueReferenceType* T) {
5099 return Visit(T->getPointeeType());
5102 bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
5103 const RValueReferenceType* T) {
5104 return Visit(T->getPointeeType());
5107 bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
5108 const MemberPointerType* T) {
5109 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
5112 bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
5113 const ConstantArrayType* T) {
5114 return Visit(T->getElementType());
5117 bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
5118 const IncompleteArrayType* T) {
5119 return Visit(T->getElementType());
5122 bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
5123 const VariableArrayType* T) {
5124 return Visit(T->getElementType());
5127 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
5128 const DependentSizedArrayType* T) {
5129 return Visit(T->getElementType());
5132 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
5133 const DependentSizedExtVectorType* T) {
5134 return Visit(T->getElementType());
5137 bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
5138 const DependentAddressSpaceType *T) {
5139 return Visit(T->getPointeeType());
5142 bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
5143 return Visit(T->getElementType());
5146 bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
5147 return Visit(T->getElementType());
5150 bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
5151 const FunctionProtoType* T) {
5152 for (const auto &A : T->param_types()) {
5157 return Visit(T->getReturnType());
5160 bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
5161 const FunctionNoProtoType* T) {
5162 return Visit(T->getReturnType());
5165 bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
5166 const UnresolvedUsingType*) {
5170 bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
5174 bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
5175 return Visit(T->getUnderlyingType());
5178 bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
5182 bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
5183 const UnaryTransformType*) {
5187 bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
5188 return Visit(T->getDeducedType());
5191 bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
5192 const DeducedTemplateSpecializationType *T) {
5193 return Visit(T->getDeducedType());
5196 bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
5197 return VisitTagDecl(T->getDecl());
5200 bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
5201 return VisitTagDecl(T->getDecl());
5204 bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
5205 const TemplateTypeParmType*) {
5209 bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
5210 const SubstTemplateTypeParmPackType *) {
5214 bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
5215 const TemplateSpecializationType*) {
5219 bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
5220 const InjectedClassNameType* T) {
5221 return VisitTagDecl(T->getDecl());
5224 bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
5225 const DependentNameType* T) {
5226 return VisitNestedNameSpecifier(T->getQualifier());
5229 bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
5230 const DependentTemplateSpecializationType* T) {
5231 return VisitNestedNameSpecifier(T->getQualifier());
5234 bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
5235 const PackExpansionType* T) {
5236 return Visit(T->getPattern());
5239 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
5243 bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
5244 const ObjCInterfaceType *) {
5248 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
5249 const ObjCObjectPointerType *) {
5253 bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
5254 return Visit(T->getValueType());
5257 bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
5261 bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
5262 if (Tag->getDeclContext()->isFunctionOrMethod()) {
5263 S.Diag(SR.getBegin(),
5264 S.getLangOpts().CPlusPlus11 ?
5265 diag::warn_cxx98_compat_template_arg_local_type :
5266 diag::ext_template_arg_local_type)
5267 << S.Context.getTypeDeclType(Tag) << SR;
5271 if (!Tag->hasNameForLinkage()) {
5272 S.Diag(SR.getBegin(),
5273 S.getLangOpts().CPlusPlus11 ?
5274 diag::warn_cxx98_compat_template_arg_unnamed_type :
5275 diag::ext_template_arg_unnamed_type) << SR;
5276 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
5283 bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
5284 NestedNameSpecifier *NNS) {
5285 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
5288 switch (NNS->getKind()) {
5289 case NestedNameSpecifier::Identifier:
5290 case NestedNameSpecifier::Namespace:
5291 case NestedNameSpecifier::NamespaceAlias:
5292 case NestedNameSpecifier::Global:
5293 case NestedNameSpecifier::Super:
5296 case NestedNameSpecifier::TypeSpec:
5297 case NestedNameSpecifier::TypeSpecWithTemplate:
5298 return Visit(QualType(NNS->getAsType(), 0));
5300 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
5303 /// \brief Check a template argument against its corresponding
5304 /// template type parameter.
5306 /// This routine implements the semantics of C++ [temp.arg.type]. It
5307 /// returns true if an error occurred, and false otherwise.
5308 bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
5309 TypeSourceInfo *ArgInfo) {
5310 assert(ArgInfo && "invalid TypeSourceInfo");
5311 QualType Arg = ArgInfo->getType();
5312 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
5314 if (Arg->isVariablyModifiedType()) {
5315 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
5316 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
5317 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
5320 // C++03 [temp.arg.type]p2:
5321 // A local type, a type with no linkage, an unnamed type or a type
5322 // compounded from any of these types shall not be used as a
5323 // template-argument for a template type-parameter.
5325 // C++11 allows these, and even in C++03 we allow them as an extension with
5327 if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) {
5328 UnnamedLocalNoLinkageFinder Finder(*this, SR);
5329 (void)Finder.Visit(Context.getCanonicalType(Arg));
5335 enum NullPointerValueKind {
5341 /// \brief Determine whether the given template argument is a null pointer
5342 /// value of the appropriate type.
5343 static NullPointerValueKind
5344 isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
5345 QualType ParamType, Expr *Arg,
5346 Decl *Entity = nullptr) {
5347 if (Arg->isValueDependent() || Arg->isTypeDependent())
5348 return NPV_NotNullPointer;
5350 // dllimport'd entities aren't constant but are available inside of template
5352 if (Entity && Entity->hasAttr<DLLImportAttr>())
5353 return NPV_NotNullPointer;
5355 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
5357 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
5359 if (!S.getLangOpts().CPlusPlus11)
5360 return NPV_NotNullPointer;
5362 // Determine whether we have a constant expression.
5363 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
5364 if (ArgRV.isInvalid())
5368 Expr::EvalResult EvalResult;
5369 SmallVector<PartialDiagnosticAt, 8> Notes;
5370 EvalResult.Diag = &Notes;
5371 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
5372 EvalResult.HasSideEffects) {
5373 SourceLocation DiagLoc = Arg->getExprLoc();
5375 // If our only note is the usual "invalid subexpression" note, just point
5376 // the caret at its location rather than producing an essentially
5378 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
5379 diag::note_invalid_subexpr_in_const_expr) {
5380 DiagLoc = Notes[0].first;
5384 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
5385 << Arg->getType() << Arg->getSourceRange();
5386 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
5387 S.Diag(Notes[I].first, Notes[I].second);
5389 S.Diag(Param->getLocation(), diag::note_template_param_here);
5393 // C++11 [temp.arg.nontype]p1:
5394 // - an address constant expression of type std::nullptr_t
5395 if (Arg->getType()->isNullPtrType())
5396 return NPV_NullPointer;
5398 // - a constant expression that evaluates to a null pointer value (4.10); or
5399 // - a constant expression that evaluates to a null member pointer value
5401 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
5402 (EvalResult.Val.isMemberPointer() &&
5403 !EvalResult.Val.getMemberPointerDecl())) {
5404 // If our expression has an appropriate type, we've succeeded.
5405 bool ObjCLifetimeConversion;
5406 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
5407 S.IsQualificationConversion(Arg->getType(), ParamType, false,
5408 ObjCLifetimeConversion))
5409 return NPV_NullPointer;
5411 // The types didn't match, but we know we got a null pointer; complain,
5412 // then recover as if the types were correct.
5413 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
5414 << Arg->getType() << ParamType << Arg->getSourceRange();
5415 S.Diag(Param->getLocation(), diag::note_template_param_here);
5416 return NPV_NullPointer;
5419 // If we don't have a null pointer value, but we do have a NULL pointer
5420 // constant, suggest a cast to the appropriate type.
5421 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
5422 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
5423 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
5424 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
5425 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
5427 S.Diag(Param->getLocation(), diag::note_template_param_here);
5428 return NPV_NullPointer;
5431 // FIXME: If we ever want to support general, address-constant expressions
5432 // as non-type template arguments, we should return the ExprResult here to
5433 // be interpreted by the caller.
5434 return NPV_NotNullPointer;
5437 /// \brief Checks whether the given template argument is compatible with its
5438 /// template parameter.
5439 static bool CheckTemplateArgumentIsCompatibleWithParameter(
5440 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
5441 Expr *Arg, QualType ArgType) {
5442 bool ObjCLifetimeConversion;
5443 if (ParamType->isPointerType() &&
5444 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
5445 S.IsQualificationConversion(ArgType, ParamType, false,
5446 ObjCLifetimeConversion)) {
5447 // For pointer-to-object types, qualification conversions are
5450 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
5451 if (!ParamRef->getPointeeType()->isFunctionType()) {
5452 // C++ [temp.arg.nontype]p5b3:
5453 // For a non-type template-parameter of type reference to
5454 // object, no conversions apply. The type referred to by the
5455 // reference may be more cv-qualified than the (otherwise
5456 // identical) type of the template- argument. The
5457 // template-parameter is bound directly to the
5458 // template-argument, which shall be an lvalue.
5460 // FIXME: Other qualifiers?
5461 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
5462 unsigned ArgQuals = ArgType.getCVRQualifiers();
5464 if ((ParamQuals | ArgQuals) != ParamQuals) {
5465 S.Diag(Arg->getLocStart(),
5466 diag::err_template_arg_ref_bind_ignores_quals)
5467 << ParamType << Arg->getType() << Arg->getSourceRange();
5468 S.Diag(Param->getLocation(), diag::note_template_param_here);
5474 // At this point, the template argument refers to an object or
5475 // function with external linkage. We now need to check whether the
5476 // argument and parameter types are compatible.
5477 if (!S.Context.hasSameUnqualifiedType(ArgType,
5478 ParamType.getNonReferenceType())) {
5479 // We can't perform this conversion or binding.
5480 if (ParamType->isReferenceType())
5481 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
5482 << ParamType << ArgIn->getType() << Arg->getSourceRange();
5484 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
5485 << ArgIn->getType() << ParamType << Arg->getSourceRange();
5486 S.Diag(Param->getLocation(), diag::note_template_param_here);
5494 /// \brief Checks whether the given template argument is the address
5495 /// of an object or function according to C++ [temp.arg.nontype]p1.
5497 CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
5498 NonTypeTemplateParmDecl *Param,
5501 TemplateArgument &Converted) {
5502 bool Invalid = false;
5504 QualType ArgType = Arg->getType();
5506 bool AddressTaken = false;
5507 SourceLocation AddrOpLoc;
5508 if (S.getLangOpts().MicrosoftExt) {
5509 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
5510 // dereference and address-of operators.
5511 Arg = Arg->IgnoreParenCasts();
5513 bool ExtWarnMSTemplateArg = false;
5514 UnaryOperatorKind FirstOpKind;
5515 SourceLocation FirstOpLoc;
5516 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5517 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
5518 if (UnOpKind == UO_Deref)
5519 ExtWarnMSTemplateArg = true;
5520 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
5521 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
5522 if (!AddrOpLoc.isValid()) {
5523 FirstOpKind = UnOpKind;
5524 FirstOpLoc = UnOp->getOperatorLoc();
5529 if (FirstOpLoc.isValid()) {
5530 if (ExtWarnMSTemplateArg)
5531 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
5532 << ArgIn->getSourceRange();
5534 if (FirstOpKind == UO_AddrOf)
5535 AddressTaken = true;
5536 else if (Arg->getType()->isPointerType()) {
5537 // We cannot let pointers get dereferenced here, that is obviously not a
5538 // constant expression.
5539 assert(FirstOpKind == UO_Deref);
5540 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5541 << Arg->getSourceRange();
5545 // See through any implicit casts we added to fix the type.
5546 Arg = Arg->IgnoreImpCasts();
5548 // C++ [temp.arg.nontype]p1:
5550 // A template-argument for a non-type, non-template
5551 // template-parameter shall be one of: [...]
5553 // -- the address of an object or function with external
5554 // linkage, including function templates and function
5555 // template-ids but excluding non-static class members,
5556 // expressed as & id-expression where the & is optional if
5557 // the name refers to a function or array, or if the
5558 // corresponding template-parameter is a reference; or
5560 // In C++98/03 mode, give an extension warning on any extra parentheses.
5561 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5562 bool ExtraParens = false;
5563 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
5564 if (!Invalid && !ExtraParens) {
5565 S.Diag(Arg->getLocStart(),
5566 S.getLangOpts().CPlusPlus11
5567 ? diag::warn_cxx98_compat_template_arg_extra_parens
5568 : diag::ext_template_arg_extra_parens)
5569 << Arg->getSourceRange();
5573 Arg = Parens->getSubExpr();
5576 while (SubstNonTypeTemplateParmExpr *subst =
5577 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5578 Arg = subst->getReplacement()->IgnoreImpCasts();
5580 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5581 if (UnOp->getOpcode() == UO_AddrOf) {
5582 Arg = UnOp->getSubExpr();
5583 AddressTaken = true;
5584 AddrOpLoc = UnOp->getOperatorLoc();
5588 while (SubstNonTypeTemplateParmExpr *subst =
5589 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5590 Arg = subst->getReplacement()->IgnoreImpCasts();
5593 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
5594 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
5596 // If our parameter has pointer type, check for a null template value.
5597 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
5598 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
5600 case NPV_NullPointer:
5601 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
5602 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5603 /*isNullPtr=*/true);
5609 case NPV_NotNullPointer:
5614 // Stop checking the precise nature of the argument if it is value dependent,
5615 // it should be checked when instantiated.
5616 if (Arg->isValueDependent()) {
5617 Converted = TemplateArgument(ArgIn);
5621 if (isa<CXXUuidofExpr>(Arg)) {
5622 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
5623 ArgIn, Arg, ArgType))
5626 Converted = TemplateArgument(ArgIn);
5631 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5632 << Arg->getSourceRange();
5633 S.Diag(Param->getLocation(), diag::note_template_param_here);
5637 // Cannot refer to non-static data members
5638 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
5639 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
5640 << Entity << Arg->getSourceRange();
5641 S.Diag(Param->getLocation(), diag::note_template_param_here);
5645 // Cannot refer to non-static member functions
5646 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
5647 if (!Method->isStatic()) {
5648 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
5649 << Method << Arg->getSourceRange();
5650 S.Diag(Param->getLocation(), diag::note_template_param_here);
5655 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
5656 VarDecl *Var = dyn_cast<VarDecl>(Entity);
5658 // A non-type template argument must refer to an object or function.
5659 if (!Func && !Var) {
5660 // We found something, but we don't know specifically what it is.
5661 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
5662 << Arg->getSourceRange();
5663 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
5667 // Address / reference template args must have external linkage in C++98.
5668 if (Entity->getFormalLinkage() == InternalLinkage) {
5669 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
5670 diag::warn_cxx98_compat_template_arg_object_internal :
5671 diag::ext_template_arg_object_internal)
5672 << !Func << Entity << Arg->getSourceRange();
5673 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5675 } else if (!Entity->hasLinkage()) {
5676 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
5677 << !Func << Entity << Arg->getSourceRange();
5678 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5684 // If the template parameter has pointer type, the function decays.
5685 if (ParamType->isPointerType() && !AddressTaken)
5686 ArgType = S.Context.getPointerType(Func->getType());
5687 else if (AddressTaken && ParamType->isReferenceType()) {
5688 // If we originally had an address-of operator, but the
5689 // parameter has reference type, complain and (if things look
5690 // like they will work) drop the address-of operator.
5691 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
5692 ParamType.getNonReferenceType())) {
5693 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5695 S.Diag(Param->getLocation(), diag::note_template_param_here);
5699 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5701 << FixItHint::CreateRemoval(AddrOpLoc);
5702 S.Diag(Param->getLocation(), diag::note_template_param_here);
5704 ArgType = Func->getType();
5707 // A value of reference type is not an object.
5708 if (Var->getType()->isReferenceType()) {
5709 S.Diag(Arg->getLocStart(),
5710 diag::err_template_arg_reference_var)
5711 << Var->getType() << Arg->getSourceRange();
5712 S.Diag(Param->getLocation(), diag::note_template_param_here);
5716 // A template argument must have static storage duration.
5717 if (Var->getTLSKind()) {
5718 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
5719 << Arg->getSourceRange();
5720 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
5724 // If the template parameter has pointer type, we must have taken
5725 // the address of this object.
5726 if (ParamType->isReferenceType()) {
5728 // If we originally had an address-of operator, but the
5729 // parameter has reference type, complain and (if things look
5730 // like they will work) drop the address-of operator.
5731 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
5732 ParamType.getNonReferenceType())) {
5733 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5735 S.Diag(Param->getLocation(), diag::note_template_param_here);
5739 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5741 << FixItHint::CreateRemoval(AddrOpLoc);
5742 S.Diag(Param->getLocation(), diag::note_template_param_here);
5744 ArgType = Var->getType();
5746 } else if (!AddressTaken && ParamType->isPointerType()) {
5747 if (Var->getType()->isArrayType()) {
5748 // Array-to-pointer decay.
5749 ArgType = S.Context.getArrayDecayedType(Var->getType());
5751 // If the template parameter has pointer type but the address of
5752 // this object was not taken, complain and (possibly) recover by
5753 // taking the address of the entity.
5754 ArgType = S.Context.getPointerType(Var->getType());
5755 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
5756 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
5758 S.Diag(Param->getLocation(), diag::note_template_param_here);
5762 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
5764 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
5766 S.Diag(Param->getLocation(), diag::note_template_param_here);
5771 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
5775 // Create the template argument.
5777 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
5778 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
5782 /// \brief Checks whether the given template argument is a pointer to
5783 /// member constant according to C++ [temp.arg.nontype]p1.
5784 static bool CheckTemplateArgumentPointerToMember(Sema &S,
5785 NonTypeTemplateParmDecl *Param,
5788 TemplateArgument &Converted) {
5789 bool Invalid = false;
5791 Expr *Arg = ResultArg;
5792 bool ObjCLifetimeConversion;
5794 // C++ [temp.arg.nontype]p1:
5796 // A template-argument for a non-type, non-template
5797 // template-parameter shall be one of: [...]
5799 // -- a pointer to member expressed as described in 5.3.1.
5800 DeclRefExpr *DRE = nullptr;
5802 // In C++98/03 mode, give an extension warning on any extra parentheses.
5803 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5804 bool ExtraParens = false;
5805 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
5806 if (!Invalid && !ExtraParens) {
5807 S.Diag(Arg->getLocStart(),
5808 S.getLangOpts().CPlusPlus11 ?
5809 diag::warn_cxx98_compat_template_arg_extra_parens :
5810 diag::ext_template_arg_extra_parens)
5811 << Arg->getSourceRange();
5815 Arg = Parens->getSubExpr();
5818 while (SubstNonTypeTemplateParmExpr *subst =
5819 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5820 Arg = subst->getReplacement()->IgnoreImpCasts();
5822 // A pointer-to-member constant written &Class::member.
5823 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5824 if (UnOp->getOpcode() == UO_AddrOf) {
5825 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
5826 if (DRE && !DRE->getQualifier())
5830 // A constant of pointer-to-member type.
5831 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
5832 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
5833 if (VD->getType()->isMemberPointerType()) {
5834 if (isa<NonTypeTemplateParmDecl>(VD)) {
5835 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5836 Converted = TemplateArgument(Arg);
5838 VD = cast<ValueDecl>(VD->getCanonicalDecl());
5839 Converted = TemplateArgument(VD, ParamType);
5849 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
5851 // Check for a null pointer value.
5852 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
5856 case NPV_NullPointer:
5857 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
5858 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5861 case NPV_NotNullPointer:
5865 if (S.IsQualificationConversion(ResultArg->getType(),
5866 ParamType.getNonReferenceType(), false,
5867 ObjCLifetimeConversion)) {
5868 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
5869 ResultArg->getValueKind())
5871 } else if (!S.Context.hasSameUnqualifiedType(
5872 ResultArg->getType(), ParamType.getNonReferenceType())) {
5873 // We can't perform this conversion.
5874 S.Diag(ResultArg->getLocStart(), diag::err_template_arg_not_convertible)
5875 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
5876 S.Diag(Param->getLocation(), diag::note_template_param_here);
5881 return S.Diag(Arg->getLocStart(),
5882 diag::err_template_arg_not_pointer_to_member_form)
5883 << Arg->getSourceRange();
5885 if (isa<FieldDecl>(DRE->getDecl()) ||
5886 isa<IndirectFieldDecl>(DRE->getDecl()) ||
5887 isa<CXXMethodDecl>(DRE->getDecl())) {
5888 assert((isa<FieldDecl>(DRE->getDecl()) ||
5889 isa<IndirectFieldDecl>(DRE->getDecl()) ||
5890 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
5891 "Only non-static member pointers can make it here");
5893 // Okay: this is the address of a non-static member, and therefore
5894 // a member pointer constant.
5895 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5896 Converted = TemplateArgument(Arg);
5898 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
5899 Converted = TemplateArgument(D, ParamType);
5904 // We found something else, but we don't know specifically what it is.
5905 S.Diag(Arg->getLocStart(),
5906 diag::err_template_arg_not_pointer_to_member_form)
5907 << Arg->getSourceRange();
5908 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
5912 /// \brief Check a template argument against its corresponding
5913 /// non-type template parameter.
5915 /// This routine implements the semantics of C++ [temp.arg.nontype].
5916 /// If an error occurred, it returns ExprError(); otherwise, it
5917 /// returns the converted template argument. \p ParamType is the
5918 /// type of the non-type template parameter after it has been instantiated.
5919 ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
5920 QualType ParamType, Expr *Arg,
5921 TemplateArgument &Converted,
5922 CheckTemplateArgumentKind CTAK) {
5923 SourceLocation StartLoc = Arg->getLocStart();
5925 // If the parameter type somehow involves auto, deduce the type now.
5926 if (getLangOpts().CPlusPlus17 && ParamType->isUndeducedType()) {
5927 // During template argument deduction, we allow 'decltype(auto)' to
5928 // match an arbitrary dependent argument.
5929 // FIXME: The language rules don't say what happens in this case.
5930 // FIXME: We get an opaque dependent type out of decltype(auto) if the
5931 // expression is merely instantiation-dependent; is this enough?
5932 if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) {
5933 auto *AT = dyn_cast<AutoType>(ParamType);
5934 if (AT && AT->isDecltypeAuto()) {
5935 Converted = TemplateArgument(Arg);
5940 // When checking a deduced template argument, deduce from its type even if
5941 // the type is dependent, in order to check the types of non-type template
5942 // arguments line up properly in partial ordering.
5943 Optional<unsigned> Depth;
5944 if (CTAK != CTAK_Specified)
5945 Depth = Param->getDepth() + 1;
5947 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()),
5948 Arg, ParamType, Depth) == DAR_Failed) {
5949 Diag(Arg->getExprLoc(),
5950 diag::err_non_type_template_parm_type_deduction_failure)
5951 << Param->getDeclName() << Param->getType() << Arg->getType()
5952 << Arg->getSourceRange();
5953 Diag(Param->getLocation(), diag::note_template_param_here);
5956 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
5957 // an error. The error message normally references the parameter
5958 // declaration, but here we'll pass the argument location because that's
5959 // where the parameter type is deduced.
5960 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
5961 if (ParamType.isNull()) {
5962 Diag(Param->getLocation(), diag::note_template_param_here);
5967 // We should have already dropped all cv-qualifiers by now.
5968 assert(!ParamType.hasQualifiers() &&
5969 "non-type template parameter type cannot be qualified");
5971 if (CTAK == CTAK_Deduced &&
5972 !Context.hasSameType(ParamType.getNonLValueExprType(Context),
5974 // FIXME: If either type is dependent, we skip the check. This isn't
5975 // correct, since during deduction we're supposed to have replaced each
5976 // template parameter with some unique (non-dependent) placeholder.
5977 // FIXME: If the argument type contains 'auto', we carry on and fail the
5978 // type check in order to force specific types to be more specialized than
5979 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
5981 if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
5982 !Arg->getType()->getContainedAutoType()) {
5983 Converted = TemplateArgument(Arg);
5986 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
5987 // we should actually be checking the type of the template argument in P,
5988 // not the type of the template argument deduced from A, against the
5989 // template parameter type.
5990 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
5992 << ParamType.getUnqualifiedType();
5993 Diag(Param->getLocation(), diag::note_template_param_here);
5997 // If either the parameter has a dependent type or the argument is
5998 // type-dependent, there's nothing we can check now.
5999 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
6000 // FIXME: Produce a cloned, canonical expression?
6001 Converted = TemplateArgument(Arg);
6005 // The initialization of the parameter from the argument is
6006 // a constant-evaluated context.
6007 EnterExpressionEvaluationContext ConstantEvaluated(
6008 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6010 if (getLangOpts().CPlusPlus17) {
6011 // C++17 [temp.arg.nontype]p1:
6012 // A template-argument for a non-type template parameter shall be
6013 // a converted constant expression of the type of the template-parameter.
6015 ExprResult ArgResult = CheckConvertedConstantExpression(
6016 Arg, ParamType, Value, CCEK_TemplateArg);
6017 if (ArgResult.isInvalid())
6020 // For a value-dependent argument, CheckConvertedConstantExpression is
6021 // permitted (and expected) to be unable to determine a value.
6022 if (ArgResult.get()->isValueDependent()) {
6023 Converted = TemplateArgument(ArgResult.get());
6027 QualType CanonParamType = Context.getCanonicalType(ParamType);
6029 // Convert the APValue to a TemplateArgument.
6030 switch (Value.getKind()) {
6031 case APValue::Uninitialized:
6032 assert(ParamType->isNullPtrType());
6033 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
6036 assert(ParamType->isIntegralOrEnumerationType());
6037 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
6039 case APValue::MemberPointer: {
6040 assert(ParamType->isMemberPointerType());
6042 // FIXME: We need TemplateArgument representation and mangling for these.
6043 if (!Value.getMemberPointerPath().empty()) {
6044 Diag(Arg->getLocStart(),
6045 diag::err_template_arg_member_ptr_base_derived_not_supported)
6046 << Value.getMemberPointerDecl() << ParamType
6047 << Arg->getSourceRange();
6051 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
6052 Converted = VD ? TemplateArgument(VD, CanonParamType)
6053 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
6056 case APValue::LValue: {
6057 // For a non-type template-parameter of pointer or reference type,
6058 // the value of the constant expression shall not refer to
6059 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
6060 ParamType->isNullPtrType());
6061 // -- a temporary object
6062 // -- a string literal
6063 // -- the result of a typeid expression, or
6064 // -- a predefined __func__ variable
6065 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
6066 if (isa<CXXUuidofExpr>(E)) {
6067 Converted = TemplateArgument(const_cast<Expr*>(E));
6070 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
6071 << Arg->getSourceRange();
6074 auto *VD = const_cast<ValueDecl *>(
6075 Value.getLValueBase().dyn_cast<const ValueDecl *>());
6077 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
6078 VD && VD->getType()->isArrayType() &&
6079 Value.getLValuePath()[0].ArrayIndex == 0 &&
6080 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
6081 // Per defect report (no number yet):
6082 // ... other than a pointer to the first element of a complete array
6084 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
6085 Value.isLValueOnePastTheEnd()) {
6086 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
6087 << Value.getAsString(Context, ParamType);
6090 assert((VD || !ParamType->isReferenceType()) &&
6091 "null reference should not be a constant expression");
6092 assert((!VD || !ParamType->isNullPtrType()) &&
6093 "non-null value of type nullptr_t?");
6094 Converted = VD ? TemplateArgument(VD, CanonParamType)
6095 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
6098 case APValue::AddrLabelDiff:
6099 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
6100 case APValue::Float:
6101 case APValue::ComplexInt:
6102 case APValue::ComplexFloat:
6103 case APValue::Vector:
6104 case APValue::Array:
6105 case APValue::Struct:
6106 case APValue::Union:
6107 llvm_unreachable("invalid kind for template argument");
6110 return ArgResult.get();
6113 // C++ [temp.arg.nontype]p5:
6114 // The following conversions are performed on each expression used
6115 // as a non-type template-argument. If a non-type
6116 // template-argument cannot be converted to the type of the
6117 // corresponding template-parameter then the program is
6119 if (ParamType->isIntegralOrEnumerationType()) {
6121 // -- for a non-type template-parameter of integral or
6122 // enumeration type, conversions permitted in a converted
6123 // constant expression are applied.
6126 // -- for a non-type template-parameter of integral or
6127 // enumeration type, integral promotions (4.5) and integral
6128 // conversions (4.7) are applied.
6130 if (getLangOpts().CPlusPlus11) {
6131 // C++ [temp.arg.nontype]p1:
6132 // A template-argument for a non-type, non-template template-parameter
6135 // -- for a non-type template-parameter of integral or enumeration
6136 // type, a converted constant expression of the type of the
6137 // template-parameter; or
6139 ExprResult ArgResult =
6140 CheckConvertedConstantExpression(Arg, ParamType, Value,
6142 if (ArgResult.isInvalid())
6145 // We can't check arbitrary value-dependent arguments.
6146 if (ArgResult.get()->isValueDependent()) {
6147 Converted = TemplateArgument(ArgResult.get());
6151 // Widen the argument value to sizeof(parameter type). This is almost
6152 // always a no-op, except when the parameter type is bool. In
6153 // that case, this may extend the argument from 1 bit to 8 bits.
6154 QualType IntegerType = ParamType;
6155 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6156 IntegerType = Enum->getDecl()->getIntegerType();
6157 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
6159 Converted = TemplateArgument(Context, Value,
6160 Context.getCanonicalType(ParamType));
6164 ExprResult ArgResult = DefaultLvalueConversion(Arg);
6165 if (ArgResult.isInvalid())
6167 Arg = ArgResult.get();
6169 QualType ArgType = Arg->getType();
6171 // C++ [temp.arg.nontype]p1:
6172 // A template-argument for a non-type, non-template
6173 // template-parameter shall be one of:
6175 // -- an integral constant-expression of integral or enumeration
6177 // -- the name of a non-type template-parameter; or
6179 if (!ArgType->isIntegralOrEnumerationType()) {
6180 Diag(Arg->getLocStart(),
6181 diag::err_template_arg_not_integral_or_enumeral)
6182 << ArgType << Arg->getSourceRange();
6183 Diag(Param->getLocation(), diag::note_template_param_here);
6185 } else if (!Arg->isValueDependent()) {
6186 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
6190 TmplArgICEDiagnoser(QualType T) : T(T) { }
6192 void diagnoseNotICE(Sema &S, SourceLocation Loc,
6193 SourceRange SR) override {
6194 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
6196 } Diagnoser(ArgType);
6198 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
6204 // From here on out, all we care about is the unqualified form
6205 // of the argument type.
6206 ArgType = ArgType.getUnqualifiedType();
6208 // Try to convert the argument to the parameter's type.
6209 if (Context.hasSameType(ParamType, ArgType)) {
6210 // Okay: no conversion necessary
6211 } else if (ParamType->isBooleanType()) {
6212 // This is an integral-to-boolean conversion.
6213 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
6214 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
6215 !ParamType->isEnumeralType()) {
6216 // This is an integral promotion or conversion.
6217 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
6219 // We can't perform this conversion.
6220 Diag(Arg->getLocStart(),
6221 diag::err_template_arg_not_convertible)
6222 << Arg->getType() << ParamType << Arg->getSourceRange();
6223 Diag(Param->getLocation(), diag::note_template_param_here);
6227 // Add the value of this argument to the list of converted
6228 // arguments. We use the bitwidth and signedness of the template
6230 if (Arg->isValueDependent()) {
6231 // The argument is value-dependent. Create a new
6232 // TemplateArgument with the converted expression.
6233 Converted = TemplateArgument(Arg);
6237 QualType IntegerType = Context.getCanonicalType(ParamType);
6238 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6239 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
6241 if (ParamType->isBooleanType()) {
6242 // Value must be zero or one.
6244 unsigned AllowedBits = Context.getTypeSize(IntegerType);
6245 if (Value.getBitWidth() != AllowedBits)
6246 Value = Value.extOrTrunc(AllowedBits);
6247 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
6249 llvm::APSInt OldValue = Value;
6251 // Coerce the template argument's value to the value it will have
6252 // based on the template parameter's type.
6253 unsigned AllowedBits = Context.getTypeSize(IntegerType);
6254 if (Value.getBitWidth() != AllowedBits)
6255 Value = Value.extOrTrunc(AllowedBits);
6256 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
6258 // Complain if an unsigned parameter received a negative value.
6259 if (IntegerType->isUnsignedIntegerOrEnumerationType()
6260 && (OldValue.isSigned() && OldValue.isNegative())) {
6261 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
6262 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6263 << Arg->getSourceRange();
6264 Diag(Param->getLocation(), diag::note_template_param_here);
6267 // Complain if we overflowed the template parameter's type.
6268 unsigned RequiredBits;
6269 if (IntegerType->isUnsignedIntegerOrEnumerationType())
6270 RequiredBits = OldValue.getActiveBits();
6271 else if (OldValue.isUnsigned())
6272 RequiredBits = OldValue.getActiveBits() + 1;
6274 RequiredBits = OldValue.getMinSignedBits();
6275 if (RequiredBits > AllowedBits) {
6276 Diag(Arg->getLocStart(),
6277 diag::warn_template_arg_too_large)
6278 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6279 << Arg->getSourceRange();
6280 Diag(Param->getLocation(), diag::note_template_param_here);
6284 Converted = TemplateArgument(Context, Value,
6285 ParamType->isEnumeralType()
6286 ? Context.getCanonicalType(ParamType)
6291 QualType ArgType = Arg->getType();
6292 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
6294 // Handle pointer-to-function, reference-to-function, and
6295 // pointer-to-member-function all in (roughly) the same way.
6296 if (// -- For a non-type template-parameter of type pointer to
6297 // function, only the function-to-pointer conversion (4.3) is
6298 // applied. If the template-argument represents a set of
6299 // overloaded functions (or a pointer to such), the matching
6300 // function is selected from the set (13.4).
6301 (ParamType->isPointerType() &&
6302 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
6303 // -- For a non-type template-parameter of type reference to
6304 // function, no conversions apply. If the template-argument
6305 // represents a set of overloaded functions, the matching
6306 // function is selected from the set (13.4).
6307 (ParamType->isReferenceType() &&
6308 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
6309 // -- For a non-type template-parameter of type pointer to
6310 // member function, no conversions apply. If the
6311 // template-argument represents a set of overloaded member
6312 // functions, the matching member function is selected from
6314 (ParamType->isMemberPointerType() &&
6315 ParamType->getAs<MemberPointerType>()->getPointeeType()
6316 ->isFunctionType())) {
6318 if (Arg->getType() == Context.OverloadTy) {
6319 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
6322 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
6325 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6326 ArgType = Arg->getType();
6331 if (!ParamType->isMemberPointerType()) {
6332 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6339 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6345 if (ParamType->isPointerType()) {
6346 // -- for a non-type template-parameter of type pointer to
6347 // object, qualification conversions (4.4) and the
6348 // array-to-pointer conversion (4.2) are applied.
6349 // C++0x also allows a value of std::nullptr_t.
6350 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
6351 "Only object pointers allowed here");
6353 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6360 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
6361 // -- For a non-type template-parameter of type reference to
6362 // object, no conversions apply. The type referred to by the
6363 // reference may be more cv-qualified than the (otherwise
6364 // identical) type of the template-argument. The
6365 // template-parameter is bound directly to the
6366 // template-argument, which must be an lvalue.
6367 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
6368 "Only object references allowed here");
6370 if (Arg->getType() == Context.OverloadTy) {
6371 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
6372 ParamRefType->getPointeeType(),
6375 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
6378 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6379 ArgType = Arg->getType();
6384 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6391 // Deal with parameters of type std::nullptr_t.
6392 if (ParamType->isNullPtrType()) {
6393 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6394 Converted = TemplateArgument(Arg);
6398 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
6399 case NPV_NotNullPointer:
6400 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
6401 << Arg->getType() << ParamType;
6402 Diag(Param->getLocation(), diag::note_template_param_here);
6408 case NPV_NullPointer:
6409 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6410 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
6416 // -- For a non-type template-parameter of type pointer to data
6417 // member, qualification conversions (4.4) are applied.
6418 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
6420 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6426 static void DiagnoseTemplateParameterListArityMismatch(
6427 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
6428 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
6430 /// \brief Check a template argument against its corresponding
6431 /// template template parameter.
6433 /// This routine implements the semantics of C++ [temp.arg.template].
6434 /// It returns true if an error occurred, and false otherwise.
6435 bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
6436 TemplateArgumentLoc &Arg,
6437 unsigned ArgumentPackIndex) {
6438 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
6439 TemplateDecl *Template = Name.getAsTemplateDecl();
6441 // Any dependent template name is fine.
6442 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
6446 if (Template->isInvalidDecl())
6449 // C++0x [temp.arg.template]p1:
6450 // A template-argument for a template template-parameter shall be
6451 // the name of a class template or an alias template, expressed as an
6452 // id-expression. When the template-argument names a class template, only
6453 // primary class templates are considered when matching the
6454 // template template argument with the corresponding parameter;
6455 // partial specializations are not considered even if their
6456 // parameter lists match that of the template template parameter.
6458 // Note that we also allow template template parameters here, which
6459 // will happen when we are dealing with, e.g., class template
6460 // partial specializations.
6461 if (!isa<ClassTemplateDecl>(Template) &&
6462 !isa<TemplateTemplateParmDecl>(Template) &&
6463 !isa<TypeAliasTemplateDecl>(Template) &&
6464 !isa<BuiltinTemplateDecl>(Template)) {
6465 assert(isa<FunctionTemplateDecl>(Template) &&
6466 "Only function templates are possible here");
6467 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
6468 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
6472 TemplateParameterList *Params = Param->getTemplateParameters();
6473 if (Param->isExpandedParameterPack())
6474 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
6476 // C++1z [temp.arg.template]p3: (DR 150)
6477 // A template-argument matches a template template-parameter P when P
6478 // is at least as specialized as the template-argument A.
6479 if (getLangOpts().RelaxedTemplateTemplateArgs) {
6480 // Quick check for the common case:
6481 // If P contains a parameter pack, then A [...] matches P if each of A's
6482 // template parameters matches the corresponding template parameter in
6483 // the template-parameter-list of P.
6484 if (TemplateParameterListsAreEqual(
6485 Template->getTemplateParameters(), Params, false,
6486 TPL_TemplateTemplateArgumentMatch, Arg.getLocation()))
6489 if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
6492 // FIXME: Produce better diagnostics for deduction failures.
6495 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
6498 TPL_TemplateTemplateArgumentMatch,
6502 /// \brief Given a non-type template argument that refers to a
6503 /// declaration and the type of its corresponding non-type template
6504 /// parameter, produce an expression that properly refers to that
6507 Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6509 SourceLocation Loc) {
6510 // C++ [temp.param]p8:
6512 // A non-type template-parameter of type "array of T" or
6513 // "function returning T" is adjusted to be of type "pointer to
6514 // T" or "pointer to function returning T", respectively.
6515 if (ParamType->isArrayType())
6516 ParamType = Context.getArrayDecayedType(ParamType);
6517 else if (ParamType->isFunctionType())
6518 ParamType = Context.getPointerType(ParamType);
6520 // For a NULL non-type template argument, return nullptr casted to the
6521 // parameter's type.
6522 if (Arg.getKind() == TemplateArgument::NullPtr) {
6523 return ImpCastExprToType(
6524 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
6526 ParamType->getAs<MemberPointerType>()
6527 ? CK_NullToMemberPointer
6528 : CK_NullToPointer);
6530 assert(Arg.getKind() == TemplateArgument::Declaration &&
6531 "Only declaration template arguments permitted here");
6533 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
6535 if (VD->getDeclContext()->isRecord() &&
6536 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
6537 isa<IndirectFieldDecl>(VD))) {
6538 // If the value is a class member, we might have a pointer-to-member.
6539 // Determine whether the non-type template template parameter is of
6540 // pointer-to-member type. If so, we need to build an appropriate
6541 // expression for a pointer-to-member, since a "normal" DeclRefExpr
6542 // would refer to the member itself.
6543 if (ParamType->isMemberPointerType()) {
6545 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
6546 NestedNameSpecifier *Qualifier
6547 = NestedNameSpecifier::Create(Context, nullptr, false,
6548 ClassType.getTypePtr());
6550 SS.MakeTrivial(Context, Qualifier, Loc);
6552 // The actual value-ness of this is unimportant, but for
6553 // internal consistency's sake, references to instance methods
6555 ExprValueKind VK = VK_LValue;
6556 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
6559 ExprResult RefExpr = BuildDeclRefExpr(VD,
6560 VD->getType().getNonReferenceType(),
6564 if (RefExpr.isInvalid())
6567 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
6569 // We might need to perform a trailing qualification conversion, since
6570 // the element type on the parameter could be more qualified than the
6571 // element type in the expression we constructed.
6572 bool ObjCLifetimeConversion;
6573 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
6574 ParamType.getUnqualifiedType(), false,
6575 ObjCLifetimeConversion))
6576 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
6578 assert(!RefExpr.isInvalid() &&
6579 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
6580 ParamType.getUnqualifiedType()));
6585 QualType T = VD->getType().getNonReferenceType();
6587 if (ParamType->isPointerType()) {
6588 // When the non-type template parameter is a pointer, take the
6589 // address of the declaration.
6590 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
6591 if (RefExpr.isInvalid())
6594 if (!Context.hasSameUnqualifiedType(ParamType->getPointeeType(), T) &&
6595 (T->isFunctionType() || T->isArrayType())) {
6596 // Decay functions and arrays unless we're forming a pointer to array.
6597 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
6598 if (RefExpr.isInvalid())
6604 // Take the address of everything else
6605 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
6608 ExprValueKind VK = VK_RValue;
6610 // If the non-type template parameter has reference type, qualify the
6611 // resulting declaration reference with the extra qualifiers on the
6612 // type that the reference refers to.
6613 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
6615 T = Context.getQualifiedType(T,
6616 TargetRef->getPointeeType().getQualifiers());
6617 } else if (isa<FunctionDecl>(VD)) {
6618 // References to functions are always lvalues.
6622 return BuildDeclRefExpr(VD, T, VK, Loc);
6625 /// \brief Construct a new expression that refers to the given
6626 /// integral template argument with the given source-location
6629 /// This routine takes care of the mapping from an integral template
6630 /// argument (which may have any integral type) to the appropriate
6633 Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6634 SourceLocation Loc) {
6635 assert(Arg.getKind() == TemplateArgument::Integral &&
6636 "Operation is only valid for integral template arguments");
6637 QualType OrigT = Arg.getIntegralType();
6639 // If this is an enum type that we're instantiating, we need to use an integer
6640 // type the same size as the enumerator. We don't want to build an
6641 // IntegerLiteral with enum type. The integer type of an enum type can be of
6642 // any integral type with C++11 enum classes, make sure we create the right
6643 // type of literal for it.
6645 if (const EnumType *ET = OrigT->getAs<EnumType>())
6646 T = ET->getDecl()->getIntegerType();
6649 if (T->isAnyCharacterType()) {
6650 // This does not need to handle u8 character literals because those are
6651 // of type char, and so can also be covered by an ASCII character literal.
6652 CharacterLiteral::CharacterKind Kind;
6653 if (T->isWideCharType())
6654 Kind = CharacterLiteral::Wide;
6655 else if (T->isChar16Type())
6656 Kind = CharacterLiteral::UTF16;
6657 else if (T->isChar32Type())
6658 Kind = CharacterLiteral::UTF32;
6660 Kind = CharacterLiteral::Ascii;
6662 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
6664 } else if (T->isBooleanType()) {
6665 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
6667 } else if (T->isNullPtrType()) {
6668 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
6670 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
6673 if (OrigT->isEnumeralType()) {
6674 // FIXME: This is a hack. We need a better way to handle substituted
6675 // non-type template parameters.
6676 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
6678 Context.getTrivialTypeSourceInfo(OrigT, Loc),
6685 /// \brief Match two template parameters within template parameter lists.
6686 static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
6688 Sema::TemplateParameterListEqualKind Kind,
6689 SourceLocation TemplateArgLoc) {
6690 // Check the actual kind (type, non-type, template).
6691 if (Old->getKind() != New->getKind()) {
6693 unsigned NextDiag = diag::err_template_param_different_kind;
6694 if (TemplateArgLoc.isValid()) {
6695 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6696 NextDiag = diag::note_template_param_different_kind;
6698 S.Diag(New->getLocation(), NextDiag)
6699 << (Kind != Sema::TPL_TemplateMatch);
6700 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
6701 << (Kind != Sema::TPL_TemplateMatch);
6707 // Check that both are parameter packs or neither are parameter packs.
6708 // However, if we are matching a template template argument to a
6709 // template template parameter, the template template parameter can have
6710 // a parameter pack where the template template argument does not.
6711 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
6712 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
6713 Old->isTemplateParameterPack())) {
6715 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
6716 if (TemplateArgLoc.isValid()) {
6717 S.Diag(TemplateArgLoc,
6718 diag::err_template_arg_template_params_mismatch);
6719 NextDiag = diag::note_template_parameter_pack_non_pack;
6722 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
6723 : isa<NonTypeTemplateParmDecl>(New)? 1
6725 S.Diag(New->getLocation(), NextDiag)
6726 << ParamKind << New->isParameterPack();
6727 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
6728 << ParamKind << Old->isParameterPack();
6734 // For non-type template parameters, check the type of the parameter.
6735 if (NonTypeTemplateParmDecl *OldNTTP
6736 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
6737 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
6739 // If we are matching a template template argument to a template
6740 // template parameter and one of the non-type template parameter types
6741 // is dependent, then we must wait until template instantiation time
6742 // to actually compare the arguments.
6743 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
6744 (OldNTTP->getType()->isDependentType() ||
6745 NewNTTP->getType()->isDependentType()))
6748 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
6750 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
6751 if (TemplateArgLoc.isValid()) {
6752 S.Diag(TemplateArgLoc,
6753 diag::err_template_arg_template_params_mismatch);
6754 NextDiag = diag::note_template_nontype_parm_different_type;
6756 S.Diag(NewNTTP->getLocation(), NextDiag)
6757 << NewNTTP->getType()
6758 << (Kind != Sema::TPL_TemplateMatch);
6759 S.Diag(OldNTTP->getLocation(),
6760 diag::note_template_nontype_parm_prev_declaration)
6761 << OldNTTP->getType();
6770 // For template template parameters, check the template parameter types.
6771 // The template parameter lists of template template
6772 // parameters must agree.
6773 if (TemplateTemplateParmDecl *OldTTP
6774 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
6775 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
6776 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
6777 OldTTP->getTemplateParameters(),
6779 (Kind == Sema::TPL_TemplateMatch
6780 ? Sema::TPL_TemplateTemplateParmMatch
6788 /// \brief Diagnose a known arity mismatch when comparing template argument
6791 void DiagnoseTemplateParameterListArityMismatch(Sema &S,
6792 TemplateParameterList *New,
6793 TemplateParameterList *Old,
6794 Sema::TemplateParameterListEqualKind Kind,
6795 SourceLocation TemplateArgLoc) {
6796 unsigned NextDiag = diag::err_template_param_list_different_arity;
6797 if (TemplateArgLoc.isValid()) {
6798 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6799 NextDiag = diag::note_template_param_list_different_arity;
6801 S.Diag(New->getTemplateLoc(), NextDiag)
6802 << (New->size() > Old->size())
6803 << (Kind != Sema::TPL_TemplateMatch)
6804 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
6805 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
6806 << (Kind != Sema::TPL_TemplateMatch)
6807 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
6810 /// \brief Determine whether the given template parameter lists are
6813 /// \param New The new template parameter list, typically written in the
6814 /// source code as part of a new template declaration.
6816 /// \param Old The old template parameter list, typically found via
6817 /// name lookup of the template declared with this template parameter
6820 /// \param Complain If true, this routine will produce a diagnostic if
6821 /// the template parameter lists are not equivalent.
6823 /// \param Kind describes how we are to match the template parameter lists.
6825 /// \param TemplateArgLoc If this source location is valid, then we
6826 /// are actually checking the template parameter list of a template
6827 /// argument (New) against the template parameter list of its
6828 /// corresponding template template parameter (Old). We produce
6829 /// slightly different diagnostics in this scenario.
6831 /// \returns True if the template parameter lists are equal, false
6834 Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
6835 TemplateParameterList *Old,
6837 TemplateParameterListEqualKind Kind,
6838 SourceLocation TemplateArgLoc) {
6839 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
6841 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6847 // C++0x [temp.arg.template]p3:
6848 // A template-argument matches a template template-parameter (call it P)
6849 // when each of the template parameters in the template-parameter-list of
6850 // the template-argument's corresponding class template or alias template
6851 // (call it A) matches the corresponding template parameter in the
6852 // template-parameter-list of P. [...]
6853 TemplateParameterList::iterator NewParm = New->begin();
6854 TemplateParameterList::iterator NewParmEnd = New->end();
6855 for (TemplateParameterList::iterator OldParm = Old->begin(),
6856 OldParmEnd = Old->end();
6857 OldParm != OldParmEnd; ++OldParm) {
6858 if (Kind != TPL_TemplateTemplateArgumentMatch ||
6859 !(*OldParm)->isTemplateParameterPack()) {
6860 if (NewParm == NewParmEnd) {
6862 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6868 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
6869 Kind, TemplateArgLoc))
6876 // C++0x [temp.arg.template]p3:
6877 // [...] When P's template- parameter-list contains a template parameter
6878 // pack (14.5.3), the template parameter pack will match zero or more
6879 // template parameters or template parameter packs in the
6880 // template-parameter-list of A with the same type and form as the
6881 // template parameter pack in P (ignoring whether those template
6882 // parameters are template parameter packs).
6883 for (; NewParm != NewParmEnd; ++NewParm) {
6884 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
6885 Kind, TemplateArgLoc))
6890 // Make sure we exhausted all of the arguments.
6891 if (NewParm != NewParmEnd) {
6893 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6902 /// \brief Check whether a template can be declared within this scope.
6904 /// If the template declaration is valid in this scope, returns
6905 /// false. Otherwise, issues a diagnostic and returns true.
6907 Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
6911 // Find the nearest enclosing declaration scope.
6912 while ((S->getFlags() & Scope::DeclScope) == 0 ||
6913 (S->getFlags() & Scope::TemplateParamScope) != 0)
6917 // A template [...] shall not have C linkage.
6918 DeclContext *Ctx = S->getEntity();
6919 if (Ctx && Ctx->isExternCContext()) {
6920 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
6921 << TemplateParams->getSourceRange();
6922 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
6923 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
6926 Ctx = Ctx->getRedeclContext();
6929 // A template-declaration can appear only as a namespace scope or
6930 // class scope declaration.
6932 if (Ctx->isFileContext())
6934 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
6935 // C++ [temp.mem]p2:
6936 // A local class shall not have member templates.
6937 if (RD->isLocalClass())
6938 return Diag(TemplateParams->getTemplateLoc(),
6939 diag::err_template_inside_local_class)
6940 << TemplateParams->getSourceRange();
6946 return Diag(TemplateParams->getTemplateLoc(),
6947 diag::err_template_outside_namespace_or_class_scope)
6948 << TemplateParams->getSourceRange();
6951 /// \brief Determine what kind of template specialization the given declaration
6953 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
6955 return TSK_Undeclared;
6957 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
6958 return Record->getTemplateSpecializationKind();
6959 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
6960 return Function->getTemplateSpecializationKind();
6961 if (VarDecl *Var = dyn_cast<VarDecl>(D))
6962 return Var->getTemplateSpecializationKind();
6964 return TSK_Undeclared;
6967 /// \brief Check whether a specialization is well-formed in the current
6970 /// This routine determines whether a template specialization can be declared
6971 /// in the current context (C++ [temp.expl.spec]p2).
6973 /// \param S the semantic analysis object for which this check is being
6976 /// \param Specialized the entity being specialized or instantiated, which
6977 /// may be a kind of template (class template, function template, etc.) or
6978 /// a member of a class template (member function, static data member,
6981 /// \param PrevDecl the previous declaration of this entity, if any.
6983 /// \param Loc the location of the explicit specialization or instantiation of
6986 /// \param IsPartialSpecialization whether this is a partial specialization of
6987 /// a class template.
6989 /// \returns true if there was an error that we cannot recover from, false
6991 static bool CheckTemplateSpecializationScope(Sema &S,
6992 NamedDecl *Specialized,
6993 NamedDecl *PrevDecl,
6995 bool IsPartialSpecialization) {
6996 // Keep these "kind" numbers in sync with the %select statements in the
6997 // various diagnostics emitted by this routine.
6999 if (isa<ClassTemplateDecl>(Specialized))
7000 EntityKind = IsPartialSpecialization? 1 : 0;
7001 else if (isa<VarTemplateDecl>(Specialized))
7002 EntityKind = IsPartialSpecialization ? 3 : 2;
7003 else if (isa<FunctionTemplateDecl>(Specialized))
7005 else if (isa<CXXMethodDecl>(Specialized))
7007 else if (isa<VarDecl>(Specialized))
7009 else if (isa<RecordDecl>(Specialized))
7011 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
7014 S.Diag(Loc, diag::err_template_spec_unknown_kind)
7015 << S.getLangOpts().CPlusPlus11;
7016 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
7020 // C++ [temp.expl.spec]p2:
7021 // An explicit specialization shall be declared in the namespace
7022 // of which the template is a member, or, for member templates, in
7023 // the namespace of which the enclosing class or enclosing class
7024 // template is a member. An explicit specialization of a member
7025 // function, member class or static data member of a class
7026 // template shall be declared in the namespace of which the class
7027 // template is a member. Such a declaration may also be a
7028 // definition. If the declaration is not a definition, the
7029 // specialization may be defined later in the name- space in which
7030 // the explicit specialization was declared, or in a namespace
7031 // that encloses the one in which the explicit specialization was
7033 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7034 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
7039 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
7040 if (S.getLangOpts().MicrosoftExt) {
7041 // Do not warn for class scope explicit specialization during
7042 // instantiation, warning was already emitted during pattern
7043 // semantic analysis.
7044 if (!S.inTemplateInstantiation())
7045 S.Diag(Loc, diag::ext_function_specialization_in_class)
7048 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
7054 if (S.CurContext->isRecord() &&
7055 !S.CurContext->Equals(Specialized->getDeclContext())) {
7056 // Make sure that we're specializing in the right record context.
7057 // Otherwise, things can go horribly wrong.
7058 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
7063 // C++ [temp.class.spec]p6:
7064 // A class template partial specialization may be declared or redeclared
7065 // in any namespace scope in which its definition may be defined (14.5.1
7067 DeclContext *SpecializedContext
7068 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
7069 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
7071 // Make sure that this redeclaration (or definition) occurs in an enclosing
7073 // Note that HandleDeclarator() performs this check for explicit
7074 // specializations of function templates, static data members, and member
7075 // functions, so we skip the check here for those kinds of entities.
7076 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
7077 // Should we refactor that check, so that it occurs later?
7078 if (!DC->Encloses(SpecializedContext) &&
7079 !(isa<FunctionTemplateDecl>(Specialized) ||
7080 isa<FunctionDecl>(Specialized) ||
7081 isa<VarTemplateDecl>(Specialized) ||
7082 isa<VarDecl>(Specialized))) {
7083 if (isa<TranslationUnitDecl>(SpecializedContext))
7084 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
7085 << EntityKind << Specialized;
7086 else if (isa<NamespaceDecl>(SpecializedContext)) {
7087 int Diag = diag::err_template_spec_redecl_out_of_scope;
7088 if (S.getLangOpts().MicrosoftExt)
7089 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
7090 S.Diag(Loc, Diag) << EntityKind << Specialized
7091 << cast<NamedDecl>(SpecializedContext);
7093 llvm_unreachable("unexpected namespace context for specialization");
7095 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
7096 } else if ((!PrevDecl ||
7097 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
7098 getTemplateSpecializationKind(PrevDecl) ==
7099 TSK_ImplicitInstantiation)) {
7100 // C++ [temp.exp.spec]p2:
7101 // An explicit specialization shall be declared in the namespace of which
7102 // the template is a member, or, for member templates, in the namespace
7103 // of which the enclosing class or enclosing class template is a member.
7104 // An explicit specialization of a member function, member class or
7105 // static data member of a class template shall be declared in the
7106 // namespace of which the class template is a member.
7108 // C++11 [temp.expl.spec]p2:
7109 // An explicit specialization shall be declared in a namespace enclosing
7110 // the specialized template.
7111 // C++11 [temp.explicit]p3:
7112 // An explicit instantiation shall appear in an enclosing namespace of its
7114 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
7115 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
7116 if (isa<TranslationUnitDecl>(SpecializedContext)) {
7117 assert(!IsCPlusPlus11Extension &&
7118 "DC encloses TU but isn't in enclosing namespace set");
7119 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
7120 << EntityKind << Specialized;
7121 } else if (isa<NamespaceDecl>(SpecializedContext)) {
7123 if (!IsCPlusPlus11Extension)
7124 Diag = diag::err_template_spec_decl_out_of_scope;
7125 else if (!S.getLangOpts().CPlusPlus11)
7126 Diag = diag::ext_template_spec_decl_out_of_scope;
7128 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
7130 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
7133 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
7140 static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
7141 if (!E->isTypeDependent())
7142 return SourceLocation();
7143 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
7144 Checker.TraverseStmt(E);
7145 if (Checker.MatchLoc.isInvalid())
7146 return E->getSourceRange();
7147 return Checker.MatchLoc;
7150 static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
7151 if (!TL.getType()->isDependentType())
7152 return SourceLocation();
7153 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
7154 Checker.TraverseTypeLoc(TL);
7155 if (Checker.MatchLoc.isInvalid())
7156 return TL.getSourceRange();
7157 return Checker.MatchLoc;
7160 /// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
7161 /// that checks non-type template partial specialization arguments.
7162 static bool CheckNonTypeTemplatePartialSpecializationArgs(
7163 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
7164 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
7165 for (unsigned I = 0; I != NumArgs; ++I) {
7166 if (Args[I].getKind() == TemplateArgument::Pack) {
7167 if (CheckNonTypeTemplatePartialSpecializationArgs(
7168 S, TemplateNameLoc, Param, Args[I].pack_begin(),
7169 Args[I].pack_size(), IsDefaultArgument))
7175 if (Args[I].getKind() != TemplateArgument::Expression)
7178 Expr *ArgExpr = Args[I].getAsExpr();
7180 // We can have a pack expansion of any of the bullets below.
7181 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
7182 ArgExpr = Expansion->getPattern();
7184 // Strip off any implicit casts we added as part of type checking.
7185 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
7186 ArgExpr = ICE->getSubExpr();
7188 // C++ [temp.class.spec]p8:
7189 // A non-type argument is non-specialized if it is the name of a
7190 // non-type parameter. All other non-type arguments are
7193 // Below, we check the two conditions that only apply to
7194 // specialized non-type arguments, so skip any non-specialized
7196 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
7197 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
7200 // C++ [temp.class.spec]p9:
7201 // Within the argument list of a class template partial
7202 // specialization, the following restrictions apply:
7203 // -- A partially specialized non-type argument expression
7204 // shall not involve a template parameter of the partial
7205 // specialization except when the argument expression is a
7206 // simple identifier.
7207 // -- The type of a template parameter corresponding to a
7208 // specialized non-type argument shall not be dependent on a
7209 // parameter of the specialization.
7210 // DR1315 removes the first bullet, leaving an incoherent set of rules.
7211 // We implement a compromise between the original rules and DR1315:
7212 // -- A specialized non-type template argument shall not be
7213 // type-dependent and the corresponding template parameter
7214 // shall have a non-dependent type.
7215 SourceRange ParamUseRange =
7216 findTemplateParameterInType(Param->getDepth(), ArgExpr);
7217 if (ParamUseRange.isValid()) {
7218 if (IsDefaultArgument) {
7219 S.Diag(TemplateNameLoc,
7220 diag::err_dependent_non_type_arg_in_partial_spec);
7221 S.Diag(ParamUseRange.getBegin(),
7222 diag::note_dependent_non_type_default_arg_in_partial_spec)
7225 S.Diag(ParamUseRange.getBegin(),
7226 diag::err_dependent_non_type_arg_in_partial_spec)
7232 ParamUseRange = findTemplateParameter(
7233 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
7234 if (ParamUseRange.isValid()) {
7235 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
7236 diag::err_dependent_typed_non_type_arg_in_partial_spec)
7237 << Param->getType();
7238 S.Diag(Param->getLocation(), diag::note_template_param_here)
7239 << (IsDefaultArgument ? ParamUseRange : SourceRange())
7248 /// \brief Check the non-type template arguments of a class template
7249 /// partial specialization according to C++ [temp.class.spec]p9.
7251 /// \param TemplateNameLoc the location of the template name.
7252 /// \param PrimaryTemplate the template parameters of the primary class
7254 /// \param NumExplicit the number of explicitly-specified template arguments.
7255 /// \param TemplateArgs the template arguments of the class template
7256 /// partial specialization.
7258 /// \returns \c true if there was an error, \c false otherwise.
7259 bool Sema::CheckTemplatePartialSpecializationArgs(
7260 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
7261 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
7262 // We have to be conservative when checking a template in a dependent
7264 if (PrimaryTemplate->getDeclContext()->isDependentContext())
7267 TemplateParameterList *TemplateParams =
7268 PrimaryTemplate->getTemplateParameters();
7269 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7270 NonTypeTemplateParmDecl *Param
7271 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
7275 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
7276 Param, &TemplateArgs[I],
7277 1, I >= NumExplicit))
7285 Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
7287 SourceLocation KWLoc,
7288 SourceLocation ModulePrivateLoc,
7289 TemplateIdAnnotation &TemplateId,
7290 AttributeList *Attr,
7291 MultiTemplateParamsArg
7292 TemplateParameterLists,
7293 SkipBodyInfo *SkipBody) {
7294 assert(TUK != TUK_Reference && "References are not specializations");
7296 CXXScopeSpec &SS = TemplateId.SS;
7298 // NOTE: KWLoc is the location of the tag keyword. This will instead
7299 // store the location of the outermost template keyword in the declaration.
7300 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
7301 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
7302 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
7303 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
7304 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
7306 // Find the class template we're specializing
7307 TemplateName Name = TemplateId.Template.get();
7308 ClassTemplateDecl *ClassTemplate
7309 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
7311 if (!ClassTemplate) {
7312 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
7313 << (Name.getAsTemplateDecl() &&
7314 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
7318 bool isMemberSpecialization = false;
7319 bool isPartialSpecialization = false;
7321 // Check the validity of the template headers that introduce this
7323 // FIXME: We probably shouldn't complain about these headers for
7324 // friend declarations.
7325 bool Invalid = false;
7326 TemplateParameterList *TemplateParams =
7327 MatchTemplateParametersToScopeSpecifier(
7328 KWLoc, TemplateNameLoc, SS, &TemplateId,
7329 TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
7334 if (TemplateParams && TemplateParams->size() > 0) {
7335 isPartialSpecialization = true;
7337 if (TUK == TUK_Friend) {
7338 Diag(KWLoc, diag::err_partial_specialization_friend)
7339 << SourceRange(LAngleLoc, RAngleLoc);
7343 // C++ [temp.class.spec]p10:
7344 // The template parameter list of a specialization shall not
7345 // contain default template argument values.
7346 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7347 Decl *Param = TemplateParams->getParam(I);
7348 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
7349 if (TTP->hasDefaultArgument()) {
7350 Diag(TTP->getDefaultArgumentLoc(),
7351 diag::err_default_arg_in_partial_spec);
7352 TTP->removeDefaultArgument();
7354 } else if (NonTypeTemplateParmDecl *NTTP
7355 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
7356 if (Expr *DefArg = NTTP->getDefaultArgument()) {
7357 Diag(NTTP->getDefaultArgumentLoc(),
7358 diag::err_default_arg_in_partial_spec)
7359 << DefArg->getSourceRange();
7360 NTTP->removeDefaultArgument();
7363 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
7364 if (TTP->hasDefaultArgument()) {
7365 Diag(TTP->getDefaultArgument().getLocation(),
7366 diag::err_default_arg_in_partial_spec)
7367 << TTP->getDefaultArgument().getSourceRange();
7368 TTP->removeDefaultArgument();
7372 } else if (TemplateParams) {
7373 if (TUK == TUK_Friend)
7374 Diag(KWLoc, diag::err_template_spec_friend)
7375 << FixItHint::CreateRemoval(
7376 SourceRange(TemplateParams->getTemplateLoc(),
7377 TemplateParams->getRAngleLoc()))
7378 << SourceRange(LAngleLoc, RAngleLoc);
7380 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
7383 // Check that the specialization uses the same tag kind as the
7384 // original template.
7385 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7386 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
7387 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
7388 Kind, TUK == TUK_Definition, KWLoc,
7389 ClassTemplate->getIdentifier())) {
7390 Diag(KWLoc, diag::err_use_with_wrong_tag)
7392 << FixItHint::CreateReplacement(KWLoc,
7393 ClassTemplate->getTemplatedDecl()->getKindName());
7394 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
7395 diag::note_previous_use);
7396 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7399 // Translate the parser's template argument list in our AST format.
7400 TemplateArgumentListInfo TemplateArgs =
7401 makeTemplateArgumentListInfo(*this, TemplateId);
7403 // Check for unexpanded parameter packs in any of the template arguments.
7404 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7405 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
7406 UPPC_PartialSpecialization))
7409 // Check that the template argument list is well-formed for this
7411 SmallVector<TemplateArgument, 4> Converted;
7412 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7413 TemplateArgs, false, Converted))
7416 // Find the class template (partial) specialization declaration that
7417 // corresponds to these arguments.
7418 if (isPartialSpecialization) {
7419 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
7420 TemplateArgs.size(), Converted))
7423 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
7424 // also do it during instantiation.
7425 bool InstantiationDependent;
7426 if (!Name.isDependent() &&
7427 !TemplateSpecializationType::anyDependentTemplateArguments(
7428 TemplateArgs.arguments(), InstantiationDependent)) {
7429 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
7430 << ClassTemplate->getDeclName();
7431 isPartialSpecialization = false;
7435 void *InsertPos = nullptr;
7436 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
7438 if (isPartialSpecialization)
7439 // FIXME: Template parameter list matters, too
7440 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
7442 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
7444 ClassTemplateSpecializationDecl *Specialization = nullptr;
7446 // Check whether we can declare a class template specialization in
7447 // the current scope.
7448 if (TUK != TUK_Friend &&
7449 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
7451 isPartialSpecialization))
7454 // The canonical type
7456 if (isPartialSpecialization) {
7457 // Build the canonical type that describes the converted template
7458 // arguments of the class template partial specialization.
7459 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7460 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
7463 if (Context.hasSameType(CanonType,
7464 ClassTemplate->getInjectedClassNameSpecialization())) {
7465 // C++ [temp.class.spec]p9b3:
7467 // -- The argument list of the specialization shall not be identical
7468 // to the implicit argument list of the primary template.
7470 // This rule has since been removed, because it's redundant given DR1495,
7471 // but we keep it because it produces better diagnostics and recovery.
7472 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
7473 << /*class template*/0 << (TUK == TUK_Definition)
7474 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
7475 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
7476 ClassTemplate->getIdentifier(),
7480 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
7481 /*FriendLoc*/SourceLocation(),
7482 TemplateParameterLists.size() - 1,
7483 TemplateParameterLists.data());
7486 // Create a new class template partial specialization declaration node.
7487 ClassTemplatePartialSpecializationDecl *PrevPartial
7488 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
7489 ClassTemplatePartialSpecializationDecl *Partial
7490 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
7491 ClassTemplate->getDeclContext(),
7492 KWLoc, TemplateNameLoc,
7499 SetNestedNameSpecifier(Partial, SS);
7500 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
7501 Partial->setTemplateParameterListsInfo(
7502 Context, TemplateParameterLists.drop_back(1));
7506 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
7507 Specialization = Partial;
7509 // If we are providing an explicit specialization of a member class
7510 // template specialization, make a note of that.
7511 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
7512 PrevPartial->setMemberSpecialization();
7514 CheckTemplatePartialSpecialization(Partial);
7516 // Create a new class template specialization declaration node for
7517 // this explicit specialization or friend declaration.
7519 = ClassTemplateSpecializationDecl::Create(Context, Kind,
7520 ClassTemplate->getDeclContext(),
7521 KWLoc, TemplateNameLoc,
7525 SetNestedNameSpecifier(Specialization, SS);
7526 if (TemplateParameterLists.size() > 0) {
7527 Specialization->setTemplateParameterListsInfo(Context,
7528 TemplateParameterLists);
7532 ClassTemplate->AddSpecialization(Specialization, InsertPos);
7534 if (CurContext->isDependentContext()) {
7535 // -fms-extensions permits specialization of nested classes without
7536 // fully specializing the outer class(es).
7537 assert(getLangOpts().MicrosoftExt &&
7538 "Only possible with -fms-extensions!");
7539 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7540 CanonType = Context.getTemplateSpecializationType(
7541 CanonTemplate, Converted);
7543 CanonType = Context.getTypeDeclType(Specialization);
7547 // C++ [temp.expl.spec]p6:
7548 // If a template, a member template or the member of a class template is
7549 // explicitly specialized then that specialization shall be declared
7550 // before the first use of that specialization that would cause an implicit
7551 // instantiation to take place, in every translation unit in which such a
7552 // use occurs; no diagnostic is required.
7553 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
7555 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
7556 // Is there any previous explicit specialization declaration?
7557 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7564 SourceRange Range(TemplateNameLoc, RAngleLoc);
7565 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
7566 << Context.getTypeDeclType(Specialization) << Range;
7568 Diag(PrevDecl->getPointOfInstantiation(),
7569 diag::note_instantiation_required_here)
7570 << (PrevDecl->getTemplateSpecializationKind()
7571 != TSK_ImplicitInstantiation);
7576 // If this is not a friend, note that this is an explicit specialization.
7577 if (TUK != TUK_Friend)
7578 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
7580 // Check that this isn't a redefinition of this specialization.
7581 if (TUK == TUK_Definition) {
7582 RecordDecl *Def = Specialization->getDefinition();
7583 NamedDecl *Hidden = nullptr;
7584 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
7585 SkipBody->ShouldSkip = true;
7586 makeMergedDefinitionVisible(Hidden);
7587 // From here on out, treat this as just a redeclaration.
7588 TUK = TUK_Declaration;
7590 SourceRange Range(TemplateNameLoc, RAngleLoc);
7591 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
7592 Diag(Def->getLocation(), diag::note_previous_definition);
7593 Specialization->setInvalidDecl();
7599 ProcessDeclAttributeList(S, Specialization, Attr);
7601 // Add alignment attributes if necessary; these attributes are checked when
7602 // the ASTContext lays out the structure.
7603 if (TUK == TUK_Definition) {
7604 AddAlignmentAttributesForRecord(Specialization);
7605 AddMsStructLayoutForRecord(Specialization);
7608 if (ModulePrivateLoc.isValid())
7609 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
7610 << (isPartialSpecialization? 1 : 0)
7611 << FixItHint::CreateRemoval(ModulePrivateLoc);
7613 // Build the fully-sugared type for this class template
7614 // specialization as the user wrote in the specialization
7615 // itself. This means that we'll pretty-print the type retrieved
7616 // from the specialization's declaration the way that the user
7617 // actually wrote the specialization, rather than formatting the
7618 // name based on the "canonical" representation used to store the
7619 // template arguments in the specialization.
7620 TypeSourceInfo *WrittenTy
7621 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7622 TemplateArgs, CanonType);
7623 if (TUK != TUK_Friend) {
7624 Specialization->setTypeAsWritten(WrittenTy);
7625 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
7628 // C++ [temp.expl.spec]p9:
7629 // A template explicit specialization is in the scope of the
7630 // namespace in which the template was defined.
7632 // We actually implement this paragraph where we set the semantic
7633 // context (in the creation of the ClassTemplateSpecializationDecl),
7634 // but we also maintain the lexical context where the actual
7635 // definition occurs.
7636 Specialization->setLexicalDeclContext(CurContext);
7638 // We may be starting the definition of this specialization.
7639 if (TUK == TUK_Definition)
7640 Specialization->startDefinition();
7642 if (TUK == TUK_Friend) {
7643 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
7647 Friend->setAccess(AS_public);
7648 CurContext->addDecl(Friend);
7650 // Add the specialization into its lexical context, so that it can
7651 // be seen when iterating through the list of declarations in that
7652 // context. However, specializations are not found by name lookup.
7653 CurContext->addDecl(Specialization);
7655 return Specialization;
7658 Decl *Sema::ActOnTemplateDeclarator(Scope *S,
7659 MultiTemplateParamsArg TemplateParameterLists,
7661 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
7662 ActOnDocumentableDecl(NewDecl);
7666 /// \brief Strips various properties off an implicit instantiation
7667 /// that has just been explicitly specialized.
7668 static void StripImplicitInstantiation(NamedDecl *D) {
7669 D->dropAttr<DLLImportAttr>();
7670 D->dropAttr<DLLExportAttr>();
7672 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
7673 FD->setInlineSpecified(false);
7676 /// \brief Compute the diagnostic location for an explicit instantiation
7677 // declaration or definition.
7678 static SourceLocation DiagLocForExplicitInstantiation(
7679 NamedDecl* D, SourceLocation PointOfInstantiation) {
7680 // Explicit instantiations following a specialization have no effect and
7681 // hence no PointOfInstantiation. In that case, walk decl backwards
7682 // until a valid name loc is found.
7683 SourceLocation PrevDiagLoc = PointOfInstantiation;
7684 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
7685 Prev = Prev->getPreviousDecl()) {
7686 PrevDiagLoc = Prev->getLocation();
7688 assert(PrevDiagLoc.isValid() &&
7689 "Explicit instantiation without point of instantiation?");
7693 /// \brief Diagnose cases where we have an explicit template specialization
7694 /// before/after an explicit template instantiation, producing diagnostics
7695 /// for those cases where they are required and determining whether the
7696 /// new specialization/instantiation will have any effect.
7698 /// \param NewLoc the location of the new explicit specialization or
7701 /// \param NewTSK the kind of the new explicit specialization or instantiation.
7703 /// \param PrevDecl the previous declaration of the entity.
7705 /// \param PrevTSK the kind of the old explicit specialization or instantiatin.
7707 /// \param PrevPointOfInstantiation if valid, indicates where the previus
7708 /// declaration was instantiated (either implicitly or explicitly).
7710 /// \param HasNoEffect will be set to true to indicate that the new
7711 /// specialization or instantiation has no effect and should be ignored.
7713 /// \returns true if there was an error that should prevent the introduction of
7714 /// the new declaration into the AST, false otherwise.
7716 Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
7717 TemplateSpecializationKind NewTSK,
7718 NamedDecl *PrevDecl,
7719 TemplateSpecializationKind PrevTSK,
7720 SourceLocation PrevPointOfInstantiation,
7721 bool &HasNoEffect) {
7722 HasNoEffect = false;
7725 case TSK_Undeclared:
7726 case TSK_ImplicitInstantiation:
7728 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
7729 "previous declaration must be implicit!");
7732 case TSK_ExplicitSpecialization:
7734 case TSK_Undeclared:
7735 case TSK_ExplicitSpecialization:
7736 // Okay, we're just specializing something that is either already
7737 // explicitly specialized or has merely been mentioned without any
7741 case TSK_ImplicitInstantiation:
7742 if (PrevPointOfInstantiation.isInvalid()) {
7743 // The declaration itself has not actually been instantiated, so it is
7744 // still okay to specialize it.
7745 StripImplicitInstantiation(PrevDecl);
7751 case TSK_ExplicitInstantiationDeclaration:
7752 case TSK_ExplicitInstantiationDefinition:
7753 assert((PrevTSK == TSK_ImplicitInstantiation ||
7754 PrevPointOfInstantiation.isValid()) &&
7755 "Explicit instantiation without point of instantiation?");
7757 // C++ [temp.expl.spec]p6:
7758 // If a template, a member template or the member of a class template
7759 // is explicitly specialized then that specialization shall be declared
7760 // before the first use of that specialization that would cause an
7761 // implicit instantiation to take place, in every translation unit in
7762 // which such a use occurs; no diagnostic is required.
7763 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
7764 // Is there any previous explicit specialization declaration?
7765 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
7769 Diag(NewLoc, diag::err_specialization_after_instantiation)
7771 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
7772 << (PrevTSK != TSK_ImplicitInstantiation);
7776 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
7778 case TSK_ExplicitInstantiationDeclaration:
7780 case TSK_ExplicitInstantiationDeclaration:
7781 // This explicit instantiation declaration is redundant (that's okay).
7785 case TSK_Undeclared:
7786 case TSK_ImplicitInstantiation:
7787 // We're explicitly instantiating something that may have already been
7788 // implicitly instantiated; that's fine.
7791 case TSK_ExplicitSpecialization:
7792 // C++0x [temp.explicit]p4:
7793 // For a given set of template parameters, if an explicit instantiation
7794 // of a template appears after a declaration of an explicit
7795 // specialization for that template, the explicit instantiation has no
7800 case TSK_ExplicitInstantiationDefinition:
7801 // C++0x [temp.explicit]p10:
7802 // If an entity is the subject of both an explicit instantiation
7803 // declaration and an explicit instantiation definition in the same
7804 // translation unit, the definition shall follow the declaration.
7806 diag::err_explicit_instantiation_declaration_after_definition);
7808 // Explicit instantiations following a specialization have no effect and
7809 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
7810 // until a valid name loc is found.
7811 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
7812 diag::note_explicit_instantiation_definition_here);
7817 case TSK_ExplicitInstantiationDefinition:
7819 case TSK_Undeclared:
7820 case TSK_ImplicitInstantiation:
7821 // We're explicitly instantiating something that may have already been
7822 // implicitly instantiated; that's fine.
7825 case TSK_ExplicitSpecialization:
7826 // C++ DR 259, C++0x [temp.explicit]p4:
7827 // For a given set of template parameters, if an explicit
7828 // instantiation of a template appears after a declaration of
7829 // an explicit specialization for that template, the explicit
7830 // instantiation has no effect.
7831 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
7833 Diag(PrevDecl->getLocation(),
7834 diag::note_previous_template_specialization);
7838 case TSK_ExplicitInstantiationDeclaration:
7839 // We're explicity instantiating a definition for something for which we
7840 // were previously asked to suppress instantiations. That's fine.
7842 // C++0x [temp.explicit]p4:
7843 // For a given set of template parameters, if an explicit instantiation
7844 // of a template appears after a declaration of an explicit
7845 // specialization for that template, the explicit instantiation has no
7847 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
7848 // Is there any previous explicit specialization declaration?
7849 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7857 case TSK_ExplicitInstantiationDefinition:
7858 // C++0x [temp.spec]p5:
7859 // For a given template and a given set of template-arguments,
7860 // - an explicit instantiation definition shall appear at most once
7863 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
7864 Diag(NewLoc, (getLangOpts().MSVCCompat)
7865 ? diag::ext_explicit_instantiation_duplicate
7866 : diag::err_explicit_instantiation_duplicate)
7868 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
7869 diag::note_previous_explicit_instantiation);
7875 llvm_unreachable("Missing specialization/instantiation case?");
7878 /// \brief Perform semantic analysis for the given dependent function
7879 /// template specialization.
7881 /// The only possible way to get a dependent function template specialization
7882 /// is with a friend declaration, like so:
7885 /// template \<class T> void foo(T);
7886 /// template \<class T> class A {
7887 /// friend void foo<>(T);
7891 /// There really isn't any useful analysis we can do here, so we
7892 /// just store the information.
7894 Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
7895 const TemplateArgumentListInfo &ExplicitTemplateArgs,
7896 LookupResult &Previous) {
7897 // Remove anything from Previous that isn't a function template in
7898 // the correct context.
7899 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
7900 LookupResult::Filter F = Previous.makeFilter();
7901 while (F.hasNext()) {
7902 NamedDecl *D = F.next()->getUnderlyingDecl();
7903 if (!isa<FunctionTemplateDecl>(D) ||
7904 !FDLookupContext->InEnclosingNamespaceSetOf(
7905 D->getDeclContext()->getRedeclContext()))
7910 // Should this be diagnosed here?
7911 if (Previous.empty()) return true;
7913 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
7914 ExplicitTemplateArgs);
7918 /// \brief Perform semantic analysis for the given function template
7921 /// This routine performs all of the semantic analysis required for an
7922 /// explicit function template specialization. On successful completion,
7923 /// the function declaration \p FD will become a function template
7926 /// \param FD the function declaration, which will be updated to become a
7927 /// function template specialization.
7929 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
7930 /// if any. Note that this may be valid info even when 0 arguments are
7931 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
7932 /// as it anyway contains info on the angle brackets locations.
7934 /// \param Previous the set of declarations that may be specialized by
7935 /// this function specialization.
7936 bool Sema::CheckFunctionTemplateSpecialization(
7937 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
7938 LookupResult &Previous) {
7939 // The set of function template specializations that could match this
7940 // explicit function template specialization.
7941 UnresolvedSet<8> Candidates;
7942 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
7943 /*ForTakingAddress=*/false);
7945 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
7946 ConvertedTemplateArgs;
7948 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
7949 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7951 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
7952 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
7953 // Only consider templates found within the same semantic lookup scope as
7955 if (!FDLookupContext->InEnclosingNamespaceSetOf(
7956 Ovl->getDeclContext()->getRedeclContext()))
7959 // When matching a constexpr member function template specialization
7960 // against the primary template, we don't yet know whether the
7961 // specialization has an implicit 'const' (because we don't know whether
7962 // it will be a static member function until we know which template it
7963 // specializes), so adjust it now assuming it specializes this template.
7964 QualType FT = FD->getType();
7965 if (FD->isConstexpr()) {
7966 CXXMethodDecl *OldMD =
7967 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
7968 if (OldMD && OldMD->isConst()) {
7969 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
7970 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7971 EPI.TypeQuals |= Qualifiers::Const;
7972 FT = Context.getFunctionType(FPT->getReturnType(),
7973 FPT->getParamTypes(), EPI);
7977 TemplateArgumentListInfo Args;
7978 if (ExplicitTemplateArgs)
7979 Args = *ExplicitTemplateArgs;
7981 // C++ [temp.expl.spec]p11:
7982 // A trailing template-argument can be left unspecified in the
7983 // template-id naming an explicit function template specialization
7984 // provided it can be deduced from the function argument type.
7985 // Perform template argument deduction to determine whether we may be
7986 // specializing this template.
7987 // FIXME: It is somewhat wasteful to build
7988 TemplateDeductionInfo Info(FailedCandidates.getLocation());
7989 FunctionDecl *Specialization = nullptr;
7990 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
7991 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
7992 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
7994 // Template argument deduction failed; record why it failed, so
7995 // that we can provide nifty diagnostics.
7996 FailedCandidates.addCandidate().set(
7997 I.getPair(), FunTmpl->getTemplatedDecl(),
7998 MakeDeductionFailureInfo(Context, TDK, Info));
8003 // Target attributes are part of the cuda function signature, so
8004 // the deduced template's cuda target must match that of the
8005 // specialization. Given that C++ template deduction does not
8006 // take target attributes into account, we reject candidates
8007 // here that have a different target.
8008 if (LangOpts.CUDA &&
8009 IdentifyCUDATarget(Specialization,
8010 /* IgnoreImplicitHDAttributes = */ true) !=
8011 IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttributes = */ true)) {
8012 FailedCandidates.addCandidate().set(
8013 I.getPair(), FunTmpl->getTemplatedDecl(),
8014 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
8018 // Record this candidate.
8019 if (ExplicitTemplateArgs)
8020 ConvertedTemplateArgs[Specialization] = std::move(Args);
8021 Candidates.addDecl(Specialization, I.getAccess());
8025 // Find the most specialized function template.
8026 UnresolvedSetIterator Result = getMostSpecialized(
8027 Candidates.begin(), Candidates.end(), FailedCandidates,
8029 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
8030 PDiag(diag::err_function_template_spec_ambiguous)
8031 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
8032 PDiag(diag::note_function_template_spec_matched));
8034 if (Result == Candidates.end())
8037 // Ignore access information; it doesn't figure into redeclaration checking.
8038 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
8040 FunctionTemplateSpecializationInfo *SpecInfo
8041 = Specialization->getTemplateSpecializationInfo();
8042 assert(SpecInfo && "Function template specialization info missing?");
8044 // Note: do not overwrite location info if previous template
8045 // specialization kind was explicit.
8046 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
8047 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
8048 Specialization->setLocation(FD->getLocation());
8049 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
8050 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
8051 // function can differ from the template declaration with respect to
8052 // the constexpr specifier.
8053 // FIXME: We need an update record for this AST mutation.
8054 // FIXME: What if there are multiple such prior declarations (for instance,
8055 // from different modules)?
8056 Specialization->setConstexpr(FD->isConstexpr());
8059 // FIXME: Check if the prior specialization has a point of instantiation.
8060 // If so, we have run afoul of .
8062 // If this is a friend declaration, then we're not really declaring
8063 // an explicit specialization.
8064 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
8066 // Check the scope of this explicit specialization.
8068 CheckTemplateSpecializationScope(*this,
8069 Specialization->getPrimaryTemplate(),
8070 Specialization, FD->getLocation(),
8074 // C++ [temp.expl.spec]p6:
8075 // If a template, a member template or the member of a class template is
8076 // explicitly specialized then that specialization shall be declared
8077 // before the first use of that specialization that would cause an implicit
8078 // instantiation to take place, in every translation unit in which such a
8079 // use occurs; no diagnostic is required.
8080 bool HasNoEffect = false;
8082 CheckSpecializationInstantiationRedecl(FD->getLocation(),
8083 TSK_ExplicitSpecialization,
8085 SpecInfo->getTemplateSpecializationKind(),
8086 SpecInfo->getPointOfInstantiation(),
8090 // Mark the prior declaration as an explicit specialization, so that later
8091 // clients know that this is an explicit specialization.
8093 // Since explicit specializations do not inherit '=delete' from their
8094 // primary function template - check if the 'specialization' that was
8095 // implicitly generated (during template argument deduction for partial
8096 // ordering) from the most specialized of all the function templates that
8097 // 'FD' could have been specializing, has a 'deleted' definition. If so,
8098 // first check that it was implicitly generated during template argument
8099 // deduction by making sure it wasn't referenced, and then reset the deleted
8100 // flag to not-deleted, so that we can inherit that information from 'FD'.
8101 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
8102 !Specialization->getCanonicalDecl()->isReferenced()) {
8103 // FIXME: This assert will not hold in the presence of modules.
8105 Specialization->getCanonicalDecl() == Specialization &&
8106 "This must be the only existing declaration of this specialization");
8107 // FIXME: We need an update record for this AST mutation.
8108 Specialization->setDeletedAsWritten(false);
8110 // FIXME: We need an update record for this AST mutation.
8111 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
8112 MarkUnusedFileScopedDecl(Specialization);
8115 // Turn the given function declaration into a function template
8116 // specialization, with the template arguments from the previous
8118 // Take copies of (semantic and syntactic) template argument lists.
8119 const TemplateArgumentList* TemplArgs = new (Context)
8120 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
8121 FD->setFunctionTemplateSpecialization(
8122 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
8123 SpecInfo->getTemplateSpecializationKind(),
8124 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
8126 // A function template specialization inherits the target attributes
8127 // of its template. (We require the attributes explicitly in the
8128 // code to match, but a template may have implicit attributes by
8129 // virtue e.g. of being constexpr, and it passes these implicit
8130 // attributes on to its specializations.)
8132 inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
8134 // The "previous declaration" for this function template specialization is
8135 // the prior function template specialization.
8137 Previous.addDecl(Specialization);
8141 /// \brief Perform semantic analysis for the given non-template member
8144 /// This routine performs all of the semantic analysis required for an
8145 /// explicit member function specialization. On successful completion,
8146 /// the function declaration \p FD will become a member function
8149 /// \param Member the member declaration, which will be updated to become a
8152 /// \param Previous the set of declarations, one of which may be specialized
8153 /// by this function specialization; the set will be modified to contain the
8154 /// redeclared member.
8156 Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
8157 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
8159 // Try to find the member we are instantiating.
8160 NamedDecl *FoundInstantiation = nullptr;
8161 NamedDecl *Instantiation = nullptr;
8162 NamedDecl *InstantiatedFrom = nullptr;
8163 MemberSpecializationInfo *MSInfo = nullptr;
8165 if (Previous.empty()) {
8166 // Nowhere to look anyway.
8167 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
8168 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8170 NamedDecl *D = (*I)->getUnderlyingDecl();
8171 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
8172 QualType Adjusted = Function->getType();
8173 if (!hasExplicitCallingConv(Adjusted))
8174 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
8175 if (Context.hasSameType(Adjusted, Method->getType())) {
8176 FoundInstantiation = *I;
8177 Instantiation = Method;
8178 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
8179 MSInfo = Method->getMemberSpecializationInfo();
8184 } else if (isa<VarDecl>(Member)) {
8186 if (Previous.isSingleResult() &&
8187 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
8188 if (PrevVar->isStaticDataMember()) {
8189 FoundInstantiation = Previous.getRepresentativeDecl();
8190 Instantiation = PrevVar;
8191 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
8192 MSInfo = PrevVar->getMemberSpecializationInfo();
8194 } else if (isa<RecordDecl>(Member)) {
8195 CXXRecordDecl *PrevRecord;
8196 if (Previous.isSingleResult() &&
8197 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
8198 FoundInstantiation = Previous.getRepresentativeDecl();
8199 Instantiation = PrevRecord;
8200 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
8201 MSInfo = PrevRecord->getMemberSpecializationInfo();
8203 } else if (isa<EnumDecl>(Member)) {
8205 if (Previous.isSingleResult() &&
8206 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
8207 FoundInstantiation = Previous.getRepresentativeDecl();
8208 Instantiation = PrevEnum;
8209 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
8210 MSInfo = PrevEnum->getMemberSpecializationInfo();
8214 if (!Instantiation) {
8215 // There is no previous declaration that matches. Since member
8216 // specializations are always out-of-line, the caller will complain about
8217 // this mismatch later.
8221 // A member specialization in a friend declaration isn't really declaring
8222 // an explicit specialization, just identifying a specific (possibly implicit)
8223 // specialization. Don't change the template specialization kind.
8225 // FIXME: Is this really valid? Other compilers reject.
8226 if (Member->getFriendObjectKind() != Decl::FOK_None) {
8227 // Preserve instantiation information.
8228 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
8229 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
8230 cast<CXXMethodDecl>(InstantiatedFrom),
8231 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
8232 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
8233 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
8234 cast<CXXRecordDecl>(InstantiatedFrom),
8235 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
8239 Previous.addDecl(FoundInstantiation);
8243 // Make sure that this is a specialization of a member.
8244 if (!InstantiatedFrom) {
8245 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
8247 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
8251 // C++ [temp.expl.spec]p6:
8252 // If a template, a member template or the member of a class template is
8253 // explicitly specialized then that specialization shall be declared
8254 // before the first use of that specialization that would cause an implicit
8255 // instantiation to take place, in every translation unit in which such a
8256 // use occurs; no diagnostic is required.
8257 assert(MSInfo && "Member specialization info missing?");
8259 bool HasNoEffect = false;
8260 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
8261 TSK_ExplicitSpecialization,
8263 MSInfo->getTemplateSpecializationKind(),
8264 MSInfo->getPointOfInstantiation(),
8268 // Check the scope of this explicit specialization.
8269 if (CheckTemplateSpecializationScope(*this,
8271 Instantiation, Member->getLocation(),
8275 // Note that this member specialization is an "instantiation of" the
8276 // corresponding member of the original template.
8277 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
8278 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
8279 if (InstantiationFunction->getTemplateSpecializationKind() ==
8280 TSK_ImplicitInstantiation) {
8281 // Explicit specializations of member functions of class templates do not
8282 // inherit '=delete' from the member function they are specializing.
8283 if (InstantiationFunction->isDeleted()) {
8284 // FIXME: This assert will not hold in the presence of modules.
8285 assert(InstantiationFunction->getCanonicalDecl() ==
8286 InstantiationFunction);
8287 // FIXME: We need an update record for this AST mutation.
8288 InstantiationFunction->setDeletedAsWritten(false);
8292 MemberFunction->setInstantiationOfMemberFunction(
8293 cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8294 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
8295 MemberVar->setInstantiationOfStaticDataMember(
8296 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8297 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
8298 MemberClass->setInstantiationOfMemberClass(
8299 cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8300 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
8301 MemberEnum->setInstantiationOfMemberEnum(
8302 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8304 llvm_unreachable("unknown member specialization kind");
8307 // Save the caller the trouble of having to figure out which declaration
8308 // this specialization matches.
8310 Previous.addDecl(FoundInstantiation);
8314 /// Complete the explicit specialization of a member of a class template by
8315 /// updating the instantiated member to be marked as an explicit specialization.
8317 /// \param OrigD The member declaration instantiated from the template.
8318 /// \param Loc The location of the explicit specialization of the member.
8319 template<typename DeclT>
8320 static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
8321 SourceLocation Loc) {
8322 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
8325 // FIXME: Inform AST mutation listeners of this AST mutation.
8326 // FIXME: If there are multiple in-class declarations of the member (from
8327 // multiple modules, or a declaration and later definition of a member type),
8328 // should we update all of them?
8329 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
8330 OrigD->setLocation(Loc);
8333 void Sema::CompleteMemberSpecialization(NamedDecl *Member,
8334 LookupResult &Previous) {
8335 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
8336 if (Instantiation == Member)
8339 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
8340 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
8341 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
8342 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
8343 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
8344 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
8345 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
8346 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
8348 llvm_unreachable("unknown member specialization kind");
8351 /// \brief Check the scope of an explicit instantiation.
8353 /// \returns true if a serious error occurs, false otherwise.
8354 static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
8355 SourceLocation InstLoc,
8356 bool WasQualifiedName) {
8357 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
8358 DeclContext *CurContext = S.CurContext->getRedeclContext();
8360 if (CurContext->isRecord()) {
8361 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
8366 // C++11 [temp.explicit]p3:
8367 // An explicit instantiation shall appear in an enclosing namespace of its
8368 // template. If the name declared in the explicit instantiation is an
8369 // unqualified name, the explicit instantiation shall appear in the
8370 // namespace where its template is declared or, if that namespace is inline
8371 // (7.3.1), any namespace from its enclosing namespace set.
8373 // This is DR275, which we do not retroactively apply to C++98/03.
8374 if (WasQualifiedName) {
8375 if (CurContext->Encloses(OrigContext))
8378 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
8382 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
8383 if (WasQualifiedName)
8385 S.getLangOpts().CPlusPlus11?
8386 diag::err_explicit_instantiation_out_of_scope :
8387 diag::warn_explicit_instantiation_out_of_scope_0x)
8391 S.getLangOpts().CPlusPlus11?
8392 diag::err_explicit_instantiation_unqualified_wrong_namespace :
8393 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
8397 S.getLangOpts().CPlusPlus11?
8398 diag::err_explicit_instantiation_must_be_global :
8399 diag::warn_explicit_instantiation_must_be_global_0x)
8401 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
8405 /// \brief Determine whether the given scope specifier has a template-id in it.
8406 static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
8410 // C++11 [temp.explicit]p3:
8411 // If the explicit instantiation is for a member function, a member class
8412 // or a static data member of a class template specialization, the name of
8413 // the class template specialization in the qualified-id for the member
8414 // name shall be a simple-template-id.
8416 // C++98 has the same restriction, just worded differently.
8417 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
8418 NNS = NNS->getPrefix())
8419 if (const Type *T = NNS->getAsType())
8420 if (isa<TemplateSpecializationType>(T))
8426 /// Make a dllexport or dllimport attr on a class template specialization take
8428 static void dllExportImportClassTemplateSpecialization(
8429 Sema &S, ClassTemplateSpecializationDecl *Def) {
8430 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
8431 assert(A && "dllExportImportClassTemplateSpecialization called "
8432 "on Def without dllexport or dllimport");
8434 // We reject explicit instantiations in class scope, so there should
8435 // never be any delayed exported classes to worry about.
8436 assert(S.DelayedDllExportClasses.empty() &&
8437 "delayed exports present at explicit instantiation");
8438 S.checkClassLevelDLLAttribute(Def);
8440 // Propagate attribute to base class templates.
8441 for (auto &B : Def->bases()) {
8442 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
8443 B.getType()->getAsCXXRecordDecl()))
8444 S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getLocStart());
8447 S.referenceDLLExportedClassMethods();
8450 // Explicit instantiation of a class template specialization
8452 Sema::ActOnExplicitInstantiation(Scope *S,
8453 SourceLocation ExternLoc,
8454 SourceLocation TemplateLoc,
8456 SourceLocation KWLoc,
8457 const CXXScopeSpec &SS,
8458 TemplateTy TemplateD,
8459 SourceLocation TemplateNameLoc,
8460 SourceLocation LAngleLoc,
8461 ASTTemplateArgsPtr TemplateArgsIn,
8462 SourceLocation RAngleLoc,
8463 AttributeList *Attr) {
8464 // Find the class template we're specializing
8465 TemplateName Name = TemplateD.get();
8466 TemplateDecl *TD = Name.getAsTemplateDecl();
8467 // Check that the specialization uses the same tag kind as the
8468 // original template.
8469 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8470 assert(Kind != TTK_Enum &&
8471 "Invalid enum tag in class template explicit instantiation!");
8473 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
8475 if (!ClassTemplate) {
8476 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
8477 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
8478 Diag(TD->getLocation(), diag::note_previous_use);
8482 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
8483 Kind, /*isDefinition*/false, KWLoc,
8484 ClassTemplate->getIdentifier())) {
8485 Diag(KWLoc, diag::err_use_with_wrong_tag)
8487 << FixItHint::CreateReplacement(KWLoc,
8488 ClassTemplate->getTemplatedDecl()->getKindName());
8489 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8490 diag::note_previous_use);
8491 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8494 // C++0x [temp.explicit]p2:
8495 // There are two forms of explicit instantiation: an explicit instantiation
8496 // definition and an explicit instantiation declaration. An explicit
8497 // instantiation declaration begins with the extern keyword. [...]
8498 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
8499 ? TSK_ExplicitInstantiationDefinition
8500 : TSK_ExplicitInstantiationDeclaration;
8502 if (TSK == TSK_ExplicitInstantiationDeclaration) {
8503 // Check for dllexport class template instantiation declarations.
8504 for (AttributeList *A = Attr; A; A = A->getNext()) {
8505 if (A->getKind() == AttributeList::AT_DLLExport) {
8507 diag::warn_attribute_dllexport_explicit_instantiation_decl);
8508 Diag(A->getLoc(), diag::note_attribute);
8513 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
8515 diag::warn_attribute_dllexport_explicit_instantiation_decl);
8516 Diag(A->getLocation(), diag::note_attribute);
8520 // In MSVC mode, dllimported explicit instantiation definitions are treated as
8521 // instantiation declarations for most purposes.
8522 bool DLLImportExplicitInstantiationDef = false;
8523 if (TSK == TSK_ExplicitInstantiationDefinition &&
8524 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
8525 // Check for dllimport class template instantiation definitions.
8527 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
8528 for (AttributeList *A = Attr; A; A = A->getNext()) {
8529 if (A->getKind() == AttributeList::AT_DLLImport)
8531 if (A->getKind() == AttributeList::AT_DLLExport) {
8532 // dllexport trumps dllimport here.
8538 TSK = TSK_ExplicitInstantiationDeclaration;
8539 DLLImportExplicitInstantiationDef = true;
8543 // Translate the parser's template argument list in our AST format.
8544 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
8545 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
8547 // Check that the template argument list is well-formed for this
8549 SmallVector<TemplateArgument, 4> Converted;
8550 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
8551 TemplateArgs, false, Converted))
8554 // Find the class template specialization declaration that
8555 // corresponds to these arguments.
8556 void *InsertPos = nullptr;
8557 ClassTemplateSpecializationDecl *PrevDecl
8558 = ClassTemplate->findSpecialization(Converted, InsertPos);
8560 TemplateSpecializationKind PrevDecl_TSK
8561 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
8563 // C++0x [temp.explicit]p2:
8564 // [...] An explicit instantiation shall appear in an enclosing
8565 // namespace of its template. [...]
8567 // This is C++ DR 275.
8568 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
8572 ClassTemplateSpecializationDecl *Specialization = nullptr;
8574 bool HasNoEffect = false;
8576 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
8577 PrevDecl, PrevDecl_TSK,
8578 PrevDecl->getPointOfInstantiation(),
8582 // Even though HasNoEffect == true means that this explicit instantiation
8583 // has no effect on semantics, we go on to put its syntax in the AST.
8585 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
8586 PrevDecl_TSK == TSK_Undeclared) {
8587 // Since the only prior class template specialization with these
8588 // arguments was referenced but not declared, reuse that
8589 // declaration node as our own, updating the source location
8590 // for the template name to reflect our new declaration.
8591 // (Other source locations will be updated later.)
8592 Specialization = PrevDecl;
8593 Specialization->setLocation(TemplateNameLoc);
8597 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
8598 DLLImportExplicitInstantiationDef) {
8599 // The new specialization might add a dllimport attribute.
8600 HasNoEffect = false;
8604 if (!Specialization) {
8605 // Create a new class template specialization declaration node for
8606 // this explicit specialization.
8608 = ClassTemplateSpecializationDecl::Create(Context, Kind,
8609 ClassTemplate->getDeclContext(),
8610 KWLoc, TemplateNameLoc,
8614 SetNestedNameSpecifier(Specialization, SS);
8616 if (!HasNoEffect && !PrevDecl) {
8617 // Insert the new specialization.
8618 ClassTemplate->AddSpecialization(Specialization, InsertPos);
8622 // Build the fully-sugared type for this explicit instantiation as
8623 // the user wrote in the explicit instantiation itself. This means
8624 // that we'll pretty-print the type retrieved from the
8625 // specialization's declaration the way that the user actually wrote
8626 // the explicit instantiation, rather than formatting the name based
8627 // on the "canonical" representation used to store the template
8628 // arguments in the specialization.
8629 TypeSourceInfo *WrittenTy
8630 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
8632 Context.getTypeDeclType(Specialization));
8633 Specialization->setTypeAsWritten(WrittenTy);
8635 // Set source locations for keywords.
8636 Specialization->setExternLoc(ExternLoc);
8637 Specialization->setTemplateKeywordLoc(TemplateLoc);
8638 Specialization->setBraceRange(SourceRange());
8640 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
8642 ProcessDeclAttributeList(S, Specialization, Attr);
8644 // Add the explicit instantiation into its lexical context. However,
8645 // since explicit instantiations are never found by name lookup, we
8646 // just put it into the declaration context directly.
8647 Specialization->setLexicalDeclContext(CurContext);
8648 CurContext->addDecl(Specialization);
8650 // Syntax is now OK, so return if it has no other effect on semantics.
8652 // Set the template specialization kind.
8653 Specialization->setTemplateSpecializationKind(TSK);
8654 return Specialization;
8657 // C++ [temp.explicit]p3:
8658 // A definition of a class template or class member template
8659 // shall be in scope at the point of the explicit instantiation of
8660 // the class template or class member template.
8662 // This check comes when we actually try to perform the
8664 ClassTemplateSpecializationDecl *Def
8665 = cast_or_null<ClassTemplateSpecializationDecl>(
8666 Specialization->getDefinition());
8668 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
8669 else if (TSK == TSK_ExplicitInstantiationDefinition) {
8670 MarkVTableUsed(TemplateNameLoc, Specialization, true);
8671 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
8674 // Instantiate the members of this class template specialization.
8675 Def = cast_or_null<ClassTemplateSpecializationDecl>(
8676 Specialization->getDefinition());
8678 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
8679 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
8680 // TSK_ExplicitInstantiationDefinition
8681 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
8682 (TSK == TSK_ExplicitInstantiationDefinition ||
8683 DLLImportExplicitInstantiationDef)) {
8684 // FIXME: Need to notify the ASTMutationListener that we did this.
8685 Def->setTemplateSpecializationKind(TSK);
8687 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
8688 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8689 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
8690 // In the MS ABI, an explicit instantiation definition can add a dll
8691 // attribute to a template with a previous instantiation declaration.
8692 // MinGW doesn't allow this.
8693 auto *A = cast<InheritableAttr>(
8694 getDLLAttr(Specialization)->clone(getASTContext()));
8695 A->setInherited(true);
8697 dllExportImportClassTemplateSpecialization(*this, Def);
8701 // Fix a TSK_ImplicitInstantiation followed by a
8702 // TSK_ExplicitInstantiationDefinition
8703 bool NewlyDLLExported =
8704 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
8705 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
8706 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8707 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
8708 // In the MS ABI, an explicit instantiation definition can add a dll
8709 // attribute to a template with a previous implicit instantiation.
8710 // MinGW doesn't allow this. We limit clang to only adding dllexport, to
8711 // avoid potentially strange codegen behavior. For example, if we extend
8712 // this conditional to dllimport, and we have a source file calling a
8713 // method on an implicitly instantiated template class instance and then
8714 // declaring a dllimport explicit instantiation definition for the same
8715 // template class, the codegen for the method call will not respect the
8716 // dllimport, while it will with cl. The Def will already have the DLL
8717 // attribute, since the Def and Specialization will be the same in the
8718 // case of Old_TSK == TSK_ImplicitInstantiation, and we already added the
8719 // attribute to the Specialization; we just need to make it take effect.
8720 assert(Def == Specialization &&
8721 "Def and Specialization should match for implicit instantiation");
8722 dllExportImportClassTemplateSpecialization(*this, Def);
8725 // Set the template specialization kind. Make sure it is set before
8726 // instantiating the members which will trigger ASTConsumer callbacks.
8727 Specialization->setTemplateSpecializationKind(TSK);
8728 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
8731 // Set the template specialization kind.
8732 Specialization->setTemplateSpecializationKind(TSK);
8735 return Specialization;
8738 // Explicit instantiation of a member class of a class template.
8740 Sema::ActOnExplicitInstantiation(Scope *S,
8741 SourceLocation ExternLoc,
8742 SourceLocation TemplateLoc,
8744 SourceLocation KWLoc,
8746 IdentifierInfo *Name,
8747 SourceLocation NameLoc,
8748 AttributeList *Attr) {
8751 bool IsDependent = false;
8752 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
8753 KWLoc, SS, Name, NameLoc, Attr, AS_none,
8754 /*ModulePrivateLoc=*/SourceLocation(),
8755 MultiTemplateParamsArg(), Owned, IsDependent,
8756 SourceLocation(), false, TypeResult(),
8757 /*IsTypeSpecifier*/false,
8758 /*IsTemplateParamOrArg*/false);
8759 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
8764 TagDecl *Tag = cast<TagDecl>(TagD);
8765 assert(!Tag->isEnum() && "shouldn't see enumerations here");
8767 if (Tag->isInvalidDecl())
8770 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
8771 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
8773 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
8774 << Context.getTypeDeclType(Record);
8775 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
8779 // C++0x [temp.explicit]p2:
8780 // If the explicit instantiation is for a class or member class, the
8781 // elaborated-type-specifier in the declaration shall include a
8782 // simple-template-id.
8784 // C++98 has the same restriction, just worded differently.
8785 if (!ScopeSpecifierHasTemplateId(SS))
8786 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
8787 << Record << SS.getRange();
8789 // C++0x [temp.explicit]p2:
8790 // There are two forms of explicit instantiation: an explicit instantiation
8791 // definition and an explicit instantiation declaration. An explicit
8792 // instantiation declaration begins with the extern keyword. [...]
8793 TemplateSpecializationKind TSK
8794 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
8795 : TSK_ExplicitInstantiationDeclaration;
8797 // C++0x [temp.explicit]p2:
8798 // [...] An explicit instantiation shall appear in an enclosing
8799 // namespace of its template. [...]
8801 // This is C++ DR 275.
8802 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
8804 // Verify that it is okay to explicitly instantiate here.
8805 CXXRecordDecl *PrevDecl
8806 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
8807 if (!PrevDecl && Record->getDefinition())
8810 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
8811 bool HasNoEffect = false;
8812 assert(MSInfo && "No member specialization information?");
8813 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
8815 MSInfo->getTemplateSpecializationKind(),
8816 MSInfo->getPointOfInstantiation(),
8823 CXXRecordDecl *RecordDef
8824 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
8826 // C++ [temp.explicit]p3:
8827 // A definition of a member class of a class template shall be in scope
8828 // at the point of an explicit instantiation of the member class.
8830 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
8832 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
8833 << 0 << Record->getDeclName() << Record->getDeclContext();
8834 Diag(Pattern->getLocation(), diag::note_forward_declaration)
8838 if (InstantiateClass(NameLoc, Record, Def,
8839 getTemplateInstantiationArgs(Record),
8843 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
8849 // Instantiate all of the members of the class.
8850 InstantiateClassMembers(NameLoc, RecordDef,
8851 getTemplateInstantiationArgs(Record), TSK);
8853 if (TSK == TSK_ExplicitInstantiationDefinition)
8854 MarkVTableUsed(NameLoc, RecordDef, true);
8856 // FIXME: We don't have any representation for explicit instantiations of
8857 // member classes. Such a representation is not needed for compilation, but it
8858 // should be available for clients that want to see all of the declarations in
8863 DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
8864 SourceLocation ExternLoc,
8865 SourceLocation TemplateLoc,
8867 // Explicit instantiations always require a name.
8868 // TODO: check if/when DNInfo should replace Name.
8869 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8870 DeclarationName Name = NameInfo.getName();
8872 if (!D.isInvalidType())
8873 Diag(D.getDeclSpec().getLocStart(),
8874 diag::err_explicit_instantiation_requires_name)
8875 << D.getDeclSpec().getSourceRange()
8876 << D.getSourceRange();
8881 // The scope passed in may not be a decl scope. Zip up the scope tree until
8882 // we find one that is.
8883 while ((S->getFlags() & Scope::DeclScope) == 0 ||
8884 (S->getFlags() & Scope::TemplateParamScope) != 0)
8887 // Determine the type of the declaration.
8888 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
8889 QualType R = T->getType();
8894 // A storage-class-specifier shall not be specified in [...] an explicit
8895 // instantiation (14.7.2) directive.
8896 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
8897 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
8900 } else if (D.getDeclSpec().getStorageClassSpec()
8901 != DeclSpec::SCS_unspecified) {
8902 // Complain about then remove the storage class specifier.
8903 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
8904 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8906 D.getMutableDeclSpec().ClearStorageClassSpecs();
8909 // C++0x [temp.explicit]p1:
8910 // [...] An explicit instantiation of a function template shall not use the
8911 // inline or constexpr specifiers.
8912 // Presumably, this also applies to member functions of class templates as
8914 if (D.getDeclSpec().isInlineSpecified())
8915 Diag(D.getDeclSpec().getInlineSpecLoc(),
8916 getLangOpts().CPlusPlus11 ?
8917 diag::err_explicit_instantiation_inline :
8918 diag::warn_explicit_instantiation_inline_0x)
8919 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8920 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
8921 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
8922 // not already specified.
8923 Diag(D.getDeclSpec().getConstexprSpecLoc(),
8924 diag::err_explicit_instantiation_constexpr);
8926 // A deduction guide is not on the list of entities that can be explicitly
8928 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8929 Diag(D.getDeclSpec().getLocStart(), diag::err_deduction_guide_specialized)
8930 << /*explicit instantiation*/ 0;
8934 // C++0x [temp.explicit]p2:
8935 // There are two forms of explicit instantiation: an explicit instantiation
8936 // definition and an explicit instantiation declaration. An explicit
8937 // instantiation declaration begins with the extern keyword. [...]
8938 TemplateSpecializationKind TSK
8939 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
8940 : TSK_ExplicitInstantiationDeclaration;
8942 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
8943 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
8945 if (!R->isFunctionType()) {
8946 // C++ [temp.explicit]p1:
8947 // A [...] static data member of a class template can be explicitly
8948 // instantiated from the member definition associated with its class
8950 // C++1y [temp.explicit]p1:
8951 // A [...] variable [...] template specialization can be explicitly
8952 // instantiated from its template.
8953 if (Previous.isAmbiguous())
8956 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
8957 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
8959 if (!PrevTemplate) {
8960 if (!Prev || !Prev->isStaticDataMember()) {
8961 // We expect to see a data data member here.
8962 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
8964 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
8966 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
8970 if (!Prev->getInstantiatedFromStaticDataMember()) {
8971 // FIXME: Check for explicit specialization?
8972 Diag(D.getIdentifierLoc(),
8973 diag::err_explicit_instantiation_data_member_not_instantiated)
8975 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
8976 // FIXME: Can we provide a note showing where this was declared?
8980 // Explicitly instantiate a variable template.
8982 // C++1y [dcl.spec.auto]p6:
8983 // ... A program that uses auto or decltype(auto) in a context not
8984 // explicitly allowed in this section is ill-formed.
8986 // This includes auto-typed variable template instantiations.
8987 if (R->isUndeducedType()) {
8988 Diag(T->getTypeLoc().getLocStart(),
8989 diag::err_auto_not_allowed_var_inst);
8993 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
8994 // C++1y [temp.explicit]p3:
8995 // If the explicit instantiation is for a variable, the unqualified-id
8996 // in the declaration shall be a template-id.
8997 Diag(D.getIdentifierLoc(),
8998 diag::err_explicit_instantiation_without_template_id)
9000 Diag(PrevTemplate->getLocation(),
9001 diag::note_explicit_instantiation_here);
9005 // Translate the parser's template argument list into our AST format.
9006 TemplateArgumentListInfo TemplateArgs =
9007 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
9009 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
9010 D.getIdentifierLoc(), TemplateArgs);
9011 if (Res.isInvalid())
9014 // Ignore access control bits, we don't need them for redeclaration
9016 Prev = cast<VarDecl>(Res.get());
9019 // C++0x [temp.explicit]p2:
9020 // If the explicit instantiation is for a member function, a member class
9021 // or a static data member of a class template specialization, the name of
9022 // the class template specialization in the qualified-id for the member
9023 // name shall be a simple-template-id.
9025 // C++98 has the same restriction, just worded differently.
9027 // This does not apply to variable template specializations, where the
9028 // template-id is in the unqualified-id instead.
9029 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
9030 Diag(D.getIdentifierLoc(),
9031 diag::ext_explicit_instantiation_without_qualified_id)
9032 << Prev << D.getCXXScopeSpec().getRange();
9034 // Check the scope of this explicit instantiation.
9035 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
9037 // Verify that it is okay to explicitly instantiate here.
9038 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
9039 SourceLocation POI = Prev->getPointOfInstantiation();
9040 bool HasNoEffect = false;
9041 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
9042 PrevTSK, POI, HasNoEffect))
9046 // Instantiate static data member or variable template.
9047 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
9049 // Merge attributes.
9050 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
9051 ProcessDeclAttributeList(S, Prev, Attr);
9053 if (TSK == TSK_ExplicitInstantiationDefinition)
9054 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
9057 // Check the new variable specialization against the parsed input.
9058 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
9059 Diag(T->getTypeLoc().getLocStart(),
9060 diag::err_invalid_var_template_spec_type)
9061 << 0 << PrevTemplate << R << Prev->getType();
9062 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
9063 << 2 << PrevTemplate->getDeclName();
9067 // FIXME: Create an ExplicitInstantiation node?
9068 return (Decl*) nullptr;
9071 // If the declarator is a template-id, translate the parser's template
9072 // argument list into our AST format.
9073 bool HasExplicitTemplateArgs = false;
9074 TemplateArgumentListInfo TemplateArgs;
9075 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
9076 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
9077 HasExplicitTemplateArgs = true;
9080 // C++ [temp.explicit]p1:
9081 // A [...] function [...] can be explicitly instantiated from its template.
9082 // A member function [...] of a class template can be explicitly
9083 // instantiated from the member definition associated with its class
9085 UnresolvedSet<8> TemplateMatches;
9086 FunctionDecl *NonTemplateMatch = nullptr;
9087 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
9088 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
9089 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9091 NamedDecl *Prev = *P;
9092 if (!HasExplicitTemplateArgs) {
9093 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
9094 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
9095 /*AdjustExceptionSpec*/true);
9096 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
9097 if (Method->getPrimaryTemplate()) {
9098 TemplateMatches.addDecl(Method, P.getAccess());
9100 // FIXME: Can this assert ever happen? Needs a test.
9101 assert(!NonTemplateMatch && "Multiple NonTemplateMatches");
9102 NonTemplateMatch = Method;
9108 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
9112 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9113 FunctionDecl *Specialization = nullptr;
9114 if (TemplateDeductionResult TDK
9115 = DeduceTemplateArguments(FunTmpl,
9116 (HasExplicitTemplateArgs ? &TemplateArgs
9118 R, Specialization, Info)) {
9119 // Keep track of almost-matches.
9120 FailedCandidates.addCandidate()
9121 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
9122 MakeDeductionFailureInfo(Context, TDK, Info));
9127 // Target attributes are part of the cuda function signature, so
9128 // the cuda target of the instantiated function must match that of its
9129 // template. Given that C++ template deduction does not take
9130 // target attributes into account, we reject candidates here that
9131 // have a different target.
9132 if (LangOpts.CUDA &&
9133 IdentifyCUDATarget(Specialization,
9134 /* IgnoreImplicitHDAttributes = */ true) !=
9135 IdentifyCUDATarget(Attr)) {
9136 FailedCandidates.addCandidate().set(
9137 P.getPair(), FunTmpl->getTemplatedDecl(),
9138 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
9142 TemplateMatches.addDecl(Specialization, P.getAccess());
9145 FunctionDecl *Specialization = NonTemplateMatch;
9146 if (!Specialization) {
9147 // Find the most specialized function template specialization.
9148 UnresolvedSetIterator Result = getMostSpecialized(
9149 TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates,
9150 D.getIdentifierLoc(),
9151 PDiag(diag::err_explicit_instantiation_not_known) << Name,
9152 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
9153 PDiag(diag::note_explicit_instantiation_candidate));
9155 if (Result == TemplateMatches.end())
9158 // Ignore access control bits, we don't need them for redeclaration checking.
9159 Specialization = cast<FunctionDecl>(*Result);
9162 // C++11 [except.spec]p4
9163 // In an explicit instantiation an exception-specification may be specified,
9164 // but is not required.
9165 // If an exception-specification is specified in an explicit instantiation
9166 // directive, it shall be compatible with the exception-specifications of
9167 // other declarations of that function.
9168 if (auto *FPT = R->getAs<FunctionProtoType>())
9169 if (FPT->hasExceptionSpec()) {
9171 diag::err_mismatched_exception_spec_explicit_instantiation;
9172 if (getLangOpts().MicrosoftExt)
9173 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
9174 bool Result = CheckEquivalentExceptionSpec(
9175 PDiag(DiagID) << Specialization->getType(),
9176 PDiag(diag::note_explicit_instantiation_here),
9177 Specialization->getType()->getAs<FunctionProtoType>(),
9178 Specialization->getLocation(), FPT, D.getLocStart());
9179 // In Microsoft mode, mismatching exception specifications just cause a
9181 if (!getLangOpts().MicrosoftExt && Result)
9185 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
9186 Diag(D.getIdentifierLoc(),
9187 diag::err_explicit_instantiation_member_function_not_instantiated)
9189 << (Specialization->getTemplateSpecializationKind() ==
9190 TSK_ExplicitSpecialization);
9191 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
9195 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
9196 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
9197 PrevDecl = Specialization;
9200 bool HasNoEffect = false;
9201 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
9203 PrevDecl->getTemplateSpecializationKind(),
9204 PrevDecl->getPointOfInstantiation(),
9208 // FIXME: We may still want to build some representation of this
9209 // explicit specialization.
9211 return (Decl*) nullptr;
9215 ProcessDeclAttributeList(S, Specialization, Attr);
9217 // In MSVC mode, dllimported explicit instantiation definitions are treated as
9218 // instantiation declarations.
9219 if (TSK == TSK_ExplicitInstantiationDefinition &&
9220 Specialization->hasAttr<DLLImportAttr>() &&
9221 Context.getTargetInfo().getCXXABI().isMicrosoft())
9222 TSK = TSK_ExplicitInstantiationDeclaration;
9224 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
9226 if (Specialization->isDefined()) {
9227 // Let the ASTConsumer know that this function has been explicitly
9228 // instantiated now, and its linkage might have changed.
9229 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
9230 } else if (TSK == TSK_ExplicitInstantiationDefinition)
9231 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
9233 // C++0x [temp.explicit]p2:
9234 // If the explicit instantiation is for a member function, a member class
9235 // or a static data member of a class template specialization, the name of
9236 // the class template specialization in the qualified-id for the member
9237 // name shall be a simple-template-id.
9239 // C++98 has the same restriction, just worded differently.
9240 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
9241 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
9242 D.getCXXScopeSpec().isSet() &&
9243 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
9244 Diag(D.getIdentifierLoc(),
9245 diag::ext_explicit_instantiation_without_qualified_id)
9246 << Specialization << D.getCXXScopeSpec().getRange();
9248 CheckExplicitInstantiationScope(*this,
9249 FunTmpl? (NamedDecl *)FunTmpl
9250 : Specialization->getInstantiatedFromMemberFunction(),
9251 D.getIdentifierLoc(),
9252 D.getCXXScopeSpec().isSet());
9254 // FIXME: Create some kind of ExplicitInstantiationDecl here.
9255 return (Decl*) nullptr;
9259 Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
9260 const CXXScopeSpec &SS, IdentifierInfo *Name,
9261 SourceLocation TagLoc, SourceLocation NameLoc) {
9262 // This has to hold, because SS is expected to be defined.
9263 assert(Name && "Expected a name in a dependent tag");
9265 NestedNameSpecifier *NNS = SS.getScopeRep();
9269 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9271 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
9272 Diag(NameLoc, diag::err_dependent_tag_decl)
9273 << (TUK == TUK_Definition) << Kind << SS.getRange();
9277 // Create the resulting type.
9278 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9279 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
9281 // Create type-source location information for this type.
9283 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
9284 TL.setElaboratedKeywordLoc(TagLoc);
9285 TL.setQualifierLoc(SS.getWithLocInContext(Context));
9286 TL.setNameLoc(NameLoc);
9287 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
9291 Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
9292 const CXXScopeSpec &SS, const IdentifierInfo &II,
9293 SourceLocation IdLoc) {
9297 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9299 getLangOpts().CPlusPlus11 ?
9300 diag::warn_cxx98_compat_typename_outside_of_template :
9301 diag::ext_typename_outside_of_template)
9302 << FixItHint::CreateRemoval(TypenameLoc);
9304 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9305 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
9306 TypenameLoc, QualifierLoc, II, IdLoc);
9310 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9311 if (isa<DependentNameType>(T)) {
9312 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
9313 TL.setElaboratedKeywordLoc(TypenameLoc);
9314 TL.setQualifierLoc(QualifierLoc);
9315 TL.setNameLoc(IdLoc);
9317 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
9318 TL.setElaboratedKeywordLoc(TypenameLoc);
9319 TL.setQualifierLoc(QualifierLoc);
9320 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
9323 return CreateParsedType(T, TSI);
9327 Sema::ActOnTypenameType(Scope *S,
9328 SourceLocation TypenameLoc,
9329 const CXXScopeSpec &SS,
9330 SourceLocation TemplateKWLoc,
9331 TemplateTy TemplateIn,
9332 IdentifierInfo *TemplateII,
9333 SourceLocation TemplateIILoc,
9334 SourceLocation LAngleLoc,
9335 ASTTemplateArgsPtr TemplateArgsIn,
9336 SourceLocation RAngleLoc) {
9337 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9339 getLangOpts().CPlusPlus11 ?
9340 diag::warn_cxx98_compat_typename_outside_of_template :
9341 diag::ext_typename_outside_of_template)
9342 << FixItHint::CreateRemoval(TypenameLoc);
9344 // Strangely, non-type results are not ignored by this lookup, so the
9345 // program is ill-formed if it finds an injected-class-name.
9346 if (TypenameLoc.isValid()) {
9348 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
9349 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
9351 diag::ext_out_of_line_qualified_id_type_names_constructor)
9352 << TemplateII << 0 /*injected-class-name used as template name*/
9353 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
9357 // Translate the parser's template argument list in our AST format.
9358 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9359 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
9361 TemplateName Template = TemplateIn.get();
9362 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
9363 // Construct a dependent template specialization type.
9364 assert(DTN && "dependent template has non-dependent name?");
9365 assert(DTN->getQualifier() == SS.getScopeRep());
9366 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
9367 DTN->getQualifier(),
9368 DTN->getIdentifier(),
9371 // Create source-location information for this type.
9372 TypeLocBuilder Builder;
9373 DependentTemplateSpecializationTypeLoc SpecTL
9374 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
9375 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
9376 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
9377 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
9378 SpecTL.setTemplateNameLoc(TemplateIILoc);
9379 SpecTL.setLAngleLoc(LAngleLoc);
9380 SpecTL.setRAngleLoc(RAngleLoc);
9381 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9382 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
9383 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
9386 QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
9390 // Provide source-location information for the template specialization type.
9391 TypeLocBuilder Builder;
9392 TemplateSpecializationTypeLoc SpecTL
9393 = Builder.push<TemplateSpecializationTypeLoc>(T);
9394 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
9395 SpecTL.setTemplateNameLoc(TemplateIILoc);
9396 SpecTL.setLAngleLoc(LAngleLoc);
9397 SpecTL.setRAngleLoc(RAngleLoc);
9398 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9399 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
9401 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
9402 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
9403 TL.setElaboratedKeywordLoc(TypenameLoc);
9404 TL.setQualifierLoc(SS.getWithLocInContext(Context));
9406 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
9407 return CreateParsedType(T, TSI);
9411 /// Determine whether this failed name lookup should be treated as being
9412 /// disabled by a usage of std::enable_if.
9413 static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
9414 SourceRange &CondRange, Expr *&Cond) {
9415 // We must be looking for a ::type...
9416 if (!II.isStr("type"))
9419 // ... within an explicitly-written template specialization...
9420 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
9422 TypeLoc EnableIfTy = NNS.getTypeLoc();
9423 TemplateSpecializationTypeLoc EnableIfTSTLoc =
9424 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
9425 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
9427 const TemplateSpecializationType *EnableIfTST =
9428 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
9430 // ... which names a complete class template declaration...
9431 const TemplateDecl *EnableIfDecl =
9432 EnableIfTST->getTemplateName().getAsTemplateDecl();
9433 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
9436 // ... called "enable_if".
9437 const IdentifierInfo *EnableIfII =
9438 EnableIfDecl->getDeclName().getAsIdentifierInfo();
9439 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
9442 // Assume the first template argument is the condition.
9443 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
9445 // Dig out the condition.
9447 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
9448 != TemplateArgument::Expression)
9451 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
9453 // Ignore Boolean literals; they add no value.
9454 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
9460 /// \brief Build the type that describes a C++ typename specifier,
9461 /// e.g., "typename T::type".
9463 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
9464 SourceLocation KeywordLoc,
9465 NestedNameSpecifierLoc QualifierLoc,
9466 const IdentifierInfo &II,
9467 SourceLocation IILoc) {
9469 SS.Adopt(QualifierLoc);
9471 DeclContext *Ctx = computeDeclContext(SS);
9473 // If the nested-name-specifier is dependent and couldn't be
9474 // resolved to a type, build a typename type.
9475 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
9476 return Context.getDependentNameType(Keyword,
9477 QualifierLoc.getNestedNameSpecifier(),
9481 // If the nested-name-specifier refers to the current instantiation,
9482 // the "typename" keyword itself is superfluous. In C++03, the
9483 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
9484 // allows such extraneous "typename" keywords, and we retroactively
9485 // apply this DR to C++03 code with only a warning. In any case we continue.
9487 if (RequireCompleteDeclContext(SS, Ctx))
9490 DeclarationName Name(&II);
9491 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
9492 LookupQualifiedName(Result, Ctx, SS);
9493 unsigned DiagID = 0;
9494 Decl *Referenced = nullptr;
9495 switch (Result.getResultKind()) {
9496 case LookupResult::NotFound: {
9497 // If we're looking up 'type' within a template named 'enable_if', produce
9498 // a more specific diagnostic.
9499 SourceRange CondRange;
9500 Expr *Cond = nullptr;
9501 if (isEnableIf(QualifierLoc, II, CondRange, Cond)) {
9502 // If we have a condition, narrow it down to the specific failed
9506 std::string FailedDescription;
9507 std::tie(FailedCond, FailedDescription) =
9508 findFailedBooleanCondition(Cond, /*AllowTopLevelCond=*/true);
9510 Diag(FailedCond->getExprLoc(),
9511 diag::err_typename_nested_not_found_requirement)
9512 << FailedDescription
9513 << FailedCond->getSourceRange();
9517 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
9518 << Ctx << CondRange;
9522 DiagID = diag::err_typename_nested_not_found;
9526 case LookupResult::FoundUnresolvedValue: {
9527 // We found a using declaration that is a value. Most likely, the using
9528 // declaration itself is meant to have the 'typename' keyword.
9529 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
9531 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
9532 << Name << Ctx << FullRange;
9533 if (UnresolvedUsingValueDecl *Using
9534 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
9535 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
9536 Diag(Loc, diag::note_using_value_decl_missing_typename)
9537 << FixItHint::CreateInsertion(Loc, "typename ");
9540 // Fall through to create a dependent typename type, from which we can recover
9544 case LookupResult::NotFoundInCurrentInstantiation:
9545 // Okay, it's a member of an unknown instantiation.
9546 return Context.getDependentNameType(Keyword,
9547 QualifierLoc.getNestedNameSpecifier(),
9550 case LookupResult::Found:
9551 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
9552 // C++ [class.qual]p2:
9553 // In a lookup in which function names are not ignored and the
9554 // nested-name-specifier nominates a class C, if the name specified
9555 // after the nested-name-specifier, when looked up in C, is the
9556 // injected-class-name of C [...] then the name is instead considered
9557 // to name the constructor of class C.
9559 // Unlike in an elaborated-type-specifier, function names are not ignored
9560 // in typename-specifier lookup. However, they are ignored in all the
9561 // contexts where we form a typename type with no keyword (that is, in
9562 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
9564 // FIXME: That's not strictly true: mem-initializer-id lookup does not
9565 // ignore functions, but that appears to be an oversight.
9566 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
9567 auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
9568 if (Keyword == ETK_Typename && LookupRD && FoundRD &&
9569 FoundRD->isInjectedClassName() &&
9570 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
9571 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
9572 << &II << 1 << 0 /*'typename' keyword used*/;
9574 // We found a type. Build an ElaboratedType, since the
9575 // typename-specifier was just sugar.
9576 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
9577 return Context.getElaboratedType(Keyword,
9578 QualifierLoc.getNestedNameSpecifier(),
9579 Context.getTypeDeclType(Type));
9582 // C++ [dcl.type.simple]p2:
9583 // A type-specifier of the form
9584 // typename[opt] nested-name-specifier[opt] template-name
9585 // is a placeholder for a deduced class type [...].
9586 if (getLangOpts().CPlusPlus17) {
9587 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
9588 return Context.getElaboratedType(
9589 Keyword, QualifierLoc.getNestedNameSpecifier(),
9590 Context.getDeducedTemplateSpecializationType(TemplateName(TD),
9591 QualType(), false));
9595 DiagID = diag::err_typename_nested_not_type;
9596 Referenced = Result.getFoundDecl();
9599 case LookupResult::FoundOverloaded:
9600 DiagID = diag::err_typename_nested_not_type;
9601 Referenced = *Result.begin();
9604 case LookupResult::Ambiguous:
9608 // If we get here, it's because name lookup did not find a
9609 // type. Emit an appropriate diagnostic and return an error.
9610 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
9612 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
9614 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
9620 // See Sema::RebuildTypeInCurrentInstantiation
9621 class CurrentInstantiationRebuilder
9622 : public TreeTransform<CurrentInstantiationRebuilder> {
9624 DeclarationName Entity;
9627 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
9629 CurrentInstantiationRebuilder(Sema &SemaRef,
9631 DeclarationName Entity)
9632 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
9633 Loc(Loc), Entity(Entity) { }
9635 /// \brief Determine whether the given type \p T has already been
9638 /// For the purposes of type reconstruction, a type has already been
9639 /// transformed if it is NULL or if it is not dependent.
9640 bool AlreadyTransformed(QualType T) {
9641 return T.isNull() || !T->isDependentType();
9644 /// \brief Returns the location of the entity whose type is being
9646 SourceLocation getBaseLocation() { return Loc; }
9648 /// \brief Returns the name of the entity whose type is being rebuilt.
9649 DeclarationName getBaseEntity() { return Entity; }
9651 /// \brief Sets the "base" location and entity when that
9652 /// information is known based on another transformation.
9653 void setBase(SourceLocation Loc, DeclarationName Entity) {
9655 this->Entity = Entity;
9658 ExprResult TransformLambdaExpr(LambdaExpr *E) {
9659 // Lambdas never need to be transformed.
9663 } // end anonymous namespace
9665 /// \brief Rebuilds a type within the context of the current instantiation.
9667 /// The type \p T is part of the type of an out-of-line member definition of
9668 /// a class template (or class template partial specialization) that was parsed
9669 /// and constructed before we entered the scope of the class template (or
9670 /// partial specialization thereof). This routine will rebuild that type now
9671 /// that we have entered the declarator's scope, which may produce different
9672 /// canonical types, e.g.,
9675 /// template<typename T>
9677 /// typedef T* pointer;
9681 /// template<typename T>
9682 /// typename X<T>::pointer X<T>::data() { ... }
9685 /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
9686 /// since we do not know that we can look into X<T> when we parsed the type.
9687 /// This function will rebuild the type, performing the lookup of "pointer"
9688 /// in X<T> and returning an ElaboratedType whose canonical type is the same
9689 /// as the canonical type of T*, allowing the return types of the out-of-line
9690 /// definition and the declaration to match.
9691 TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
9693 DeclarationName Name) {
9694 if (!T || !T->getType()->isDependentType())
9697 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
9698 return Rebuilder.TransformType(T);
9701 ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
9702 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
9704 return Rebuilder.TransformExpr(E);
9707 bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
9711 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9712 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
9714 NestedNameSpecifierLoc Rebuilt
9715 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
9723 /// \brief Rebuild the template parameters now that we know we're in a current
9725 bool Sema::RebuildTemplateParamsInCurrentInstantiation(
9726 TemplateParameterList *Params) {
9727 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
9728 Decl *Param = Params->getParam(I);
9730 // There is nothing to rebuild in a type parameter.
9731 if (isa<TemplateTypeParmDecl>(Param))
9734 // Rebuild the template parameter list of a template template parameter.
9735 if (TemplateTemplateParmDecl *TTP
9736 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
9737 if (RebuildTemplateParamsInCurrentInstantiation(
9738 TTP->getTemplateParameters()))
9744 // Rebuild the type of a non-type template parameter.
9745 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
9746 TypeSourceInfo *NewTSI
9747 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
9748 NTTP->getLocation(),
9749 NTTP->getDeclName());
9753 if (NewTSI != NTTP->getTypeSourceInfo()) {
9754 NTTP->setTypeSourceInfo(NewTSI);
9755 NTTP->setType(NewTSI->getType());
9762 /// \brief Produces a formatted string that describes the binding of
9763 /// template parameters to template arguments.
9765 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
9766 const TemplateArgumentList &Args) {
9767 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
9771 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
9772 const TemplateArgument *Args,
9774 SmallString<128> Str;
9775 llvm::raw_svector_ostream Out(Str);
9777 if (!Params || Params->size() == 0 || NumArgs == 0)
9778 return std::string();
9780 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
9789 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
9790 Out << Id->getName();
9796 Args[I].print(getPrintingPolicy(), Out);
9803 void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
9804 CachedTokens &Toks) {
9808 auto LPT = llvm::make_unique<LateParsedTemplate>();
9810 // Take tokens to avoid allocations
9811 LPT->Toks.swap(Toks);
9813 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
9815 FD->setLateTemplateParsed(true);
9818 void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
9821 FD->setLateTemplateParsed(false);
9824 bool Sema::IsInsideALocalClassWithinATemplateFunction() {
9825 DeclContext *DC = CurContext;
9828 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
9829 const FunctionDecl *FD = RD->isLocalClass();
9830 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
9831 } else if (DC->isTranslationUnit() || DC->isNamespace())
9834 DC = DC->getParent();
9840 /// \brief Walk the path from which a declaration was instantiated, and check
9841 /// that every explicit specialization along that path is visible. This enforces
9842 /// C++ [temp.expl.spec]/6:
9844 /// If a template, a member template or a member of a class template is
9845 /// explicitly specialized then that specialization shall be declared before
9846 /// the first use of that specialization that would cause an implicit
9847 /// instantiation to take place, in every translation unit in which such a
9848 /// use occurs; no diagnostic is required.
9850 /// and also C++ [temp.class.spec]/1:
9852 /// A partial specialization shall be declared before the first use of a
9853 /// class template specialization that would make use of the partial
9854 /// specialization as the result of an implicit or explicit instantiation
9855 /// in every translation unit in which such a use occurs; no diagnostic is
9857 class ExplicitSpecializationVisibilityChecker {
9860 llvm::SmallVector<Module *, 8> Modules;
9863 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
9866 void check(NamedDecl *ND) {
9867 if (auto *FD = dyn_cast<FunctionDecl>(ND))
9868 return checkImpl(FD);
9869 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
9870 return checkImpl(RD);
9871 if (auto *VD = dyn_cast<VarDecl>(ND))
9872 return checkImpl(VD);
9873 if (auto *ED = dyn_cast<EnumDecl>(ND))
9874 return checkImpl(ED);
9878 void diagnose(NamedDecl *D, bool IsPartialSpec) {
9879 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
9880 : Sema::MissingImportKind::ExplicitSpecialization;
9881 const bool Recover = true;
9883 // If we got a custom set of modules (because only a subset of the
9884 // declarations are interesting), use them, otherwise let
9885 // diagnoseMissingImport intelligently pick some.
9886 if (Modules.empty())
9887 S.diagnoseMissingImport(Loc, D, Kind, Recover);
9889 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
9892 // Check a specific declaration. There are three problematic cases:
9894 // 1) The declaration is an explicit specialization of a template
9896 // 2) The declaration is an explicit specialization of a member of an
9898 // 3) The declaration is an instantiation of a template, and that template
9899 // is an explicit specialization of a member of a templated class.
9901 // We don't need to go any deeper than that, as the instantiation of the
9902 // surrounding class / etc is not triggered by whatever triggered this
9903 // instantiation, and thus should be checked elsewhere.
9904 template<typename SpecDecl>
9905 void checkImpl(SpecDecl *Spec) {
9906 bool IsHiddenExplicitSpecialization = false;
9907 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
9908 IsHiddenExplicitSpecialization =
9909 Spec->getMemberSpecializationInfo()
9910 ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
9911 : !S.hasVisibleExplicitSpecialization(Spec, &Modules);
9913 checkInstantiated(Spec);
9916 if (IsHiddenExplicitSpecialization)
9917 diagnose(Spec->getMostRecentDecl(), false);
9920 void checkInstantiated(FunctionDecl *FD) {
9921 if (auto *TD = FD->getPrimaryTemplate())
9925 void checkInstantiated(CXXRecordDecl *RD) {
9926 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
9930 auto From = SD->getSpecializedTemplateOrPartial();
9931 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
9934 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
9935 if (!S.hasVisibleDeclaration(TD))
9941 void checkInstantiated(VarDecl *RD) {
9942 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
9946 auto From = SD->getSpecializedTemplateOrPartial();
9947 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
9950 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
9951 if (!S.hasVisibleDeclaration(TD))
9957 void checkInstantiated(EnumDecl *FD) {}
9959 template<typename TemplDecl>
9960 void checkTemplate(TemplDecl *TD) {
9961 if (TD->isMemberSpecialization()) {
9962 if (!S.hasVisibleMemberSpecialization(TD, &Modules))
9963 diagnose(TD->getMostRecentDecl(), false);
9967 } // end anonymous namespace
9969 void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
9970 if (!getLangOpts().Modules)
9973 ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
9976 /// \brief Check whether a template partial specialization that we've discovered
9977 /// is hidden, and produce suitable diagnostics if so.
9978 void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
9980 llvm::SmallVector<Module *, 8> Modules;
9981 if (!hasVisibleDeclaration(Spec, &Modules))
9982 diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
9983 MissingImportKind::PartialSpecialization,