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 /// ActOnDependentIdExpression - Handle a dependent id-expression that
459 /// was just parsed. This is only possible with an explicit scope
460 /// specifier naming a dependent type.
462 Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
463 SourceLocation TemplateKWLoc,
464 const DeclarationNameInfo &NameInfo,
465 bool isAddressOfOperand,
466 const TemplateArgumentListInfo *TemplateArgs) {
467 DeclContext *DC = getFunctionLevelDeclContext();
469 // C++11 [expr.prim.general]p12:
470 // An id-expression that denotes a non-static data member or non-static
471 // member function of a class can only be used:
473 // - if that id-expression denotes a non-static data member and it
474 // appears in an unevaluated operand.
476 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
477 // CXXDependentScopeMemberExpr. The former can instantiate to either
478 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
479 // always a MemberExpr.
480 bool MightBeCxx11UnevalField =
481 getLangOpts().CPlusPlus11 && isUnevaluatedContext();
483 // Check if the nested name specifier is an enum type.
485 if (NestedNameSpecifier *NNS = SS.getScopeRep())
486 IsEnum = dyn_cast_or_null<EnumType>(NNS->getAsType());
488 if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
489 isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
490 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
492 // Since the 'this' expression is synthesized, we don't need to
493 // perform the double-lookup check.
494 NamedDecl *FirstQualifierInScope = nullptr;
496 return CXXDependentScopeMemberExpr::Create(
497 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
498 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
499 FirstQualifierInScope, NameInfo, TemplateArgs);
502 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
506 Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
507 SourceLocation TemplateKWLoc,
508 const DeclarationNameInfo &NameInfo,
509 const TemplateArgumentListInfo *TemplateArgs) {
510 return DependentScopeDeclRefExpr::Create(
511 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
516 /// Determine whether we would be unable to instantiate this template (because
517 /// it either has no definition, or is in the process of being instantiated).
518 bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
519 NamedDecl *Instantiation,
520 bool InstantiatedFromMember,
521 const NamedDecl *Pattern,
522 const NamedDecl *PatternDef,
523 TemplateSpecializationKind TSK,
524 bool Complain /*= true*/) {
525 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
526 isa<VarDecl>(Instantiation));
528 bool IsEntityBeingDefined = false;
529 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
530 IsEntityBeingDefined = TD->isBeingDefined();
532 if (PatternDef && !IsEntityBeingDefined) {
533 NamedDecl *SuggestedDef = nullptr;
534 if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
535 /*OnlyNeedComplete*/false)) {
536 // If we're allowed to diagnose this and recover, do so.
537 bool Recover = Complain && !isSFINAEContext();
539 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
540 Sema::MissingImportKind::Definition, Recover);
546 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
549 llvm::Optional<unsigned> Note;
550 QualType InstantiationTy;
551 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
552 InstantiationTy = Context.getTypeDeclType(TD);
554 Diag(PointOfInstantiation,
555 diag::err_template_instantiate_within_definition)
556 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
558 // Not much point in noting the template declaration here, since
559 // we're lexically inside it.
560 Instantiation->setInvalidDecl();
561 } else if (InstantiatedFromMember) {
562 if (isa<FunctionDecl>(Instantiation)) {
563 Diag(PointOfInstantiation,
564 diag::err_explicit_instantiation_undefined_member)
565 << /*member function*/ 1 << Instantiation->getDeclName()
566 << Instantiation->getDeclContext();
567 Note = diag::note_explicit_instantiation_here;
569 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
570 Diag(PointOfInstantiation,
571 diag::err_implicit_instantiate_member_undefined)
573 Note = diag::note_member_declared_at;
576 if (isa<FunctionDecl>(Instantiation)) {
577 Diag(PointOfInstantiation,
578 diag::err_explicit_instantiation_undefined_func_template)
580 Note = diag::note_explicit_instantiation_here;
581 } else if (isa<TagDecl>(Instantiation)) {
582 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
583 << (TSK != TSK_ImplicitInstantiation)
585 Note = diag::note_template_decl_here;
587 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
588 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
589 Diag(PointOfInstantiation,
590 diag::err_explicit_instantiation_undefined_var_template)
592 Instantiation->setInvalidDecl();
594 Diag(PointOfInstantiation,
595 diag::err_explicit_instantiation_undefined_member)
596 << /*static data member*/ 2 << Instantiation->getDeclName()
597 << Instantiation->getDeclContext();
598 Note = diag::note_explicit_instantiation_here;
601 if (Note) // Diagnostics were emitted.
602 Diag(Pattern->getLocation(), Note.getValue());
604 // In general, Instantiation isn't marked invalid to get more than one
605 // error for multiple undefined instantiations. But the code that does
606 // explicit declaration -> explicit definition conversion can't handle
607 // invalid declarations, so mark as invalid in that case.
608 if (TSK == TSK_ExplicitInstantiationDeclaration)
609 Instantiation->setInvalidDecl();
613 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
614 /// that the template parameter 'PrevDecl' is being shadowed by a new
615 /// declaration at location Loc. Returns true to indicate that this is
616 /// an error, and false otherwise.
617 void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
618 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
620 // Microsoft Visual C++ permits template parameters to be shadowed.
621 if (getLangOpts().MicrosoftExt)
624 // C++ [temp.local]p4:
625 // A template-parameter shall not be redeclared within its
626 // scope (including nested scopes).
627 Diag(Loc, diag::err_template_param_shadow)
628 << cast<NamedDecl>(PrevDecl)->getDeclName();
629 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
632 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
633 /// the parameter D to reference the templated declaration and return a pointer
634 /// to the template declaration. Otherwise, do nothing to D and return null.
635 TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
636 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
637 D = Temp->getTemplatedDecl();
643 ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
644 SourceLocation EllipsisLoc) const {
645 assert(Kind == Template &&
646 "Only template template arguments can be pack expansions here");
647 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
648 "Template template argument pack expansion without packs");
649 ParsedTemplateArgument Result(*this);
650 Result.EllipsisLoc = EllipsisLoc;
654 static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
655 const ParsedTemplateArgument &Arg) {
657 switch (Arg.getKind()) {
658 case ParsedTemplateArgument::Type: {
660 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
662 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
663 return TemplateArgumentLoc(TemplateArgument(T), DI);
666 case ParsedTemplateArgument::NonType: {
667 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
668 return TemplateArgumentLoc(TemplateArgument(E), E);
671 case ParsedTemplateArgument::Template: {
672 TemplateName Template = Arg.getAsTemplate().get();
673 TemplateArgument TArg;
674 if (Arg.getEllipsisLoc().isValid())
675 TArg = TemplateArgument(Template, Optional<unsigned int>());
678 return TemplateArgumentLoc(TArg,
679 Arg.getScopeSpec().getWithLocInContext(
682 Arg.getEllipsisLoc());
686 llvm_unreachable("Unhandled parsed template argument");
689 /// \brief Translates template arguments as provided by the parser
690 /// into template arguments used by semantic analysis.
691 void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
692 TemplateArgumentListInfo &TemplateArgs) {
693 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
694 TemplateArgs.addArgument(translateTemplateArgument(*this,
698 static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
700 IdentifierInfo *Name) {
701 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
702 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration);
703 if (PrevDecl && PrevDecl->isTemplateParameter())
704 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
707 /// ActOnTypeParameter - Called when a C++ template type parameter
708 /// (e.g., "typename T") has been parsed. Typename specifies whether
709 /// the keyword "typename" was used to declare the type parameter
710 /// (otherwise, "class" was used), and KeyLoc is the location of the
711 /// "class" or "typename" keyword. ParamName is the name of the
712 /// parameter (NULL indicates an unnamed template parameter) and
713 /// ParamNameLoc is the location of the parameter name (if any).
714 /// If the type parameter has a default argument, it will be added
715 /// later via ActOnTypeParameterDefault.
716 Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
717 SourceLocation EllipsisLoc,
718 SourceLocation KeyLoc,
719 IdentifierInfo *ParamName,
720 SourceLocation ParamNameLoc,
721 unsigned Depth, unsigned Position,
722 SourceLocation EqualLoc,
723 ParsedType DefaultArg) {
724 assert(S->isTemplateParamScope() &&
725 "Template type parameter not in template parameter scope!");
727 SourceLocation Loc = ParamNameLoc;
731 bool IsParameterPack = EllipsisLoc.isValid();
732 TemplateTypeParmDecl *Param
733 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
734 KeyLoc, Loc, Depth, Position, ParamName,
735 Typename, IsParameterPack);
736 Param->setAccess(AS_public);
739 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
741 // Add the template parameter into the current scope.
743 IdResolver.AddDecl(Param);
746 // C++0x [temp.param]p9:
747 // A default template-argument may be specified for any kind of
748 // template-parameter that is not a template parameter pack.
749 if (DefaultArg && IsParameterPack) {
750 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
751 DefaultArg = nullptr;
754 // Handle the default argument, if provided.
756 TypeSourceInfo *DefaultTInfo;
757 GetTypeFromParser(DefaultArg, &DefaultTInfo);
759 assert(DefaultTInfo && "expected source information for type");
761 // Check for unexpanded parameter packs.
762 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
763 UPPC_DefaultArgument))
766 // Check the template argument itself.
767 if (CheckTemplateArgument(Param, DefaultTInfo)) {
768 Param->setInvalidDecl();
772 Param->setDefaultArgument(DefaultTInfo);
778 /// \brief Check that the type of a non-type template parameter is
781 /// \returns the (possibly-promoted) parameter type if valid;
782 /// otherwise, produces a diagnostic and returns a NULL type.
783 QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
784 SourceLocation Loc) {
785 if (TSI->getType()->isUndeducedType()) {
786 // C++1z [temp.dep.expr]p3:
787 // An id-expression is type-dependent if it contains
788 // - an identifier associated by name lookup with a non-type
789 // template-parameter declared with a type that contains a
790 // placeholder type (7.1.7.4),
791 TSI = SubstAutoTypeSourceInfo(TSI, Context.DependentTy);
794 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
797 QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
798 SourceLocation Loc) {
799 // We don't allow variably-modified types as the type of non-type template
801 if (T->isVariablyModifiedType()) {
802 Diag(Loc, diag::err_variably_modified_nontype_template_param)
807 // C++ [temp.param]p4:
809 // A non-type template-parameter shall have one of the following
810 // (optionally cv-qualified) types:
812 // -- integral or enumeration type,
813 if (T->isIntegralOrEnumerationType() ||
814 // -- pointer to object or pointer to function,
815 T->isPointerType() ||
816 // -- reference to object or reference to function,
817 T->isReferenceType() ||
818 // -- pointer to member,
819 T->isMemberPointerType() ||
820 // -- std::nullptr_t.
821 T->isNullPtrType() ||
822 // If T is a dependent type, we can't do the check now, so we
823 // assume that it is well-formed.
824 T->isDependentType() ||
825 // Allow use of auto in template parameter declarations.
826 T->isUndeducedType()) {
827 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
828 // are ignored when determining its type.
829 return T.getUnqualifiedType();
832 // C++ [temp.param]p8:
834 // A non-type template-parameter of type "array of T" or
835 // "function returning T" is adjusted to be of type "pointer to
836 // T" or "pointer to function returning T", respectively.
837 else if (T->isArrayType() || T->isFunctionType())
838 return Context.getDecayedType(T);
840 Diag(Loc, diag::err_template_nontype_parm_bad_type)
846 Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
849 SourceLocation EqualLoc,
851 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
853 if (TInfo->getType()->isUndeducedType()) {
854 Diag(D.getIdentifierLoc(),
855 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
856 << QualType(TInfo->getType()->getContainedAutoType(), 0);
859 assert(S->isTemplateParamScope() &&
860 "Non-type template parameter not in template parameter scope!");
861 bool Invalid = false;
863 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
865 T = Context.IntTy; // Recover with an 'int' type.
869 IdentifierInfo *ParamName = D.getIdentifier();
870 bool IsParameterPack = D.hasEllipsis();
871 NonTypeTemplateParmDecl *Param
872 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
874 D.getIdentifierLoc(),
875 Depth, Position, ParamName, T,
876 IsParameterPack, TInfo);
877 Param->setAccess(AS_public);
880 Param->setInvalidDecl();
883 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
886 // Add the template parameter into the current scope.
888 IdResolver.AddDecl(Param);
891 // C++0x [temp.param]p9:
892 // A default template-argument may be specified for any kind of
893 // template-parameter that is not a template parameter pack.
894 if (Default && IsParameterPack) {
895 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
899 // Check the well-formedness of the default template argument, if provided.
901 // Check for unexpanded parameter packs.
902 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
905 TemplateArgument Converted;
906 ExprResult DefaultRes =
907 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
908 if (DefaultRes.isInvalid()) {
909 Param->setInvalidDecl();
912 Default = DefaultRes.get();
914 Param->setDefaultArgument(Default);
920 /// ActOnTemplateTemplateParameter - Called when a C++ template template
921 /// parameter (e.g. T in template <template \<typename> class T> class array)
922 /// has been parsed. S is the current scope.
923 Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
924 SourceLocation TmpLoc,
925 TemplateParameterList *Params,
926 SourceLocation EllipsisLoc,
927 IdentifierInfo *Name,
928 SourceLocation NameLoc,
931 SourceLocation EqualLoc,
932 ParsedTemplateArgument Default) {
933 assert(S->isTemplateParamScope() &&
934 "Template template parameter not in template parameter scope!");
936 // Construct the parameter object.
937 bool IsParameterPack = EllipsisLoc.isValid();
938 TemplateTemplateParmDecl *Param =
939 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
940 NameLoc.isInvalid()? TmpLoc : NameLoc,
941 Depth, Position, IsParameterPack,
943 Param->setAccess(AS_public);
945 // If the template template parameter has a name, then link the identifier
946 // into the scope and lookup mechanisms.
948 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
951 IdResolver.AddDecl(Param);
954 if (Params->size() == 0) {
955 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
956 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
957 Param->setInvalidDecl();
960 // C++0x [temp.param]p9:
961 // A default template-argument may be specified for any kind of
962 // template-parameter that is not a template parameter pack.
963 if (IsParameterPack && !Default.isInvalid()) {
964 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
965 Default = ParsedTemplateArgument();
968 if (!Default.isInvalid()) {
969 // Check only that we have a template template argument. We don't want to
970 // try to check well-formedness now, because our template template parameter
971 // might have dependent types in its template parameters, which we wouldn't
972 // be able to match now.
974 // If none of the template template parameter's template arguments mention
975 // other template parameters, we could actually perform more checking here.
976 // However, it isn't worth doing.
977 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
978 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
979 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
980 << DefaultArg.getSourceRange();
984 // Check for unexpanded parameter packs.
985 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
986 DefaultArg.getArgument().getAsTemplate(),
987 UPPC_DefaultArgument))
990 Param->setDefaultArgument(Context, DefaultArg);
996 /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
997 /// constrained by RequiresClause, that contains the template parameters in
999 TemplateParameterList *
1000 Sema::ActOnTemplateParameterList(unsigned Depth,
1001 SourceLocation ExportLoc,
1002 SourceLocation TemplateLoc,
1003 SourceLocation LAngleLoc,
1004 ArrayRef<Decl *> Params,
1005 SourceLocation RAngleLoc,
1006 Expr *RequiresClause) {
1007 if (ExportLoc.isValid())
1008 Diag(ExportLoc, diag::warn_template_export_unsupported);
1010 return TemplateParameterList::Create(
1011 Context, TemplateLoc, LAngleLoc,
1012 llvm::makeArrayRef((NamedDecl *const *)Params.data(), Params.size()),
1013 RAngleLoc, RequiresClause);
1016 static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
1018 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
1022 Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
1023 SourceLocation KWLoc, CXXScopeSpec &SS,
1024 IdentifierInfo *Name, SourceLocation NameLoc,
1025 AttributeList *Attr,
1026 TemplateParameterList *TemplateParams,
1027 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1028 SourceLocation FriendLoc,
1029 unsigned NumOuterTemplateParamLists,
1030 TemplateParameterList** OuterTemplateParamLists,
1031 SkipBodyInfo *SkipBody) {
1032 assert(TemplateParams && TemplateParams->size() > 0 &&
1033 "No template parameters");
1034 assert(TUK != TUK_Reference && "Can only declare or define class templates");
1035 bool Invalid = false;
1037 // Check that we can declare a template here.
1038 if (CheckTemplateDeclScope(S, TemplateParams))
1041 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1042 assert(Kind != TTK_Enum && "can't build template of enumerated type");
1044 // There is no such thing as an unnamed class template.
1046 Diag(KWLoc, diag::err_template_unnamed_class);
1050 // Find any previous declaration with this name. For a friend with no
1051 // scope explicitly specified, we only look for tag declarations (per
1052 // C++11 [basic.lookup.elab]p2).
1053 DeclContext *SemanticContext;
1054 LookupResult Previous(*this, Name, NameLoc,
1055 (SS.isEmpty() && TUK == TUK_Friend)
1056 ? LookupTagName : LookupOrdinaryName,
1058 if (SS.isNotEmpty() && !SS.isInvalid()) {
1059 SemanticContext = computeDeclContext(SS, true);
1060 if (!SemanticContext) {
1061 // FIXME: Horrible, horrible hack! We can't currently represent this
1062 // in the AST, and historically we have just ignored such friend
1063 // class templates, so don't complain here.
1064 Diag(NameLoc, TUK == TUK_Friend
1065 ? diag::warn_template_qualified_friend_ignored
1066 : diag::err_template_qualified_declarator_no_match)
1067 << SS.getScopeRep() << SS.getRange();
1068 return TUK != TUK_Friend;
1071 if (RequireCompleteDeclContext(SS, SemanticContext))
1074 // If we're adding a template to a dependent context, we may need to
1075 // rebuilding some of the types used within the template parameter list,
1076 // now that we know what the current instantiation is.
1077 if (SemanticContext->isDependentContext()) {
1078 ContextRAII SavedContext(*this, SemanticContext);
1079 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1081 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
1082 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
1084 LookupQualifiedName(Previous, SemanticContext);
1086 SemanticContext = CurContext;
1088 // C++14 [class.mem]p14:
1089 // If T is the name of a class, then each of the following shall have a
1090 // name different from T:
1091 // -- every member template of class T
1092 if (TUK != TUK_Friend &&
1093 DiagnoseClassNameShadow(SemanticContext,
1094 DeclarationNameInfo(Name, NameLoc)))
1097 LookupName(Previous, S);
1100 if (Previous.isAmbiguous())
1103 NamedDecl *PrevDecl = nullptr;
1104 if (Previous.begin() != Previous.end())
1105 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1107 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1108 // Maybe we will complain about the shadowed template parameter.
1109 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1110 // Just pretend that we didn't see the previous declaration.
1114 // If there is a previous declaration with the same name, check
1115 // whether this is a valid redeclaration.
1116 ClassTemplateDecl *PrevClassTemplate
1117 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1119 // We may have found the injected-class-name of a class template,
1120 // class template partial specialization, or class template specialization.
1121 // In these cases, grab the template that is being defined or specialized.
1122 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
1123 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1124 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1126 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1127 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1129 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1130 ->getSpecializedTemplate();
1134 if (TUK == TUK_Friend) {
1135 // C++ [namespace.memdef]p3:
1136 // [...] When looking for a prior declaration of a class or a function
1137 // declared as a friend, and when the name of the friend class or
1138 // function is neither a qualified name nor a template-id, scopes outside
1139 // the innermost enclosing namespace scope are not considered.
1141 DeclContext *OutermostContext = CurContext;
1142 while (!OutermostContext->isFileContext())
1143 OutermostContext = OutermostContext->getLookupParent();
1146 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1147 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1148 SemanticContext = PrevDecl->getDeclContext();
1150 // Declarations in outer scopes don't matter. However, the outermost
1151 // context we computed is the semantic context for our new
1153 PrevDecl = PrevClassTemplate = nullptr;
1154 SemanticContext = OutermostContext;
1156 // Check that the chosen semantic context doesn't already contain a
1157 // declaration of this name as a non-tag type.
1158 Previous.clear(LookupOrdinaryName);
1159 DeclContext *LookupContext = SemanticContext;
1160 while (LookupContext->isTransparentContext())
1161 LookupContext = LookupContext->getLookupParent();
1162 LookupQualifiedName(Previous, LookupContext);
1164 if (Previous.isAmbiguous())
1167 if (Previous.begin() != Previous.end())
1168 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1171 } else if (PrevDecl &&
1172 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1174 PrevDecl = PrevClassTemplate = nullptr;
1176 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1177 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1179 !(PrevClassTemplate &&
1180 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1181 SemanticContext->getRedeclContext()))) {
1182 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1183 Diag(Shadow->getTargetDecl()->getLocation(),
1184 diag::note_using_decl_target);
1185 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1186 // Recover by ignoring the old declaration.
1187 PrevDecl = PrevClassTemplate = nullptr;
1191 // TODO Memory management; associated constraints are not always stored.
1192 Expr *const CurAC = formAssociatedConstraints(TemplateParams, nullptr);
1194 if (PrevClassTemplate) {
1195 // Ensure that the template parameter lists are compatible. Skip this check
1196 // for a friend in a dependent context: the template parameter list itself
1197 // could be dependent.
1198 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1199 !TemplateParameterListsAreEqual(TemplateParams,
1200 PrevClassTemplate->getTemplateParameters(),
1205 // Check for matching associated constraints on redeclarations.
1206 const Expr *const PrevAC = PrevClassTemplate->getAssociatedConstraints();
1207 const bool RedeclACMismatch = [&] {
1208 if (!(CurAC || PrevAC))
1209 return false; // Nothing to check; no mismatch.
1210 if (CurAC && PrevAC) {
1211 llvm::FoldingSetNodeID CurACInfo, PrevACInfo;
1212 CurAC->Profile(CurACInfo, Context, /*Canonical=*/true);
1213 PrevAC->Profile(PrevACInfo, Context, /*Canonical=*/true);
1214 if (CurACInfo == PrevACInfo)
1215 return false; // All good; no mismatch.
1220 if (RedeclACMismatch) {
1221 Diag(CurAC ? CurAC->getLocStart() : NameLoc,
1222 diag::err_template_different_associated_constraints);
1223 Diag(PrevAC ? PrevAC->getLocStart() : PrevClassTemplate->getLocation(),
1224 diag::note_template_prev_declaration) << /*declaration*/0;
1228 // C++ [temp.class]p4:
1229 // In a redeclaration, partial specialization, explicit
1230 // specialization or explicit instantiation of a class template,
1231 // the class-key shall agree in kind with the original class
1232 // template declaration (7.1.5.3).
1233 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
1234 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
1235 TUK == TUK_Definition, KWLoc, Name)) {
1236 Diag(KWLoc, diag::err_use_with_wrong_tag)
1238 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
1239 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
1240 Kind = PrevRecordDecl->getTagKind();
1243 // Check for redefinition of this class template.
1244 if (TUK == TUK_Definition) {
1245 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
1246 // If we have a prior definition that is not visible, treat this as
1247 // simply making that previous definition visible.
1248 NamedDecl *Hidden = nullptr;
1249 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
1250 SkipBody->ShouldSkip = true;
1251 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1252 assert(Tmpl && "original definition of a class template is not a "
1254 makeMergedDefinitionVisible(Hidden, KWLoc);
1255 makeMergedDefinitionVisible(Tmpl, KWLoc);
1259 Diag(NameLoc, diag::err_redefinition) << Name;
1260 Diag(Def->getLocation(), diag::note_previous_definition);
1261 // FIXME: Would it make sense to try to "forget" the previous
1262 // definition, as part of error recovery?
1266 } else if (PrevDecl) {
1268 // A class template shall not have the same name as any other
1269 // template, class, function, object, enumeration, enumerator,
1270 // namespace, or type in the same scope (3.3), except as specified
1272 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1273 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1277 // Check the template parameter list of this declaration, possibly
1278 // merging in the template parameter list from the previous class
1279 // template declaration. Skip this check for a friend in a dependent
1280 // context, because the template parameter list might be dependent.
1281 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1282 CheckTemplateParameterList(
1284 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1286 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1287 SemanticContext->isDependentContext())
1288 ? TPC_ClassTemplateMember
1289 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1290 : TPC_ClassTemplate))
1294 // If the name of the template was qualified, we must be defining the
1295 // template out-of-line.
1296 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1297 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
1298 : diag::err_member_decl_does_not_match)
1299 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
1304 // If this is a templated friend in a dependent context we should not put it
1305 // on the redecl chain. In some cases, the templated friend can be the most
1306 // recent declaration tricking the template instantiator to make substitutions
1308 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
1309 bool ShouldAddRedecl
1310 = !(TUK == TUK_Friend && CurContext->isDependentContext());
1312 CXXRecordDecl *NewClass =
1313 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
1314 PrevClassTemplate && ShouldAddRedecl ?
1315 PrevClassTemplate->getTemplatedDecl() : nullptr,
1316 /*DelayTypeCreation=*/true);
1317 SetNestedNameSpecifier(NewClass, SS);
1318 if (NumOuterTemplateParamLists > 0)
1319 NewClass->setTemplateParameterListsInfo(
1320 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1321 NumOuterTemplateParamLists));
1323 // Add alignment attributes if necessary; these attributes are checked when
1324 // the ASTContext lays out the structure.
1325 if (TUK == TUK_Definition) {
1326 AddAlignmentAttributesForRecord(NewClass);
1327 AddMsStructLayoutForRecord(NewClass);
1330 // Attach the associated constraints when the declaration will not be part of
1332 Expr *const ACtoAttach =
1333 PrevClassTemplate && ShouldAddRedecl ? nullptr : CurAC;
1335 ClassTemplateDecl *NewTemplate
1336 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1337 DeclarationName(Name), TemplateParams,
1338 NewClass, ACtoAttach);
1340 if (ShouldAddRedecl)
1341 NewTemplate->setPreviousDecl(PrevClassTemplate);
1343 NewClass->setDescribedClassTemplate(NewTemplate);
1345 if (ModulePrivateLoc.isValid())
1346 NewTemplate->setModulePrivate();
1348 // Build the type for the class template declaration now.
1349 QualType T = NewTemplate->getInjectedClassNameSpecialization();
1350 T = Context.getInjectedClassNameType(NewClass, T);
1351 assert(T->isDependentType() && "Class template type is not dependent?");
1354 // If we are providing an explicit specialization of a member that is a
1355 // class template, make a note of that.
1356 if (PrevClassTemplate &&
1357 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1358 PrevClassTemplate->setMemberSpecialization();
1360 // Set the access specifier.
1361 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
1362 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
1364 // Set the lexical context of these templates
1365 NewClass->setLexicalDeclContext(CurContext);
1366 NewTemplate->setLexicalDeclContext(CurContext);
1368 if (TUK == TUK_Definition)
1369 NewClass->startDefinition();
1372 ProcessDeclAttributeList(S, NewClass, Attr);
1374 if (PrevClassTemplate)
1375 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1377 AddPushedVisibilityAttribute(NewClass);
1379 if (TUK != TUK_Friend) {
1380 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1382 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1383 Outer = Outer->getParent();
1384 PushOnScopeChains(NewTemplate, Outer);
1386 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
1387 NewTemplate->setAccess(PrevClassTemplate->getAccess());
1388 NewClass->setAccess(PrevClassTemplate->getAccess());
1391 NewTemplate->setObjectOfFriendDecl();
1393 // Friend templates are visible in fairly strange ways.
1394 if (!CurContext->isDependentContext()) {
1395 DeclContext *DC = SemanticContext->getRedeclContext();
1396 DC->makeDeclVisibleInContext(NewTemplate);
1397 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1398 PushOnScopeChains(NewTemplate, EnclosingScope,
1399 /* AddToContext = */ false);
1402 FriendDecl *Friend = FriendDecl::Create(
1403 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
1404 Friend->setAccess(AS_public);
1405 CurContext->addDecl(Friend);
1409 NewTemplate->setInvalidDecl();
1410 NewClass->setInvalidDecl();
1413 ActOnDocumentableDecl(NewTemplate);
1419 /// Transform to convert portions of a constructor declaration into the
1420 /// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
1421 struct ConvertConstructorToDeductionGuideTransform {
1422 ConvertConstructorToDeductionGuideTransform(Sema &S,
1423 ClassTemplateDecl *Template)
1424 : SemaRef(S), Template(Template) {}
1427 ClassTemplateDecl *Template;
1429 DeclContext *DC = Template->getDeclContext();
1430 CXXRecordDecl *Primary = Template->getTemplatedDecl();
1431 DeclarationName DeductionGuideName =
1432 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template);
1434 QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
1436 // Index adjustment to apply to convert depth-1 template parameters into
1437 // depth-0 template parameters.
1438 unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
1440 /// Transform a constructor declaration into a deduction guide.
1441 NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
1442 CXXConstructorDecl *CD) {
1443 SmallVector<TemplateArgument, 16> SubstArgs;
1445 LocalInstantiationScope Scope(SemaRef);
1447 // C++ [over.match.class.deduct]p1:
1448 // -- For each constructor of the class template designated by the
1449 // template-name, a function template with the following properties:
1451 // -- The template parameters are the template parameters of the class
1452 // template followed by the template parameters (including default
1453 // template arguments) of the constructor, if any.
1454 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
1456 TemplateParameterList *InnerParams = FTD->getTemplateParameters();
1457 SmallVector<NamedDecl *, 16> AllParams;
1458 AllParams.reserve(TemplateParams->size() + InnerParams->size());
1459 AllParams.insert(AllParams.begin(),
1460 TemplateParams->begin(), TemplateParams->end());
1461 SubstArgs.reserve(InnerParams->size());
1463 // Later template parameters could refer to earlier ones, so build up
1464 // a list of substituted template arguments as we go.
1465 for (NamedDecl *Param : *InnerParams) {
1466 MultiLevelTemplateArgumentList Args;
1467 Args.addOuterTemplateArguments(SubstArgs);
1468 Args.addOuterRetainedLevel();
1469 NamedDecl *NewParam = transformTemplateParameter(Param, Args);
1472 AllParams.push_back(NewParam);
1473 SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
1474 SemaRef.Context.getInjectedTemplateArg(NewParam)));
1476 TemplateParams = TemplateParameterList::Create(
1477 SemaRef.Context, InnerParams->getTemplateLoc(),
1478 InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
1479 /*FIXME: RequiresClause*/ nullptr);
1482 // If we built a new template-parameter-list, track that we need to
1483 // substitute references to the old parameters into references to the
1485 MultiLevelTemplateArgumentList Args;
1487 Args.addOuterTemplateArguments(SubstArgs);
1488 Args.addOuterRetainedLevel();
1491 FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc()
1492 .getAsAdjusted<FunctionProtoTypeLoc>();
1493 assert(FPTL && "no prototype for constructor declaration");
1495 // Transform the type of the function, adjusting the return type and
1496 // replacing references to the old parameters with references to the
1499 SmallVector<ParmVarDecl*, 8> Params;
1500 QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args);
1501 if (NewType.isNull())
1503 TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
1505 return buildDeductionGuide(TemplateParams, CD->isExplicit(), NewTInfo,
1506 CD->getLocStart(), CD->getLocation(),
1510 /// Build a deduction guide with the specified parameter types.
1511 NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
1512 SourceLocation Loc = Template->getLocation();
1514 // Build the requested type.
1515 FunctionProtoType::ExtProtoInfo EPI;
1516 EPI.HasTrailingReturn = true;
1517 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
1518 DeductionGuideName, EPI);
1519 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
1521 FunctionProtoTypeLoc FPTL =
1522 TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
1524 // Build the parameters, needed during deduction / substitution.
1525 SmallVector<ParmVarDecl*, 4> Params;
1526 for (auto T : ParamTypes) {
1527 ParmVarDecl *NewParam = ParmVarDecl::Create(
1528 SemaRef.Context, DC, Loc, Loc, nullptr, T,
1529 SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
1530 NewParam->setScopeInfo(0, Params.size());
1531 FPTL.setParam(Params.size(), NewParam);
1532 Params.push_back(NewParam);
1535 return buildDeductionGuide(Template->getTemplateParameters(), false, TSI,
1540 /// Transform a constructor template parameter into a deduction guide template
1541 /// parameter, rebuilding any internal references to earlier parameters and
1542 /// renumbering as we go.
1543 NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
1544 MultiLevelTemplateArgumentList &Args) {
1545 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
1546 // TemplateTypeParmDecl's index cannot be changed after creation, so
1547 // substitute it directly.
1548 auto *NewTTP = TemplateTypeParmDecl::Create(
1549 SemaRef.Context, DC, TTP->getLocStart(), TTP->getLocation(),
1550 /*Depth*/0, Depth1IndexAdjustment + TTP->getIndex(),
1551 TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
1552 TTP->isParameterPack());
1553 if (TTP->hasDefaultArgument()) {
1554 TypeSourceInfo *InstantiatedDefaultArg =
1555 SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
1556 TTP->getDefaultArgumentLoc(), TTP->getDeclName());
1557 if (InstantiatedDefaultArg)
1558 NewTTP->setDefaultArgument(InstantiatedDefaultArg);
1560 SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam,
1565 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
1566 return transformTemplateParameterImpl(TTP, Args);
1568 return transformTemplateParameterImpl(
1569 cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
1571 template<typename TemplateParmDecl>
1573 transformTemplateParameterImpl(TemplateParmDecl *OldParam,
1574 MultiLevelTemplateArgumentList &Args) {
1575 // Ask the template instantiator to do the heavy lifting for us, then adjust
1576 // the index of the parameter once it's done.
1578 cast_or_null<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
1579 assert(NewParam->getDepth() == 0 && "unexpected template param depth");
1580 NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
1584 QualType transformFunctionProtoType(TypeLocBuilder &TLB,
1585 FunctionProtoTypeLoc TL,
1586 SmallVectorImpl<ParmVarDecl*> &Params,
1587 MultiLevelTemplateArgumentList &Args) {
1588 SmallVector<QualType, 4> ParamTypes;
1589 const FunctionProtoType *T = TL.getTypePtr();
1591 // -- The types of the function parameters are those of the constructor.
1592 for (auto *OldParam : TL.getParams()) {
1593 ParmVarDecl *NewParam = transformFunctionTypeParam(OldParam, Args);
1596 ParamTypes.push_back(NewParam->getType());
1597 Params.push_back(NewParam);
1600 // -- The return type is the class template specialization designated by
1601 // the template-name and template arguments corresponding to the
1602 // template parameters obtained from the class template.
1604 // We use the injected-class-name type of the primary template instead.
1605 // This has the convenient property that it is different from any type that
1606 // the user can write in a deduction-guide (because they cannot enter the
1607 // context of the template), so implicit deduction guides can never collide
1608 // with explicit ones.
1609 QualType ReturnType = DeducedType;
1610 TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
1612 // Resolving a wording defect, we also inherit the variadicness of the
1614 FunctionProtoType::ExtProtoInfo EPI;
1615 EPI.Variadic = T->isVariadic();
1616 EPI.HasTrailingReturn = true;
1618 QualType Result = SemaRef.BuildFunctionType(
1619 ReturnType, ParamTypes, TL.getLocStart(), DeductionGuideName, EPI);
1620 if (Result.isNull())
1623 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
1624 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
1625 NewTL.setLParenLoc(TL.getLParenLoc());
1626 NewTL.setRParenLoc(TL.getRParenLoc());
1627 NewTL.setExceptionSpecRange(SourceRange());
1628 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
1629 for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
1630 NewTL.setParam(I, Params[I]);
1636 transformFunctionTypeParam(ParmVarDecl *OldParam,
1637 MultiLevelTemplateArgumentList &Args) {
1638 TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
1639 TypeSourceInfo *NewDI;
1640 if (!Args.getNumLevels())
1642 else if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
1643 // Expand out the one and only element in each inner pack.
1644 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
1646 SemaRef.SubstType(PackTL.getPatternLoc(), Args,
1647 OldParam->getLocation(), OldParam->getDeclName());
1648 if (!NewDI) return nullptr;
1650 SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
1651 PackTL.getTypePtr()->getNumExpansions());
1653 NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
1654 OldParam->getDeclName());
1658 // Canonicalize the type. This (for instance) replaces references to
1659 // typedef members of the current instantiations with the definitions of
1660 // those typedefs, avoiding triggering instantiation of the deduced type
1661 // during deduction.
1662 // FIXME: It would be preferable to retain type sugar and source
1663 // information here (and handle this in substitution instead).
1664 NewDI = SemaRef.Context.getTrivialTypeSourceInfo(
1665 SemaRef.Context.getCanonicalType(NewDI->getType()),
1666 OldParam->getLocation());
1668 // Resolving a wording defect, we also inherit default arguments from the
1670 ExprResult NewDefArg;
1671 if (OldParam->hasDefaultArg()) {
1672 NewDefArg = Args.getNumLevels()
1673 ? SemaRef.SubstExpr(OldParam->getDefaultArg(), Args)
1674 : OldParam->getDefaultArg();
1675 if (NewDefArg.isInvalid())
1679 ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
1680 OldParam->getInnerLocStart(),
1681 OldParam->getLocation(),
1682 OldParam->getIdentifier(),
1685 OldParam->getStorageClass(),
1687 NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
1688 OldParam->getFunctionScopeIndex());
1692 NamedDecl *buildDeductionGuide(TemplateParameterList *TemplateParams,
1693 bool Explicit, TypeSourceInfo *TInfo,
1694 SourceLocation LocStart, SourceLocation Loc,
1695 SourceLocation LocEnd) {
1696 DeclarationNameInfo Name(DeductionGuideName, Loc);
1697 ArrayRef<ParmVarDecl *> Params =
1698 TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
1700 // Build the implicit deduction guide template.
1702 CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, Explicit,
1703 Name, TInfo->getType(), TInfo, LocEnd);
1704 Guide->setImplicit();
1705 Guide->setParams(Params);
1707 for (auto *Param : Params)
1708 Param->setDeclContext(Guide);
1710 auto *GuideTemplate = FunctionTemplateDecl::Create(
1711 SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
1712 GuideTemplate->setImplicit();
1713 Guide->setDescribedFunctionTemplate(GuideTemplate);
1715 if (isa<CXXRecordDecl>(DC)) {
1716 Guide->setAccess(AS_public);
1717 GuideTemplate->setAccess(AS_public);
1720 DC->addDecl(GuideTemplate);
1721 return GuideTemplate;
1726 void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
1727 SourceLocation Loc) {
1728 DeclContext *DC = Template->getDeclContext();
1729 if (DC->isDependentContext())
1732 ConvertConstructorToDeductionGuideTransform Transform(
1733 *this, cast<ClassTemplateDecl>(Template));
1734 if (!isCompleteType(Loc, Transform.DeducedType))
1737 // Check whether we've already declared deduction guides for this template.
1738 // FIXME: Consider storing a flag on the template to indicate this.
1739 auto Existing = DC->lookup(Transform.DeductionGuideName);
1740 for (auto *D : Existing)
1741 if (D->isImplicit())
1744 // In case we were expanding a pack when we attempted to declare deduction
1745 // guides, turn off pack expansion for everything we're about to do.
1746 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1747 // Create a template instantiation record to track the "instantiation" of
1748 // constructors into deduction guides.
1749 // FIXME: Add a kind for this to give more meaningful diagnostics. But can
1750 // this substitution process actually fail?
1751 InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
1753 // Convert declared constructors into deduction guide templates.
1754 // FIXME: Skip constructors for which deduction must necessarily fail (those
1755 // for which some class template parameter without a default argument never
1756 // appears in a deduced context).
1757 bool AddedAny = false;
1758 bool AddedCopyOrMove = false;
1759 for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
1760 D = D->getUnderlyingDecl();
1761 if (D->isInvalidDecl() || D->isImplicit())
1763 D = cast<NamedDecl>(D->getCanonicalDecl());
1765 auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
1767 dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
1768 // Class-scope explicit specializations (MS extension) do not result in
1769 // deduction guides.
1770 if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
1773 Transform.transformConstructor(FTD, CD);
1776 AddedCopyOrMove |= CD->isCopyOrMoveConstructor();
1779 // Synthesize an X() -> X<...> guide if there were no declared constructors.
1780 // FIXME: The standard doesn't say (how) to do this.
1782 Transform.buildSimpleDeductionGuide(None);
1784 // Synthesize an X(X<...>) -> X<...> guide if there was no declared constructor
1785 // resembling a copy or move constructor.
1786 // FIXME: The standard doesn't say (how) to do this.
1787 if (!AddedCopyOrMove)
1788 Transform.buildSimpleDeductionGuide(Transform.DeducedType);
1791 /// \brief Diagnose the presence of a default template argument on a
1792 /// template parameter, which is ill-formed in certain contexts.
1794 /// \returns true if the default template argument should be dropped.
1795 static bool DiagnoseDefaultTemplateArgument(Sema &S,
1796 Sema::TemplateParamListContext TPC,
1797 SourceLocation ParamLoc,
1798 SourceRange DefArgRange) {
1800 case Sema::TPC_ClassTemplate:
1801 case Sema::TPC_VarTemplate:
1802 case Sema::TPC_TypeAliasTemplate:
1805 case Sema::TPC_FunctionTemplate:
1806 case Sema::TPC_FriendFunctionTemplateDefinition:
1807 // C++ [temp.param]p9:
1808 // A default template-argument shall not be specified in a
1809 // function template declaration or a function template
1811 // If a friend function template declaration specifies a default
1812 // template-argument, that declaration shall be a definition and shall be
1813 // the only declaration of the function template in the translation unit.
1814 // (C++98/03 doesn't have this wording; see DR226).
1815 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
1816 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1817 : diag::ext_template_parameter_default_in_function_template)
1821 case Sema::TPC_ClassTemplateMember:
1822 // C++0x [temp.param]p9:
1823 // A default template-argument shall not be specified in the
1824 // template-parameter-lists of the definition of a member of a
1825 // class template that appears outside of the member's class.
1826 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1830 case Sema::TPC_FriendClassTemplate:
1831 case Sema::TPC_FriendFunctionTemplate:
1832 // C++ [temp.param]p9:
1833 // A default template-argument shall not be specified in a
1834 // friend template declaration.
1835 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1839 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1840 // for friend function templates if there is only a single
1841 // declaration (and it is a definition). Strange!
1844 llvm_unreachable("Invalid TemplateParamListContext!");
1847 /// \brief Check for unexpanded parameter packs within the template parameters
1848 /// of a template template parameter, recursively.
1849 static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1850 TemplateTemplateParmDecl *TTP) {
1851 // A template template parameter which is a parameter pack is also a pack
1853 if (TTP->isParameterPack())
1856 TemplateParameterList *Params = TTP->getTemplateParameters();
1857 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1858 NamedDecl *P = Params->getParam(I);
1859 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
1860 if (!NTTP->isParameterPack() &&
1861 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
1862 NTTP->getTypeSourceInfo(),
1863 Sema::UPPC_NonTypeTemplateParameterType))
1869 if (TemplateTemplateParmDecl *InnerTTP
1870 = dyn_cast<TemplateTemplateParmDecl>(P))
1871 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1878 /// \brief Checks the validity of a template parameter list, possibly
1879 /// considering the template parameter list from a previous
1882 /// If an "old" template parameter list is provided, it must be
1883 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
1884 /// template parameter list.
1886 /// \param NewParams Template parameter list for a new template
1887 /// declaration. This template parameter list will be updated with any
1888 /// default arguments that are carried through from the previous
1889 /// template parameter list.
1891 /// \param OldParams If provided, template parameter list from a
1892 /// previous declaration of the same template. Default template
1893 /// arguments will be merged from the old template parameter list to
1894 /// the new template parameter list.
1896 /// \param TPC Describes the context in which we are checking the given
1897 /// template parameter list.
1899 /// \returns true if an error occurred, false otherwise.
1900 bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
1901 TemplateParameterList *OldParams,
1902 TemplateParamListContext TPC) {
1903 bool Invalid = false;
1905 // C++ [temp.param]p10:
1906 // The set of default template-arguments available for use with a
1907 // template declaration or definition is obtained by merging the
1908 // default arguments from the definition (if in scope) and all
1909 // declarations in scope in the same way default function
1910 // arguments are (8.3.6).
1911 bool SawDefaultArgument = false;
1912 SourceLocation PreviousDefaultArgLoc;
1914 // Dummy initialization to avoid warnings.
1915 TemplateParameterList::iterator OldParam = NewParams->end();
1917 OldParam = OldParams->begin();
1919 bool RemoveDefaultArguments = false;
1920 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1921 NewParamEnd = NewParams->end();
1922 NewParam != NewParamEnd; ++NewParam) {
1923 // Variables used to diagnose redundant default arguments
1924 bool RedundantDefaultArg = false;
1925 SourceLocation OldDefaultLoc;
1926 SourceLocation NewDefaultLoc;
1928 // Variable used to diagnose missing default arguments
1929 bool MissingDefaultArg = false;
1931 // Variable used to diagnose non-final parameter packs
1932 bool SawParameterPack = false;
1934 if (TemplateTypeParmDecl *NewTypeParm
1935 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
1936 // Check the presence of a default argument here.
1937 if (NewTypeParm->hasDefaultArgument() &&
1938 DiagnoseDefaultTemplateArgument(*this, TPC,
1939 NewTypeParm->getLocation(),
1940 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1942 NewTypeParm->removeDefaultArgument();
1944 // Merge default arguments for template type parameters.
1945 TemplateTypeParmDecl *OldTypeParm
1946 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
1947 if (NewTypeParm->isParameterPack()) {
1948 assert(!NewTypeParm->hasDefaultArgument() &&
1949 "Parameter packs can't have a default argument!");
1950 SawParameterPack = true;
1951 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
1952 NewTypeParm->hasDefaultArgument()) {
1953 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1954 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1955 SawDefaultArgument = true;
1956 RedundantDefaultArg = true;
1957 PreviousDefaultArgLoc = NewDefaultLoc;
1958 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1959 // Merge the default argument from the old declaration to the
1961 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
1962 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1963 } else if (NewTypeParm->hasDefaultArgument()) {
1964 SawDefaultArgument = true;
1965 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1966 } else if (SawDefaultArgument)
1967 MissingDefaultArg = true;
1968 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
1969 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
1970 // Check for unexpanded parameter packs.
1971 if (!NewNonTypeParm->isParameterPack() &&
1972 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
1973 NewNonTypeParm->getTypeSourceInfo(),
1974 UPPC_NonTypeTemplateParameterType)) {
1979 // Check the presence of a default argument here.
1980 if (NewNonTypeParm->hasDefaultArgument() &&
1981 DiagnoseDefaultTemplateArgument(*this, TPC,
1982 NewNonTypeParm->getLocation(),
1983 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1984 NewNonTypeParm->removeDefaultArgument();
1987 // Merge default arguments for non-type template parameters
1988 NonTypeTemplateParmDecl *OldNonTypeParm
1989 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
1990 if (NewNonTypeParm->isParameterPack()) {
1991 assert(!NewNonTypeParm->hasDefaultArgument() &&
1992 "Parameter packs can't have a default argument!");
1993 if (!NewNonTypeParm->isPackExpansion())
1994 SawParameterPack = true;
1995 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
1996 NewNonTypeParm->hasDefaultArgument()) {
1997 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1998 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1999 SawDefaultArgument = true;
2000 RedundantDefaultArg = true;
2001 PreviousDefaultArgLoc = NewDefaultLoc;
2002 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2003 // Merge the default argument from the old declaration to the
2005 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2006 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2007 } else if (NewNonTypeParm->hasDefaultArgument()) {
2008 SawDefaultArgument = true;
2009 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2010 } else if (SawDefaultArgument)
2011 MissingDefaultArg = true;
2013 TemplateTemplateParmDecl *NewTemplateParm
2014 = cast<TemplateTemplateParmDecl>(*NewParam);
2016 // Check for unexpanded parameter packs, recursively.
2017 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2022 // Check the presence of a default argument here.
2023 if (NewTemplateParm->hasDefaultArgument() &&
2024 DiagnoseDefaultTemplateArgument(*this, TPC,
2025 NewTemplateParm->getLocation(),
2026 NewTemplateParm->getDefaultArgument().getSourceRange()))
2027 NewTemplateParm->removeDefaultArgument();
2029 // Merge default arguments for template template parameters
2030 TemplateTemplateParmDecl *OldTemplateParm
2031 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2032 if (NewTemplateParm->isParameterPack()) {
2033 assert(!NewTemplateParm->hasDefaultArgument() &&
2034 "Parameter packs can't have a default argument!");
2035 if (!NewTemplateParm->isPackExpansion())
2036 SawParameterPack = true;
2037 } else if (OldTemplateParm &&
2038 hasVisibleDefaultArgument(OldTemplateParm) &&
2039 NewTemplateParm->hasDefaultArgument()) {
2040 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2041 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2042 SawDefaultArgument = true;
2043 RedundantDefaultArg = true;
2044 PreviousDefaultArgLoc = NewDefaultLoc;
2045 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2046 // Merge the default argument from the old declaration to the
2048 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2049 PreviousDefaultArgLoc
2050 = OldTemplateParm->getDefaultArgument().getLocation();
2051 } else if (NewTemplateParm->hasDefaultArgument()) {
2052 SawDefaultArgument = true;
2053 PreviousDefaultArgLoc
2054 = NewTemplateParm->getDefaultArgument().getLocation();
2055 } else if (SawDefaultArgument)
2056 MissingDefaultArg = true;
2059 // C++11 [temp.param]p11:
2060 // If a template parameter of a primary class template or alias template
2061 // is a template parameter pack, it shall be the last template parameter.
2062 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2063 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2064 TPC == TPC_TypeAliasTemplate)) {
2065 Diag((*NewParam)->getLocation(),
2066 diag::err_template_param_pack_must_be_last_template_parameter);
2070 if (RedundantDefaultArg) {
2071 // C++ [temp.param]p12:
2072 // A template-parameter shall not be given default arguments
2073 // by two different declarations in the same scope.
2074 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2075 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2077 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
2078 // C++ [temp.param]p11:
2079 // If a template-parameter of a class template has a default
2080 // template-argument, each subsequent template-parameter shall either
2081 // have a default template-argument supplied or be a template parameter
2083 Diag((*NewParam)->getLocation(),
2084 diag::err_template_param_default_arg_missing);
2085 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2087 RemoveDefaultArguments = true;
2090 // If we have an old template parameter list that we're merging
2091 // in, move on to the next parameter.
2096 // We were missing some default arguments at the end of the list, so remove
2097 // all of the default arguments.
2098 if (RemoveDefaultArguments) {
2099 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2100 NewParamEnd = NewParams->end();
2101 NewParam != NewParamEnd; ++NewParam) {
2102 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2103 TTP->removeDefaultArgument();
2104 else if (NonTypeTemplateParmDecl *NTTP
2105 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2106 NTTP->removeDefaultArgument();
2108 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2117 /// A class which looks for a use of a certain level of template
2119 struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
2120 typedef RecursiveASTVisitor<DependencyChecker> super;
2124 // Whether we're looking for a use of a template parameter that makes the
2125 // overall construct type-dependent / a dependent type. This is strictly
2126 // best-effort for now; we may fail to match at all for a dependent type
2127 // in some cases if this is set.
2128 bool IgnoreNonTypeDependent;
2131 SourceLocation MatchLoc;
2133 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2134 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2137 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2138 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2139 NamedDecl *ND = Params->getParam(0);
2140 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2141 Depth = PD->getDepth();
2142 } else if (NonTypeTemplateParmDecl *PD =
2143 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2144 Depth = PD->getDepth();
2146 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2150 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2151 if (ParmDepth >= Depth) {
2159 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2160 // Prune out non-type-dependent expressions if requested. This can
2161 // sometimes result in us failing to find a template parameter reference
2162 // (if a value-dependent expression creates a dependent type), but this
2163 // mode is best-effort only.
2164 if (auto *E = dyn_cast_or_null<Expr>(S))
2165 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2167 return super::TraverseStmt(S, Q);
2170 bool TraverseTypeLoc(TypeLoc TL) {
2171 if (IgnoreNonTypeDependent && !TL.isNull() &&
2172 !TL.getType()->isDependentType())
2174 return super::TraverseTypeLoc(TL);
2177 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2178 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2181 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
2182 // For a best-effort search, keep looking until we find a location.
2183 return IgnoreNonTypeDependent || !Matches(T->getDepth());
2186 bool TraverseTemplateName(TemplateName N) {
2187 if (TemplateTemplateParmDecl *PD =
2188 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2189 if (Matches(PD->getDepth()))
2191 return super::TraverseTemplateName(N);
2194 bool VisitDeclRefExpr(DeclRefExpr *E) {
2195 if (NonTypeTemplateParmDecl *PD =
2196 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2197 if (Matches(PD->getDepth(), E->getExprLoc()))
2199 return super::VisitDeclRefExpr(E);
2202 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2203 return TraverseType(T->getReplacementType());
2207 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
2208 return TraverseTemplateArgument(T->getArgumentPack());
2211 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
2212 return TraverseType(T->getInjectedSpecializationType());
2215 } // end anonymous namespace
2217 /// Determines whether a given type depends on the given parameter
2220 DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
2221 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2222 Checker.TraverseType(T);
2223 return Checker.Match;
2226 // Find the source range corresponding to the named type in the given
2227 // nested-name-specifier, if any.
2228 static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2230 const CXXScopeSpec &SS) {
2231 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2232 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2233 if (const Type *CurType = NNS->getAsType()) {
2234 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2235 return NNSLoc.getTypeLoc().getSourceRange();
2239 NNSLoc = NNSLoc.getPrefix();
2242 return SourceRange();
2245 /// \brief Match the given template parameter lists to the given scope
2246 /// specifier, returning the template parameter list that applies to the
2249 /// \param DeclStartLoc the start of the declaration that has a scope
2250 /// specifier or a template parameter list.
2252 /// \param DeclLoc The location of the declaration itself.
2254 /// \param SS the scope specifier that will be matched to the given template
2255 /// parameter lists. This scope specifier precedes a qualified name that is
2258 /// \param TemplateId The template-id following the scope specifier, if there
2259 /// is one. Used to check for a missing 'template<>'.
2261 /// \param ParamLists the template parameter lists, from the outermost to the
2262 /// innermost template parameter lists.
2264 /// \param IsFriend Whether to apply the slightly different rules for
2265 /// matching template parameters to scope specifiers in friend
2268 /// \param IsMemberSpecialization will be set true if the scope specifier
2269 /// denotes a fully-specialized type, and therefore this is a declaration of
2270 /// a member specialization.
2272 /// \returns the template parameter list, if any, that corresponds to the
2273 /// name that is preceded by the scope specifier @p SS. This template
2274 /// parameter list may have template parameters (if we're declaring a
2275 /// template) or may have no template parameters (if we're declaring a
2276 /// template specialization), or may be NULL (if what we're declaring isn't
2277 /// itself a template).
2278 TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2279 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2280 TemplateIdAnnotation *TemplateId,
2281 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2282 bool &IsMemberSpecialization, bool &Invalid) {
2283 IsMemberSpecialization = false;
2286 // The sequence of nested types to which we will match up the template
2287 // parameter lists. We first build this list by starting with the type named
2288 // by the nested-name-specifier and walking out until we run out of types.
2289 SmallVector<QualType, 4> NestedTypes;
2291 if (SS.getScopeRep()) {
2292 if (CXXRecordDecl *Record
2293 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2294 T = Context.getTypeDeclType(Record);
2296 T = QualType(SS.getScopeRep()->getAsType(), 0);
2299 // If we found an explicit specialization that prevents us from needing
2300 // 'template<>' headers, this will be set to the location of that
2301 // explicit specialization.
2302 SourceLocation ExplicitSpecLoc;
2304 while (!T.isNull()) {
2305 NestedTypes.push_back(T);
2307 // Retrieve the parent of a record type.
2308 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2309 // If this type is an explicit specialization, we're done.
2310 if (ClassTemplateSpecializationDecl *Spec
2311 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2312 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
2313 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2314 ExplicitSpecLoc = Spec->getLocation();
2317 } else if (Record->getTemplateSpecializationKind()
2318 == TSK_ExplicitSpecialization) {
2319 ExplicitSpecLoc = Record->getLocation();
2323 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2324 T = Context.getTypeDeclType(Parent);
2330 if (const TemplateSpecializationType *TST
2331 = T->getAs<TemplateSpecializationType>()) {
2332 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2333 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2334 T = Context.getTypeDeclType(Parent);
2341 // Look one step prior in a dependent template specialization type.
2342 if (const DependentTemplateSpecializationType *DependentTST
2343 = T->getAs<DependentTemplateSpecializationType>()) {
2344 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2345 T = QualType(NNS->getAsType(), 0);
2351 // Look one step prior in a dependent name type.
2352 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2353 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2354 T = QualType(NNS->getAsType(), 0);
2360 // Retrieve the parent of an enumeration type.
2361 if (const EnumType *EnumT = T->getAs<EnumType>()) {
2362 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2364 EnumDecl *Enum = EnumT->getDecl();
2366 // Get to the parent type.
2367 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2368 T = Context.getTypeDeclType(Parent);
2376 // Reverse the nested types list, since we want to traverse from the outermost
2377 // to the innermost while checking template-parameter-lists.
2378 std::reverse(NestedTypes.begin(), NestedTypes.end());
2380 // C++0x [temp.expl.spec]p17:
2381 // A member or a member template may be nested within many
2382 // enclosing class templates. In an explicit specialization for
2383 // such a member, the member declaration shall be preceded by a
2384 // template<> for each enclosing class template that is
2385 // explicitly specialized.
2386 bool SawNonEmptyTemplateParameterList = false;
2388 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2389 if (SawNonEmptyTemplateParameterList) {
2390 Diag(DeclLoc, diag::err_specialize_member_of_template)
2391 << !Recovery << Range;
2393 IsMemberSpecialization = false;
2400 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2401 // Check that we can have an explicit specialization here.
2402 if (CheckExplicitSpecialization(Range, true))
2405 // We don't have a template header, but we should.
2406 SourceLocation ExpectedTemplateLoc;
2407 if (!ParamLists.empty())
2408 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2410 ExpectedTemplateLoc = DeclStartLoc;
2412 Diag(DeclLoc, diag::err_template_spec_needs_header)
2414 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2418 unsigned ParamIdx = 0;
2419 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2421 T = NestedTypes[TypeIdx];
2423 // Whether we expect a 'template<>' header.
2424 bool NeedEmptyTemplateHeader = false;
2426 // Whether we expect a template header with parameters.
2427 bool NeedNonemptyTemplateHeader = false;
2429 // For a dependent type, the set of template parameters that we
2431 TemplateParameterList *ExpectedTemplateParams = nullptr;
2433 // C++0x [temp.expl.spec]p15:
2434 // A member or a member template may be nested within many enclosing
2435 // class templates. In an explicit specialization for such a member, the
2436 // member declaration shall be preceded by a template<> for each
2437 // enclosing class template that is explicitly specialized.
2438 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2439 if (ClassTemplatePartialSpecializationDecl *Partial
2440 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2441 ExpectedTemplateParams = Partial->getTemplateParameters();
2442 NeedNonemptyTemplateHeader = true;
2443 } else if (Record->isDependentType()) {
2444 if (Record->getDescribedClassTemplate()) {
2445 ExpectedTemplateParams = Record->getDescribedClassTemplate()
2446 ->getTemplateParameters();
2447 NeedNonemptyTemplateHeader = true;
2449 } else if (ClassTemplateSpecializationDecl *Spec
2450 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2451 // C++0x [temp.expl.spec]p4:
2452 // Members of an explicitly specialized class template are defined
2453 // in the same manner as members of normal classes, and not using
2454 // the template<> syntax.
2455 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2456 NeedEmptyTemplateHeader = true;
2459 } else if (Record->getTemplateSpecializationKind()) {
2460 if (Record->getTemplateSpecializationKind()
2461 != TSK_ExplicitSpecialization &&
2462 TypeIdx == NumTypes - 1)
2463 IsMemberSpecialization = true;
2467 } else if (const TemplateSpecializationType *TST
2468 = T->getAs<TemplateSpecializationType>()) {
2469 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2470 ExpectedTemplateParams = Template->getTemplateParameters();
2471 NeedNonemptyTemplateHeader = true;
2473 } else if (T->getAs<DependentTemplateSpecializationType>()) {
2474 // FIXME: We actually could/should check the template arguments here
2475 // against the corresponding template parameter list.
2476 NeedNonemptyTemplateHeader = false;
2479 // C++ [temp.expl.spec]p16:
2480 // In an explicit specialization declaration for a member of a class
2481 // template or a member template that ap- pears in namespace scope, the
2482 // member template and some of its enclosing class templates may remain
2483 // unspecialized, except that the declaration shall not explicitly
2484 // specialize a class member template if its en- closing class templates
2485 // are not explicitly specialized as well.
2486 if (ParamIdx < ParamLists.size()) {
2487 if (ParamLists[ParamIdx]->size() == 0) {
2488 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2492 SawNonEmptyTemplateParameterList = true;
2495 if (NeedEmptyTemplateHeader) {
2496 // If we're on the last of the types, and we need a 'template<>' header
2497 // here, then it's a member specialization.
2498 if (TypeIdx == NumTypes - 1)
2499 IsMemberSpecialization = true;
2501 if (ParamIdx < ParamLists.size()) {
2502 if (ParamLists[ParamIdx]->size() > 0) {
2503 // The header has template parameters when it shouldn't. Complain.
2504 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2505 diag::err_template_param_list_matches_nontemplate)
2507 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2508 ParamLists[ParamIdx]->getRAngleLoc())
2509 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2514 // Consume this template header.
2520 if (DiagnoseMissingExplicitSpecialization(
2521 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
2527 if (NeedNonemptyTemplateHeader) {
2528 // In friend declarations we can have template-ids which don't
2529 // depend on the corresponding template parameter lists. But
2530 // assume that empty parameter lists are supposed to match this
2532 if (IsFriend && T->isDependentType()) {
2533 if (ParamIdx < ParamLists.size() &&
2534 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
2535 ExpectedTemplateParams = nullptr;
2540 if (ParamIdx < ParamLists.size()) {
2541 // Check the template parameter list, if we can.
2542 if (ExpectedTemplateParams &&
2543 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
2544 ExpectedTemplateParams,
2545 true, TPL_TemplateMatch))
2549 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
2550 TPC_ClassTemplateMember))
2557 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2559 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2565 // If there were at least as many template-ids as there were template
2566 // parameter lists, then there are no template parameter lists remaining for
2567 // the declaration itself.
2568 if (ParamIdx >= ParamLists.size()) {
2569 if (TemplateId && !IsFriend) {
2570 // We don't have a template header for the declaration itself, but we
2572 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2573 TemplateId->RAngleLoc));
2575 // Fabricate an empty template parameter list for the invented header.
2576 return TemplateParameterList::Create(Context, SourceLocation(),
2577 SourceLocation(), None,
2578 SourceLocation(), nullptr);
2584 // If there were too many template parameter lists, complain about that now.
2585 if (ParamIdx < ParamLists.size() - 1) {
2586 bool HasAnyExplicitSpecHeader = false;
2587 bool AllExplicitSpecHeaders = true;
2588 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
2589 if (ParamLists[I]->size() == 0)
2590 HasAnyExplicitSpecHeader = true;
2592 AllExplicitSpecHeaders = false;
2595 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2596 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
2597 : diag::err_template_spec_extra_headers)
2598 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
2599 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
2601 // If there was a specialization somewhere, such that 'template<>' is
2602 // not required, and there were any 'template<>' headers, note where the
2603 // specialization occurred.
2604 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
2605 Diag(ExplicitSpecLoc,
2606 diag::note_explicit_template_spec_does_not_need_header)
2607 << NestedTypes.back();
2609 // We have a template parameter list with no corresponding scope, which
2610 // means that the resulting template declaration can't be instantiated
2611 // properly (we'll end up with dependent nodes when we shouldn't).
2612 if (!AllExplicitSpecHeaders)
2616 // C++ [temp.expl.spec]p16:
2617 // In an explicit specialization declaration for a member of a class
2618 // template or a member template that ap- pears in namespace scope, the
2619 // member template and some of its enclosing class templates may remain
2620 // unspecialized, except that the declaration shall not explicitly
2621 // specialize a class member template if its en- closing class templates
2622 // are not explicitly specialized as well.
2623 if (ParamLists.back()->size() == 0 &&
2624 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2628 // Return the last template parameter list, which corresponds to the
2629 // entity being declared.
2630 return ParamLists.back();
2633 void Sema::NoteAllFoundTemplates(TemplateName Name) {
2634 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2635 Diag(Template->getLocation(), diag::note_template_declared_here)
2636 << (isa<FunctionTemplateDecl>(Template)
2638 : isa<ClassTemplateDecl>(Template)
2640 : isa<VarTemplateDecl>(Template)
2642 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2643 << Template->getDeclName();
2647 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
2648 for (OverloadedTemplateStorage::iterator I = OST->begin(),
2651 Diag((*I)->getLocation(), diag::note_template_declared_here)
2652 << 0 << (*I)->getDeclName();
2659 checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
2660 const SmallVectorImpl<TemplateArgument> &Converted,
2661 SourceLocation TemplateLoc,
2662 TemplateArgumentListInfo &TemplateArgs) {
2663 ASTContext &Context = SemaRef.getASTContext();
2664 switch (BTD->getBuiltinTemplateKind()) {
2665 case BTK__make_integer_seq: {
2666 // Specializations of __make_integer_seq<S, T, N> are treated like
2667 // S<T, 0, ..., N-1>.
2669 // C++14 [inteseq.intseq]p1:
2670 // T shall be an integer type.
2671 if (!Converted[1].getAsType()->isIntegralType(Context)) {
2672 SemaRef.Diag(TemplateArgs[1].getLocation(),
2673 diag::err_integer_sequence_integral_element_type);
2677 // C++14 [inteseq.make]p1:
2678 // If N is negative the program is ill-formed.
2679 TemplateArgument NumArgsArg = Converted[2];
2680 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2682 SemaRef.Diag(TemplateArgs[2].getLocation(),
2683 diag::err_integer_sequence_negative_length);
2687 QualType ArgTy = NumArgsArg.getIntegralType();
2688 TemplateArgumentListInfo SyntheticTemplateArgs;
2689 // The type argument gets reused as the first template argument in the
2690 // synthetic template argument list.
2691 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2692 // Expand N into 0 ... N-1.
2693 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2695 TemplateArgument TA(Context, I, ArgTy);
2696 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
2697 TA, ArgTy, TemplateArgs[2].getLocation()));
2699 // The first template argument will be reused as the template decl that
2700 // our synthetic template arguments will be applied to.
2701 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2702 TemplateLoc, SyntheticTemplateArgs);
2705 case BTK__type_pack_element:
2706 // Specializations of
2707 // __type_pack_element<Index, T_1, ..., T_N>
2708 // are treated like T_Index.
2709 assert(Converted.size() == 2 &&
2710 "__type_pack_element should be given an index and a parameter pack");
2712 // If the Index is out of bounds, the program is ill-formed.
2713 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
2714 llvm::APSInt Index = IndexArg.getAsIntegral();
2715 assert(Index >= 0 && "the index used with __type_pack_element should be of "
2716 "type std::size_t, and hence be non-negative");
2717 if (Index >= Ts.pack_size()) {
2718 SemaRef.Diag(TemplateArgs[0].getLocation(),
2719 diag::err_type_pack_element_out_of_bounds);
2723 // We simply return the type at index `Index`.
2724 auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
2725 return Nth->getAsType();
2727 llvm_unreachable("unexpected BuiltinTemplateDecl!");
2730 QualType Sema::CheckTemplateIdType(TemplateName Name,
2731 SourceLocation TemplateLoc,
2732 TemplateArgumentListInfo &TemplateArgs) {
2733 DependentTemplateName *DTN
2734 = Name.getUnderlying().getAsDependentTemplateName();
2735 if (DTN && DTN->isIdentifier())
2736 // When building a template-id where the template-name is dependent,
2737 // assume the template is a type template. Either our assumption is
2738 // correct, or the code is ill-formed and will be diagnosed when the
2739 // dependent name is substituted.
2740 return Context.getDependentTemplateSpecializationType(ETK_None,
2741 DTN->getQualifier(),
2742 DTN->getIdentifier(),
2745 TemplateDecl *Template = Name.getAsTemplateDecl();
2746 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2747 isa<VarTemplateDecl>(Template)) {
2748 // We might have a substituted template template parameter pack. If so,
2749 // build a template specialization type for it.
2750 if (Name.getAsSubstTemplateTemplateParmPack())
2751 return Context.getTemplateSpecializationType(Name, TemplateArgs);
2753 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2755 NoteAllFoundTemplates(Name);
2759 // Check that the template argument list is well-formed for this
2761 SmallVector<TemplateArgument, 4> Converted;
2762 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
2768 bool InstantiationDependent = false;
2769 if (TypeAliasTemplateDecl *AliasTemplate =
2770 dyn_cast<TypeAliasTemplateDecl>(Template)) {
2771 // Find the canonical type for this type alias template specialization.
2772 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2773 if (Pattern->isInvalidDecl())
2776 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2779 // Only substitute for the innermost template argument list.
2780 MultiLevelTemplateArgumentList TemplateArgLists;
2781 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
2782 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2783 for (unsigned I = 0; I < Depth; ++I)
2784 TemplateArgLists.addOuterTemplateArguments(None);
2786 LocalInstantiationScope Scope(*this);
2787 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
2788 if (Inst.isInvalid())
2791 CanonType = SubstType(Pattern->getUnderlyingType(),
2792 TemplateArgLists, AliasTemplate->getLocation(),
2793 AliasTemplate->getDeclName());
2794 if (CanonType.isNull())
2796 } else if (Name.isDependent() ||
2797 TemplateSpecializationType::anyDependentTemplateArguments(
2798 TemplateArgs, InstantiationDependent)) {
2799 // This class template specialization is a dependent
2800 // type. Therefore, its canonical type is another class template
2801 // specialization type that contains all of the converted
2802 // arguments in canonical form. This ensures that, e.g., A<T> and
2803 // A<T, T> have identical types when A is declared as:
2805 // template<typename T, typename U = T> struct A;
2806 CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
2808 // This might work out to be a current instantiation, in which
2809 // case the canonical type needs to be the InjectedClassNameType.
2811 // TODO: in theory this could be a simple hashtable lookup; most
2812 // changes to CurContext don't change the set of current
2814 if (isa<ClassTemplateDecl>(Template)) {
2815 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2816 // If we get out to a namespace, we're done.
2817 if (Ctx->isFileContext()) break;
2819 // If this isn't a record, keep looking.
2820 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2821 if (!Record) continue;
2823 // Look for one of the two cases with InjectedClassNameTypes
2824 // and check whether it's the same template.
2825 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2826 !Record->getDescribedClassTemplate())
2829 // Fetch the injected class name type and check whether its
2830 // injected type is equal to the type we just built.
2831 QualType ICNT = Context.getTypeDeclType(Record);
2832 QualType Injected = cast<InjectedClassNameType>(ICNT)
2833 ->getInjectedSpecializationType();
2835 if (CanonType != Injected->getCanonicalTypeInternal())
2838 // If so, the canonical type of this TST is the injected
2839 // class name type of the record we just found.
2840 assert(ICNT.isCanonical());
2845 } else if (ClassTemplateDecl *ClassTemplate
2846 = dyn_cast<ClassTemplateDecl>(Template)) {
2847 // Find the class template specialization declaration that
2848 // corresponds to these arguments.
2849 void *InsertPos = nullptr;
2850 ClassTemplateSpecializationDecl *Decl
2851 = ClassTemplate->findSpecialization(Converted, InsertPos);
2853 // This is the first time we have referenced this class template
2854 // specialization. Create the canonical declaration and add it to
2855 // the set of specializations.
2856 Decl = ClassTemplateSpecializationDecl::Create(Context,
2857 ClassTemplate->getTemplatedDecl()->getTagKind(),
2858 ClassTemplate->getDeclContext(),
2859 ClassTemplate->getTemplatedDecl()->getLocStart(),
2860 ClassTemplate->getLocation(),
2862 Converted, nullptr);
2863 ClassTemplate->AddSpecialization(Decl, InsertPos);
2864 if (ClassTemplate->isOutOfLine())
2865 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
2868 if (Decl->getSpecializationKind() == TSK_Undeclared) {
2869 MultiLevelTemplateArgumentList TemplateArgLists;
2870 TemplateArgLists.addOuterTemplateArguments(Converted);
2871 InstantiateAttrsForDecl(TemplateArgLists, ClassTemplate->getTemplatedDecl(),
2875 // Diagnose uses of this specialization.
2876 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2878 CanonType = Context.getTypeDeclType(Decl);
2879 assert(isa<RecordType>(CanonType) &&
2880 "type of non-dependent specialization is not a RecordType");
2881 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
2882 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
2886 // Build the fully-sugared type for this class template
2887 // specialization, which refers back to the class template
2888 // specialization we created or found.
2889 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
2893 Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
2894 TemplateTy TemplateD, IdentifierInfo *TemplateII,
2895 SourceLocation TemplateIILoc,
2896 SourceLocation LAngleLoc,
2897 ASTTemplateArgsPtr TemplateArgsIn,
2898 SourceLocation RAngleLoc,
2899 bool IsCtorOrDtorName, bool IsClassName) {
2903 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
2904 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
2906 // C++ [temp.res]p3:
2907 // A qualified-id that refers to a type and in which the
2908 // nested-name-specifier depends on a template-parameter (14.6.2)
2909 // shall be prefixed by the keyword typename to indicate that the
2910 // qualified-id denotes a type, forming an
2911 // elaborated-type-specifier (7.1.5.3).
2912 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
2913 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
2914 << SS.getScopeRep() << TemplateII->getName();
2915 // Recover as if 'typename' were specified.
2916 // FIXME: This is not quite correct recovery as we don't transform SS
2917 // into the corresponding dependent form (and we don't diagnose missing
2918 // 'template' keywords within SS as a result).
2919 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
2920 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
2921 TemplateArgsIn, RAngleLoc);
2924 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
2925 // it's not actually allowed to be used as a type in most cases. Because
2926 // we annotate it before we know whether it's valid, we have to check for
2928 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
2929 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
2931 TemplateKWLoc.isInvalid()
2932 ? diag::err_out_of_line_qualified_id_type_names_constructor
2933 : diag::ext_out_of_line_qualified_id_type_names_constructor)
2934 << TemplateII << 0 /*injected-class-name used as template name*/
2935 << 1 /*if any keyword was present, it was 'template'*/;
2939 TemplateName Template = TemplateD.get();
2941 // Translate the parser's template argument list in our AST format.
2942 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2943 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2945 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2947 = Context.getDependentTemplateSpecializationType(ETK_None,
2948 DTN->getQualifier(),
2949 DTN->getIdentifier(),
2951 // Build type-source information.
2953 DependentTemplateSpecializationTypeLoc SpecTL
2954 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2955 SpecTL.setElaboratedKeywordLoc(SourceLocation());
2956 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
2957 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2958 SpecTL.setTemplateNameLoc(TemplateIILoc);
2959 SpecTL.setLAngleLoc(LAngleLoc);
2960 SpecTL.setRAngleLoc(RAngleLoc);
2961 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2962 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2963 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2966 QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
2967 if (Result.isNull())
2970 // Build type-source information.
2972 TemplateSpecializationTypeLoc SpecTL
2973 = TLB.push<TemplateSpecializationTypeLoc>(Result);
2974 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2975 SpecTL.setTemplateNameLoc(TemplateIILoc);
2976 SpecTL.setLAngleLoc(LAngleLoc);
2977 SpecTL.setRAngleLoc(RAngleLoc);
2978 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2979 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
2981 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2982 // constructor or destructor name (in such a case, the scope specifier
2983 // will be attached to the enclosing Decl or Expr node).
2984 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
2985 // Create an elaborated-type-specifier containing the nested-name-specifier.
2986 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2987 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
2988 ElabTL.setElaboratedKeywordLoc(SourceLocation());
2989 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2992 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
2995 TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
2996 TypeSpecifierType TagSpec,
2997 SourceLocation TagLoc,
2999 SourceLocation TemplateKWLoc,
3000 TemplateTy TemplateD,
3001 SourceLocation TemplateLoc,
3002 SourceLocation LAngleLoc,
3003 ASTTemplateArgsPtr TemplateArgsIn,
3004 SourceLocation RAngleLoc) {
3005 TemplateName Template = TemplateD.get();
3007 // Translate the parser's template argument list in our AST format.
3008 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3009 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3011 // Determine the tag kind
3012 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3013 ElaboratedTypeKeyword Keyword
3014 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
3016 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3017 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
3018 DTN->getQualifier(),
3019 DTN->getIdentifier(),
3022 // Build type-source information.
3024 DependentTemplateSpecializationTypeLoc SpecTL
3025 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3026 SpecTL.setElaboratedKeywordLoc(TagLoc);
3027 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3028 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3029 SpecTL.setTemplateNameLoc(TemplateLoc);
3030 SpecTL.setLAngleLoc(LAngleLoc);
3031 SpecTL.setRAngleLoc(RAngleLoc);
3032 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3033 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3034 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3037 if (TypeAliasTemplateDecl *TAT =
3038 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3039 // C++0x [dcl.type.elab]p2:
3040 // If the identifier resolves to a typedef-name or the simple-template-id
3041 // resolves to an alias template specialization, the
3042 // elaborated-type-specifier is ill-formed.
3043 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3044 << TAT << NTK_TypeAliasTemplate << TagKind;
3045 Diag(TAT->getLocation(), diag::note_declared_at);
3048 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3049 if (Result.isNull())
3050 return TypeResult(true);
3052 // Check the tag kind
3053 if (const RecordType *RT = Result->getAs<RecordType>()) {
3054 RecordDecl *D = RT->getDecl();
3056 IdentifierInfo *Id = D->getIdentifier();
3057 assert(Id && "templated class must have an identifier");
3059 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
3061 Diag(TagLoc, diag::err_use_with_wrong_tag)
3063 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
3064 Diag(D->getLocation(), diag::note_previous_use);
3068 // Provide source-location information for the template specialization.
3070 TemplateSpecializationTypeLoc SpecTL
3071 = TLB.push<TemplateSpecializationTypeLoc>(Result);
3072 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3073 SpecTL.setTemplateNameLoc(TemplateLoc);
3074 SpecTL.setLAngleLoc(LAngleLoc);
3075 SpecTL.setRAngleLoc(RAngleLoc);
3076 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3077 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3079 // Construct an elaborated type containing the nested-name-specifier (if any)
3081 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
3082 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
3083 ElabTL.setElaboratedKeywordLoc(TagLoc);
3084 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3085 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
3088 static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3089 NamedDecl *PrevDecl,
3091 bool IsPartialSpecialization);
3093 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
3095 static bool isTemplateArgumentTemplateParameter(
3096 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3097 switch (Arg.getKind()) {
3098 case TemplateArgument::Null:
3099 case TemplateArgument::NullPtr:
3100 case TemplateArgument::Integral:
3101 case TemplateArgument::Declaration:
3102 case TemplateArgument::Pack:
3103 case TemplateArgument::TemplateExpansion:
3106 case TemplateArgument::Type: {
3107 QualType Type = Arg.getAsType();
3108 const TemplateTypeParmType *TPT =
3109 Arg.getAsType()->getAs<TemplateTypeParmType>();
3110 return TPT && !Type.hasQualifiers() &&
3111 TPT->getDepth() == Depth && TPT->getIndex() == Index;
3114 case TemplateArgument::Expression: {
3115 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3116 if (!DRE || !DRE->getDecl())
3118 const NonTypeTemplateParmDecl *NTTP =
3119 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3120 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3123 case TemplateArgument::Template:
3124 const TemplateTemplateParmDecl *TTP =
3125 dyn_cast_or_null<TemplateTemplateParmDecl>(
3126 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
3127 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3129 llvm_unreachable("unexpected kind of template argument");
3132 static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
3133 ArrayRef<TemplateArgument> Args) {
3134 if (Params->size() != Args.size())
3137 unsigned Depth = Params->getDepth();
3139 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3140 TemplateArgument Arg = Args[I];
3142 // If the parameter is a pack expansion, the argument must be a pack
3143 // whose only element is a pack expansion.
3144 if (Params->getParam(I)->isParameterPack()) {
3145 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
3146 !Arg.pack_begin()->isPackExpansion())
3148 Arg = Arg.pack_begin()->getPackExpansionPattern();
3151 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
3158 /// Convert the parser's template argument list representation into our form.
3159 static TemplateArgumentListInfo
3160 makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
3161 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
3162 TemplateId.RAngleLoc);
3163 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
3164 TemplateId.NumArgs);
3165 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
3166 return TemplateArgs;
3169 template<typename PartialSpecDecl>
3170 static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
3171 if (Partial->getDeclContext()->isDependentContext())
3174 // FIXME: Get the TDK from deduction in order to provide better diagnostics
3175 // for non-substitution-failure issues?
3176 TemplateDeductionInfo Info(Partial->getLocation());
3177 if (S.isMoreSpecializedThanPrimary(Partial, Info))
3180 auto *Template = Partial->getSpecializedTemplate();
3181 S.Diag(Partial->getLocation(),
3182 diag::ext_partial_spec_not_more_specialized_than_primary)
3183 << isa<VarTemplateDecl>(Template);
3185 if (Info.hasSFINAEDiagnostic()) {
3186 PartialDiagnosticAt Diag = {SourceLocation(),
3187 PartialDiagnostic::NullDiagnostic()};
3188 Info.takeSFINAEDiagnostic(Diag);
3189 SmallString<128> SFINAEArgString;
3190 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
3192 diag::note_partial_spec_not_more_specialized_than_primary)
3196 S.Diag(Template->getLocation(), diag::note_template_decl_here);
3200 noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
3201 const llvm::SmallBitVector &DeducibleParams) {
3202 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3203 if (!DeducibleParams[I]) {
3204 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3205 if (Param->getDeclName())
3206 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3207 << Param->getDeclName();
3209 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3216 template<typename PartialSpecDecl>
3217 static void checkTemplatePartialSpecialization(Sema &S,
3218 PartialSpecDecl *Partial) {
3219 // C++1z [temp.class.spec]p8: (DR1495)
3220 // - The specialization shall be more specialized than the primary
3221 // template (14.5.5.2).
3222 checkMoreSpecializedThanPrimary(S, Partial);
3224 // C++ [temp.class.spec]p8: (DR1315)
3225 // - Each template-parameter shall appear at least once in the
3226 // template-id outside a non-deduced context.
3227 // C++1z [temp.class.spec.match]p3 (P0127R2)
3228 // If the template arguments of a partial specialization cannot be
3229 // deduced because of the structure of its template-parameter-list
3230 // and the template-id, the program is ill-formed.
3231 auto *TemplateParams = Partial->getTemplateParameters();
3232 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3233 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3234 TemplateParams->getDepth(), DeducibleParams);
3236 if (!DeducibleParams.all()) {
3237 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3238 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
3239 << isa<VarTemplatePartialSpecializationDecl>(Partial)
3240 << (NumNonDeducible > 1)
3241 << SourceRange(Partial->getLocation(),
3242 Partial->getTemplateArgsAsWritten()->RAngleLoc);
3243 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
3247 void Sema::CheckTemplatePartialSpecialization(
3248 ClassTemplatePartialSpecializationDecl *Partial) {
3249 checkTemplatePartialSpecialization(*this, Partial);
3252 void Sema::CheckTemplatePartialSpecialization(
3253 VarTemplatePartialSpecializationDecl *Partial) {
3254 checkTemplatePartialSpecialization(*this, Partial);
3257 void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
3258 // C++1z [temp.param]p11:
3259 // A template parameter of a deduction guide template that does not have a
3260 // default-argument shall be deducible from the parameter-type-list of the
3261 // deduction guide template.
3262 auto *TemplateParams = TD->getTemplateParameters();
3263 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3264 MarkDeducedTemplateParameters(TD, DeducibleParams);
3265 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
3266 // A parameter pack is deducible (to an empty pack).
3267 auto *Param = TemplateParams->getParam(I);
3268 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
3269 DeducibleParams[I] = true;
3272 if (!DeducibleParams.all()) {
3273 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3274 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
3275 << (NumNonDeducible > 1);
3276 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
3280 DeclResult Sema::ActOnVarTemplateSpecialization(
3281 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
3282 TemplateParameterList *TemplateParams, StorageClass SC,
3283 bool IsPartialSpecialization) {
3284 // D must be variable template id.
3285 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
3286 "Variable template specialization is declared with a template it.");
3288 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
3289 TemplateArgumentListInfo TemplateArgs =
3290 makeTemplateArgumentListInfo(*this, *TemplateId);
3291 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
3292 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
3293 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
3295 TemplateName Name = TemplateId->Template.get();
3297 // The template-id must name a variable template.
3298 VarTemplateDecl *VarTemplate =
3299 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
3301 NamedDecl *FnTemplate;
3302 if (auto *OTS = Name.getAsOverloadedTemplate())
3303 FnTemplate = *OTS->begin();
3305 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
3307 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
3308 << FnTemplate->getDeclName();
3309 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
3310 << IsPartialSpecialization;
3313 // Check for unexpanded parameter packs in any of the template arguments.
3314 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3315 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
3316 UPPC_PartialSpecialization))
3319 // Check that the template argument list is well-formed for this
3321 SmallVector<TemplateArgument, 4> Converted;
3322 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
3326 // Find the variable template (partial) specialization declaration that
3327 // corresponds to these arguments.
3328 if (IsPartialSpecialization) {
3329 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
3330 TemplateArgs.size(), Converted))
3333 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
3334 // also do them during instantiation.
3335 bool InstantiationDependent;
3336 if (!Name.isDependent() &&
3337 !TemplateSpecializationType::anyDependentTemplateArguments(
3338 TemplateArgs.arguments(),
3339 InstantiationDependent)) {
3340 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3341 << VarTemplate->getDeclName();
3342 IsPartialSpecialization = false;
3345 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
3347 // C++ [temp.class.spec]p9b3:
3349 // -- The argument list of the specialization shall not be identical
3350 // to the implicit argument list of the primary template.
3351 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
3352 << /*variable template*/ 1
3353 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
3354 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
3355 // FIXME: Recover from this by treating the declaration as a redeclaration
3356 // of the primary template.
3361 void *InsertPos = nullptr;
3362 VarTemplateSpecializationDecl *PrevDecl = nullptr;
3364 if (IsPartialSpecialization)
3365 // FIXME: Template parameter list matters too
3366 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
3368 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
3370 VarTemplateSpecializationDecl *Specialization = nullptr;
3372 // Check whether we can declare a variable template specialization in
3373 // the current scope.
3374 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
3376 IsPartialSpecialization))
3379 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3380 // Since the only prior variable template specialization with these
3381 // arguments was referenced but not declared, reuse that
3382 // declaration node as our own, updating its source location and
3383 // the list of outer template parameters to reflect our new declaration.
3384 Specialization = PrevDecl;
3385 Specialization->setLocation(TemplateNameLoc);
3387 } else if (IsPartialSpecialization) {
3388 // Create a new class template partial specialization declaration node.
3389 VarTemplatePartialSpecializationDecl *PrevPartial =
3390 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
3391 VarTemplatePartialSpecializationDecl *Partial =
3392 VarTemplatePartialSpecializationDecl::Create(
3393 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
3394 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
3395 Converted, TemplateArgs);
3398 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
3399 Specialization = Partial;
3401 // If we are providing an explicit specialization of a member variable
3402 // template specialization, make a note of that.
3403 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3404 PrevPartial->setMemberSpecialization();
3406 CheckTemplatePartialSpecialization(Partial);
3408 // Create a new class template specialization declaration node for
3409 // this explicit specialization or friend declaration.
3410 Specialization = VarTemplateSpecializationDecl::Create(
3411 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
3412 VarTemplate, DI->getType(), DI, SC, Converted);
3413 Specialization->setTemplateArgsInfo(TemplateArgs);
3416 VarTemplate->AddSpecialization(Specialization, InsertPos);
3419 // C++ [temp.expl.spec]p6:
3420 // If a template, a member template or the member of a class template is
3421 // explicitly specialized then that specialization shall be declared
3422 // before the first use of that specialization that would cause an implicit
3423 // instantiation to take place, in every translation unit in which such a
3424 // use occurs; no diagnostic is required.
3425 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3427 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
3428 // Is there any previous explicit specialization declaration?
3429 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3436 SourceRange Range(TemplateNameLoc, RAngleLoc);
3437 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3440 Diag(PrevDecl->getPointOfInstantiation(),
3441 diag::note_instantiation_required_here)
3442 << (PrevDecl->getTemplateSpecializationKind() !=
3443 TSK_ImplicitInstantiation);
3448 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
3449 Specialization->setLexicalDeclContext(CurContext);
3451 // Add the specialization into its lexical context, so that it can
3452 // be seen when iterating through the list of declarations in that
3453 // context. However, specializations are not found by name lookup.
3454 CurContext->addDecl(Specialization);
3456 // Note that this is an explicit specialization.
3457 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
3460 // Check that this isn't a redefinition of this specialization,
3461 // merging with previous declarations.
3462 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
3464 PrevSpec.addDecl(PrevDecl);
3465 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
3466 } else if (Specialization->isStaticDataMember() &&
3467 Specialization->isOutOfLine()) {
3468 Specialization->setAccess(VarTemplate->getAccess());
3471 // Link instantiations of static data members back to the template from
3472 // which they were instantiated.
3473 if (Specialization->isStaticDataMember())
3474 Specialization->setInstantiationOfStaticDataMember(
3475 VarTemplate->getTemplatedDecl(),
3476 Specialization->getSpecializationKind());
3478 return Specialization;
3482 /// \brief A partial specialization whose template arguments have matched
3483 /// a given template-id.
3484 struct PartialSpecMatchResult {
3485 VarTemplatePartialSpecializationDecl *Partial;
3486 TemplateArgumentList *Args;
3488 } // end anonymous namespace
3491 Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
3492 SourceLocation TemplateNameLoc,
3493 const TemplateArgumentListInfo &TemplateArgs) {
3494 assert(Template && "A variable template id without template?");
3496 // Check that the template argument list is well-formed for this template.
3497 SmallVector<TemplateArgument, 4> Converted;
3498 if (CheckTemplateArgumentList(
3499 Template, TemplateNameLoc,
3500 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
3504 // Find the variable template specialization declaration that
3505 // corresponds to these arguments.
3506 void *InsertPos = nullptr;
3507 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
3508 Converted, InsertPos)) {
3509 checkSpecializationVisibility(TemplateNameLoc, Spec);
3510 // If we already have a variable template specialization, return it.
3514 // This is the first time we have referenced this variable template
3515 // specialization. Create the canonical declaration and add it to
3516 // the set of specializations, based on the closest partial specialization
3517 // that it represents. That is,
3518 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
3519 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
3521 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
3522 bool AmbiguousPartialSpec = false;
3523 typedef PartialSpecMatchResult MatchResult;
3524 SmallVector<MatchResult, 4> Matched;
3525 SourceLocation PointOfInstantiation = TemplateNameLoc;
3526 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
3527 /*ForTakingAddress=*/false);
3529 // 1. Attempt to find the closest partial specialization that this
3530 // specializes, if any.
3531 // If any of the template arguments is dependent, then this is probably
3532 // a placeholder for an incomplete declarative context; which must be
3533 // complete by instantiation time. Thus, do not search through the partial
3534 // specializations yet.
3535 // TODO: Unify with InstantiateClassTemplateSpecialization()?
3536 // Perhaps better after unification of DeduceTemplateArguments() and
3537 // getMoreSpecializedPartialSpecialization().
3538 bool InstantiationDependent = false;
3539 if (!TemplateSpecializationType::anyDependentTemplateArguments(
3540 TemplateArgs, InstantiationDependent)) {
3542 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
3543 Template->getPartialSpecializations(PartialSpecs);
3545 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3546 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
3547 TemplateDeductionInfo Info(FailedCandidates.getLocation());
3549 if (TemplateDeductionResult Result =
3550 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
3551 // Store the failed-deduction information for use in diagnostics, later.
3552 // TODO: Actually use the failed-deduction info?
3553 FailedCandidates.addCandidate().set(
3554 DeclAccessPair::make(Template, AS_public), Partial,
3555 MakeDeductionFailureInfo(Context, Result, Info));
3558 Matched.push_back(PartialSpecMatchResult());
3559 Matched.back().Partial = Partial;
3560 Matched.back().Args = Info.take();
3564 if (Matched.size() >= 1) {
3565 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
3566 if (Matched.size() == 1) {
3567 // -- If exactly one matching specialization is found, the
3568 // instantiation is generated from that specialization.
3569 // We don't need to do anything for this.
3571 // -- If more than one matching specialization is found, the
3572 // partial order rules (14.5.4.2) are used to determine
3573 // whether one of the specializations is more specialized
3574 // than the others. If none of the specializations is more
3575 // specialized than all of the other matching
3576 // specializations, then the use of the variable template is
3577 // ambiguous and the program is ill-formed.
3578 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
3579 PEnd = Matched.end();
3581 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
3582 PointOfInstantiation) ==
3587 // Determine if the best partial specialization is more specialized than
3589 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
3590 PEnd = Matched.end();
3592 if (P != Best && getMoreSpecializedPartialSpecialization(
3593 P->Partial, Best->Partial,
3594 PointOfInstantiation) != Best->Partial) {
3595 AmbiguousPartialSpec = true;
3601 // Instantiate using the best variable template partial specialization.
3602 InstantiationPattern = Best->Partial;
3603 InstantiationArgs = Best->Args;
3605 // -- If no match is found, the instantiation is generated
3606 // from the primary template.
3607 // InstantiationPattern = Template->getTemplatedDecl();
3611 // 2. Create the canonical declaration.
3612 // Note that we do not instantiate a definition until we see an odr-use
3613 // in DoMarkVarDeclReferenced().
3614 // FIXME: LateAttrs et al.?
3615 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
3616 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
3617 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
3621 if (AmbiguousPartialSpec) {
3622 // Partial ordering did not produce a clear winner. Complain.
3623 Decl->setInvalidDecl();
3624 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
3627 // Print the matching partial specializations.
3628 for (MatchResult P : Matched)
3629 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
3630 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
3635 if (VarTemplatePartialSpecializationDecl *D =
3636 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
3637 Decl->setInstantiationOf(D, InstantiationArgs);
3639 checkSpecializationVisibility(TemplateNameLoc, Decl);
3641 assert(Decl && "No variable template specialization?");
3646 Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
3647 const DeclarationNameInfo &NameInfo,
3648 VarTemplateDecl *Template, SourceLocation TemplateLoc,
3649 const TemplateArgumentListInfo *TemplateArgs) {
3651 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
3653 if (Decl.isInvalid())
3656 VarDecl *Var = cast<VarDecl>(Decl.get());
3657 if (!Var->getTemplateSpecializationKind())
3658 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
3661 // Build an ordinary singleton decl ref.
3662 return BuildDeclarationNameExpr(SS, NameInfo, Var,
3663 /*FoundD=*/nullptr, TemplateArgs);
3666 ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
3667 SourceLocation TemplateKWLoc,
3670 const TemplateArgumentListInfo *TemplateArgs) {
3671 // FIXME: Can we do any checking at this point? I guess we could check the
3672 // template arguments that we have against the template name, if the template
3673 // name refers to a single template. That's not a terribly common case,
3675 // foo<int> could identify a single function unambiguously
3676 // This approach does NOT work, since f<int>(1);
3677 // gets resolved prior to resorting to overload resolution
3678 // i.e., template<class T> void f(double);
3679 // vs template<class T, class U> void f(U);
3681 // These should be filtered out by our callers.
3682 assert(!R.empty() && "empty lookup results when building templateid");
3683 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
3685 // In C++1y, check variable template ids.
3686 bool InstantiationDependent;
3687 if (R.getAsSingle<VarTemplateDecl>() &&
3688 !TemplateSpecializationType::anyDependentTemplateArguments(
3689 *TemplateArgs, InstantiationDependent)) {
3690 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
3691 R.getAsSingle<VarTemplateDecl>(),
3692 TemplateKWLoc, TemplateArgs);
3695 // We don't want lookup warnings at this point.
3696 R.suppressDiagnostics();
3698 UnresolvedLookupExpr *ULE
3699 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3700 SS.getWithLocInContext(Context),
3702 R.getLookupNameInfo(),
3703 RequiresADL, TemplateArgs,
3704 R.begin(), R.end());
3709 // We actually only call this from template instantiation.
3711 Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
3712 SourceLocation TemplateKWLoc,
3713 const DeclarationNameInfo &NameInfo,
3714 const TemplateArgumentListInfo *TemplateArgs) {
3716 assert(TemplateArgs || TemplateKWLoc.isValid());
3718 if (!(DC = computeDeclContext(SS, false)) ||
3719 DC->isDependentContext() ||
3720 RequireCompleteDeclContext(SS, DC))
3721 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
3723 bool MemberOfUnknownSpecialization;
3724 LookupResult R(*this, NameInfo, LookupOrdinaryName);
3725 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
3726 MemberOfUnknownSpecialization);
3728 if (R.isAmbiguous())
3732 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
3733 << NameInfo.getName() << SS.getRange();
3737 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
3738 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
3740 << NameInfo.getName().getAsString() << SS.getRange();
3741 Diag(Temp->getLocation(), diag::note_referenced_class_template);
3745 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
3748 /// \brief Form a dependent template name.
3750 /// This action forms a dependent template name given the template
3751 /// name and its (presumably dependent) scope specifier. For
3752 /// example, given "MetaFun::template apply", the scope specifier \p
3753 /// SS will be "MetaFun::", \p TemplateKWLoc contains the location
3754 /// of the "template" keyword, and "apply" is the \p Name.
3755 TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
3757 SourceLocation TemplateKWLoc,
3758 UnqualifiedId &Name,
3759 ParsedType ObjectType,
3760 bool EnteringContext,
3762 bool AllowInjectedClassName) {
3763 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
3765 getLangOpts().CPlusPlus11 ?
3766 diag::warn_cxx98_compat_template_outside_of_template :
3767 diag::ext_template_outside_of_template)
3768 << FixItHint::CreateRemoval(TemplateKWLoc);
3770 DeclContext *LookupCtx = nullptr;
3772 LookupCtx = computeDeclContext(SS, EnteringContext);
3773 if (!LookupCtx && ObjectType)
3774 LookupCtx = computeDeclContext(ObjectType.get());
3776 // C++0x [temp.names]p5:
3777 // If a name prefixed by the keyword template is not the name of
3778 // a template, the program is ill-formed. [Note: the keyword
3779 // template may not be applied to non-template members of class
3780 // templates. -end note ] [ Note: as is the case with the
3781 // typename prefix, the template prefix is allowed in cases
3782 // where it is not strictly necessary; i.e., when the
3783 // nested-name-specifier or the expression on the left of the ->
3784 // or . is not dependent on a template-parameter, or the use
3785 // does not appear in the scope of a template. -end note]
3787 // Note: C++03 was more strict here, because it banned the use of
3788 // the "template" keyword prior to a template-name that was not a
3789 // dependent name. C++ DR468 relaxed this requirement (the
3790 // "template" keyword is now permitted). We follow the C++0x
3791 // rules, even in C++03 mode with a warning, retroactively applying the DR.
3792 bool MemberOfUnknownSpecialization;
3793 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
3794 ObjectType, EnteringContext, Result,
3795 MemberOfUnknownSpecialization);
3796 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
3797 isa<CXXRecordDecl>(LookupCtx) &&
3798 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
3799 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
3800 // This is a dependent template. Handle it below.
3801 } else if (TNK == TNK_Non_template) {
3802 Diag(Name.getLocStart(),
3803 diag::err_template_kw_refers_to_non_template)
3804 << GetNameFromUnqualifiedId(Name).getName()
3805 << Name.getSourceRange()
3807 return TNK_Non_template;
3809 // We found something; return it.
3810 auto *LookupRD = dyn_cast<CXXRecordDecl>(LookupCtx);
3811 if (!AllowInjectedClassName && SS.isSet() && LookupRD &&
3812 Name.getKind() == UnqualifiedId::IK_Identifier && Name.Identifier &&
3813 LookupRD->getIdentifier() == Name.Identifier) {
3814 // C++14 [class.qual]p2:
3815 // In a lookup in which function names are not ignored and the
3816 // nested-name-specifier nominates a class C, if the name specified
3817 // [...] is the injected-class-name of C, [...] the name is instead
3818 // considered to name the constructor
3820 // We don't get here if naming the constructor would be valid, so we
3821 // just reject immediately and recover by treating the
3822 // injected-class-name as naming the template.
3823 Diag(Name.getLocStart(),
3824 diag::ext_out_of_line_qualified_id_type_names_constructor)
3825 << Name.Identifier << 0 /*injected-class-name used as template name*/
3826 << 1 /*'template' keyword was used*/;
3832 NestedNameSpecifier *Qualifier = SS.getScopeRep();
3834 switch (Name.getKind()) {
3835 case UnqualifiedId::IK_Identifier:
3836 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
3838 return TNK_Dependent_template_name;
3840 case UnqualifiedId::IK_OperatorFunctionId:
3841 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
3842 Name.OperatorFunctionId.Operator));
3843 return TNK_Function_template;
3845 case UnqualifiedId::IK_LiteralOperatorId:
3846 llvm_unreachable("literal operator id cannot have a dependent scope");
3852 Diag(Name.getLocStart(),
3853 diag::err_template_kw_refers_to_non_template)
3854 << GetNameFromUnqualifiedId(Name).getName()
3855 << Name.getSourceRange()
3857 return TNK_Non_template;
3860 bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
3861 TemplateArgumentLoc &AL,
3862 SmallVectorImpl<TemplateArgument> &Converted) {
3863 const TemplateArgument &Arg = AL.getArgument();
3865 TypeSourceInfo *TSI = nullptr;
3867 // Check template type parameter.
3868 switch(Arg.getKind()) {
3869 case TemplateArgument::Type:
3870 // C++ [temp.arg.type]p1:
3871 // A template-argument for a template-parameter which is a
3872 // type shall be a type-id.
3873 ArgType = Arg.getAsType();
3874 TSI = AL.getTypeSourceInfo();
3876 case TemplateArgument::Template: {
3877 // We have a template type parameter but the template argument
3878 // is a template without any arguments.
3879 SourceRange SR = AL.getSourceRange();
3880 TemplateName Name = Arg.getAsTemplate();
3881 Diag(SR.getBegin(), diag::err_template_missing_args)
3882 << (int)getTemplateNameKindForDiagnostics(Name) << Name << SR;
3883 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3884 Diag(Decl->getLocation(), diag::note_template_decl_here);
3888 case TemplateArgument::Expression: {
3889 // We have a template type parameter but the template argument is an
3890 // expression; see if maybe it is missing the "typename" keyword.
3892 DeclarationNameInfo NameInfo;
3894 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3895 SS.Adopt(ArgExpr->getQualifierLoc());
3896 NameInfo = ArgExpr->getNameInfo();
3897 } else if (DependentScopeDeclRefExpr *ArgExpr =
3898 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3899 SS.Adopt(ArgExpr->getQualifierLoc());
3900 NameInfo = ArgExpr->getNameInfo();
3901 } else if (CXXDependentScopeMemberExpr *ArgExpr =
3902 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
3903 if (ArgExpr->isImplicitAccess()) {
3904 SS.Adopt(ArgExpr->getQualifierLoc());
3905 NameInfo = ArgExpr->getMemberNameInfo();
3909 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
3910 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3911 LookupParsedName(Result, CurScope, &SS);
3913 if (Result.getAsSingle<TypeDecl>() ||
3914 Result.getResultKind() ==
3915 LookupResult::NotFoundInCurrentInstantiation) {
3916 // Suggest that the user add 'typename' before the NNS.
3917 SourceLocation Loc = AL.getSourceRange().getBegin();
3918 Diag(Loc, getLangOpts().MSVCCompat
3919 ? diag::ext_ms_template_type_arg_missing_typename
3920 : diag::err_template_arg_must_be_type_suggest)
3921 << FixItHint::CreateInsertion(Loc, "typename ");
3922 Diag(Param->getLocation(), diag::note_template_param_here);
3924 // Recover by synthesizing a type using the location information that we
3927 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
3929 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
3930 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
3931 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3932 TL.setNameLoc(NameInfo.getLoc());
3933 TSI = TLB.getTypeSourceInfo(Context, ArgType);
3935 // Overwrite our input TemplateArgumentLoc so that we can recover
3937 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
3938 TemplateArgumentLocInfo(TSI));
3946 // We have a template type parameter but the template argument
3948 SourceRange SR = AL.getSourceRange();
3949 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
3950 Diag(Param->getLocation(), diag::note_template_param_here);
3956 if (CheckTemplateArgument(Param, TSI))
3959 // Add the converted template type argument.
3960 ArgType = Context.getCanonicalType(ArgType);
3963 // If an explicitly-specified template argument type is a lifetime type
3964 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
3965 if (getLangOpts().ObjCAutoRefCount &&
3966 ArgType->isObjCLifetimeType() &&
3967 !ArgType.getObjCLifetime()) {
3969 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
3970 ArgType = Context.getQualifiedType(ArgType, Qs);
3973 Converted.push_back(TemplateArgument(ArgType));
3977 /// \brief Substitute template arguments into the default template argument for
3978 /// the given template type parameter.
3980 /// \param SemaRef the semantic analysis object for which we are performing
3981 /// the substitution.
3983 /// \param Template the template that we are synthesizing template arguments
3986 /// \param TemplateLoc the location of the template name that started the
3987 /// template-id we are checking.
3989 /// \param RAngleLoc the location of the right angle bracket ('>') that
3990 /// terminates the template-id.
3992 /// \param Param the template template parameter whose default we are
3993 /// substituting into.
3995 /// \param Converted the list of template arguments provided for template
3996 /// parameters that precede \p Param in the template parameter list.
3997 /// \returns the substituted template argument, or NULL if an error occurred.
3998 static TypeSourceInfo *
3999 SubstDefaultTemplateArgument(Sema &SemaRef,
4000 TemplateDecl *Template,
4001 SourceLocation TemplateLoc,
4002 SourceLocation RAngleLoc,
4003 TemplateTypeParmDecl *Param,
4004 SmallVectorImpl<TemplateArgument> &Converted) {
4005 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
4007 // If the argument type is dependent, instantiate it now based
4008 // on the previously-computed template arguments.
4009 if (ArgType->getType()->isDependentType()) {
4010 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
4011 Param, Template, Converted,
4012 SourceRange(TemplateLoc, RAngleLoc));
4013 if (Inst.isInvalid())
4016 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4018 // Only substitute for the innermost template argument list.
4019 MultiLevelTemplateArgumentList TemplateArgLists;
4020 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4021 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4022 TemplateArgLists.addOuterTemplateArguments(None);
4024 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4026 SemaRef.SubstType(ArgType, TemplateArgLists,
4027 Param->getDefaultArgumentLoc(), Param->getDeclName());
4033 /// \brief Substitute template arguments into the default template argument for
4034 /// the given non-type template parameter.
4036 /// \param SemaRef the semantic analysis object for which we are performing
4037 /// the substitution.
4039 /// \param Template the template that we are synthesizing template arguments
4042 /// \param TemplateLoc the location of the template name that started the
4043 /// template-id we are checking.
4045 /// \param RAngleLoc the location of the right angle bracket ('>') that
4046 /// terminates the template-id.
4048 /// \param Param the non-type template parameter whose default we are
4049 /// substituting into.
4051 /// \param Converted the list of template arguments provided for template
4052 /// parameters that precede \p Param in the template parameter list.
4054 /// \returns the substituted template argument, or NULL if an error occurred.
4056 SubstDefaultTemplateArgument(Sema &SemaRef,
4057 TemplateDecl *Template,
4058 SourceLocation TemplateLoc,
4059 SourceLocation RAngleLoc,
4060 NonTypeTemplateParmDecl *Param,
4061 SmallVectorImpl<TemplateArgument> &Converted) {
4062 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
4063 Param, Template, Converted,
4064 SourceRange(TemplateLoc, RAngleLoc));
4065 if (Inst.isInvalid())
4068 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4070 // Only substitute for the innermost template argument list.
4071 MultiLevelTemplateArgumentList TemplateArgLists;
4072 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4073 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4074 TemplateArgLists.addOuterTemplateArguments(None);
4076 EnterExpressionEvaluationContext ConstantEvaluated(
4077 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4078 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
4081 /// \brief Substitute template arguments into the default template argument for
4082 /// the given template template parameter.
4084 /// \param SemaRef the semantic analysis object for which we are performing
4085 /// the substitution.
4087 /// \param Template the template that we are synthesizing template arguments
4090 /// \param TemplateLoc the location of the template name that started the
4091 /// template-id we are checking.
4093 /// \param RAngleLoc the location of the right angle bracket ('>') that
4094 /// terminates the template-id.
4096 /// \param Param the template template parameter whose default we are
4097 /// substituting into.
4099 /// \param Converted the list of template arguments provided for template
4100 /// parameters that precede \p Param in the template parameter list.
4102 /// \param QualifierLoc Will be set to the nested-name-specifier (with
4103 /// source-location information) that precedes the template name.
4105 /// \returns the substituted template argument, or NULL if an error occurred.
4107 SubstDefaultTemplateArgument(Sema &SemaRef,
4108 TemplateDecl *Template,
4109 SourceLocation TemplateLoc,
4110 SourceLocation RAngleLoc,
4111 TemplateTemplateParmDecl *Param,
4112 SmallVectorImpl<TemplateArgument> &Converted,
4113 NestedNameSpecifierLoc &QualifierLoc) {
4114 Sema::InstantiatingTemplate Inst(
4115 SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
4116 SourceRange(TemplateLoc, RAngleLoc));
4117 if (Inst.isInvalid())
4118 return TemplateName();
4120 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4122 // Only substitute for the innermost template argument list.
4123 MultiLevelTemplateArgumentList TemplateArgLists;
4124 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4125 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4126 TemplateArgLists.addOuterTemplateArguments(None);
4128 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4129 // Substitute into the nested-name-specifier first,
4130 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
4133 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
4135 return TemplateName();
4138 return SemaRef.SubstTemplateName(
4140 Param->getDefaultArgument().getArgument().getAsTemplate(),
4141 Param->getDefaultArgument().getTemplateNameLoc(),
4145 /// \brief If the given template parameter has a default template
4146 /// argument, substitute into that default template argument and
4147 /// return the corresponding template argument.
4149 Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
4150 SourceLocation TemplateLoc,
4151 SourceLocation RAngleLoc,
4153 SmallVectorImpl<TemplateArgument>
4155 bool &HasDefaultArg) {
4156 HasDefaultArg = false;
4158 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
4159 if (!hasVisibleDefaultArgument(TypeParm))
4160 return TemplateArgumentLoc();
4162 HasDefaultArg = true;
4163 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
4169 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4171 return TemplateArgumentLoc();
4174 if (NonTypeTemplateParmDecl *NonTypeParm
4175 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4176 if (!hasVisibleDefaultArgument(NonTypeParm))
4177 return TemplateArgumentLoc();
4179 HasDefaultArg = true;
4180 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
4185 if (Arg.isInvalid())
4186 return TemplateArgumentLoc();
4188 Expr *ArgE = Arg.getAs<Expr>();
4189 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
4192 TemplateTemplateParmDecl *TempTempParm
4193 = cast<TemplateTemplateParmDecl>(Param);
4194 if (!hasVisibleDefaultArgument(TempTempParm))
4195 return TemplateArgumentLoc();
4197 HasDefaultArg = true;
4198 NestedNameSpecifierLoc QualifierLoc;
4199 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
4206 return TemplateArgumentLoc();
4208 return TemplateArgumentLoc(TemplateArgument(TName),
4209 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
4210 TempTempParm->getDefaultArgument().getTemplateNameLoc());
4213 /// Convert a template-argument that we parsed as a type into a template, if
4214 /// possible. C++ permits injected-class-names to perform dual service as
4215 /// template template arguments and as template type arguments.
4216 static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(TypeLoc TLoc) {
4217 // Extract and step over any surrounding nested-name-specifier.
4218 NestedNameSpecifierLoc QualLoc;
4219 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
4220 if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
4221 return TemplateArgumentLoc();
4223 QualLoc = ETLoc.getQualifierLoc();
4224 TLoc = ETLoc.getNamedTypeLoc();
4227 // If this type was written as an injected-class-name, it can be used as a
4228 // template template argument.
4229 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
4230 return TemplateArgumentLoc(InjLoc.getTypePtr()->getTemplateName(),
4231 QualLoc, InjLoc.getNameLoc());
4233 // If this type was written as an injected-class-name, it may have been
4234 // converted to a RecordType during instantiation. If the RecordType is
4235 // *not* wrapped in a TemplateSpecializationType and denotes a class
4236 // template specialization, it must have come from an injected-class-name.
4237 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
4239 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
4240 return TemplateArgumentLoc(TemplateName(CTSD->getSpecializedTemplate()),
4241 QualLoc, RecLoc.getNameLoc());
4243 return TemplateArgumentLoc();
4246 /// \brief Check that the given template argument corresponds to the given
4247 /// template parameter.
4249 /// \param Param The template parameter against which the argument will be
4252 /// \param Arg The template argument, which may be updated due to conversions.
4254 /// \param Template The template in which the template argument resides.
4256 /// \param TemplateLoc The location of the template name for the template
4257 /// whose argument list we're matching.
4259 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
4260 /// the template argument list.
4262 /// \param ArgumentPackIndex The index into the argument pack where this
4263 /// argument will be placed. Only valid if the parameter is a parameter pack.
4265 /// \param Converted The checked, converted argument will be added to the
4266 /// end of this small vector.
4268 /// \param CTAK Describes how we arrived at this particular template argument:
4269 /// explicitly written, deduced, etc.
4271 /// \returns true on error, false otherwise.
4272 bool Sema::CheckTemplateArgument(NamedDecl *Param,
4273 TemplateArgumentLoc &Arg,
4274 NamedDecl *Template,
4275 SourceLocation TemplateLoc,
4276 SourceLocation RAngleLoc,
4277 unsigned ArgumentPackIndex,
4278 SmallVectorImpl<TemplateArgument> &Converted,
4279 CheckTemplateArgumentKind CTAK) {
4280 // Check template type parameters.
4281 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4282 return CheckTemplateTypeArgument(TTP, Arg, Converted);
4284 // Check non-type template parameters.
4285 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4286 // Do substitution on the type of the non-type template parameter
4287 // with the template arguments we've seen thus far. But if the
4288 // template has a dependent context then we cannot substitute yet.
4289 QualType NTTPType = NTTP->getType();
4290 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
4291 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
4293 if (NTTPType->isDependentType() &&
4294 !isa<TemplateTemplateParmDecl>(Template) &&
4295 !Template->getDeclContext()->isDependentContext()) {
4296 // Do substitution on the type of the non-type template parameter.
4297 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
4299 SourceRange(TemplateLoc, RAngleLoc));
4300 if (Inst.isInvalid())
4303 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
4305 NTTPType = SubstType(NTTPType,
4306 MultiLevelTemplateArgumentList(TemplateArgs),
4307 NTTP->getLocation(),
4308 NTTP->getDeclName());
4309 // If that worked, check the non-type template parameter type
4311 if (!NTTPType.isNull())
4312 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
4313 NTTP->getLocation());
4314 if (NTTPType.isNull())
4318 switch (Arg.getArgument().getKind()) {
4319 case TemplateArgument::Null:
4320 llvm_unreachable("Should never see a NULL template argument here");
4322 case TemplateArgument::Expression: {
4323 TemplateArgument Result;
4325 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
4327 if (Res.isInvalid())
4330 // If the resulting expression is new, then use it in place of the
4331 // old expression in the template argument.
4332 if (Res.get() != Arg.getArgument().getAsExpr()) {
4333 TemplateArgument TA(Res.get());
4334 Arg = TemplateArgumentLoc(TA, Res.get());
4337 Converted.push_back(Result);
4341 case TemplateArgument::Declaration:
4342 case TemplateArgument::Integral:
4343 case TemplateArgument::NullPtr:
4344 // We've already checked this template argument, so just copy
4345 // it to the list of converted arguments.
4346 Converted.push_back(Arg.getArgument());
4349 case TemplateArgument::Template:
4350 case TemplateArgument::TemplateExpansion:
4351 // We were given a template template argument. It may not be ill-formed;
4353 if (DependentTemplateName *DTN
4354 = Arg.getArgument().getAsTemplateOrTemplatePattern()
4355 .getAsDependentTemplateName()) {
4356 // We have a template argument such as \c T::template X, which we
4357 // parsed as a template template argument. However, since we now
4358 // know that we need a non-type template argument, convert this
4359 // template name into an expression.
4361 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
4362 Arg.getTemplateNameLoc());
4365 SS.Adopt(Arg.getTemplateQualifierLoc());
4366 // FIXME: the template-template arg was a DependentTemplateName,
4367 // so it was provided with a template keyword. However, its source
4368 // location is not stored in the template argument structure.
4369 SourceLocation TemplateKWLoc;
4370 ExprResult E = DependentScopeDeclRefExpr::Create(
4371 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
4374 // If we parsed the template argument as a pack expansion, create a
4375 // pack expansion expression.
4376 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
4377 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
4382 TemplateArgument Result;
4383 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
4387 Converted.push_back(Result);
4391 // We have a template argument that actually does refer to a class
4392 // template, alias template, or template template parameter, and
4393 // therefore cannot be a non-type template argument.
4394 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
4395 << Arg.getSourceRange();
4397 Diag(Param->getLocation(), diag::note_template_param_here);
4400 case TemplateArgument::Type: {
4401 // We have a non-type template parameter but the template
4402 // argument is a type.
4404 // C++ [temp.arg]p2:
4405 // In a template-argument, an ambiguity between a type-id and
4406 // an expression is resolved to a type-id, regardless of the
4407 // form of the corresponding template-parameter.
4409 // We warn specifically about this case, since it can be rather
4410 // confusing for users.
4411 QualType T = Arg.getArgument().getAsType();
4412 SourceRange SR = Arg.getSourceRange();
4413 if (T->isFunctionType())
4414 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
4416 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
4417 Diag(Param->getLocation(), diag::note_template_param_here);
4421 case TemplateArgument::Pack:
4422 llvm_unreachable("Caller must expand template argument packs");
4429 // Check template template parameters.
4430 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
4432 // Substitute into the template parameter list of the template
4433 // template parameter, since previously-supplied template arguments
4434 // may appear within the template template parameter.
4436 // Set up a template instantiation context.
4437 LocalInstantiationScope Scope(*this);
4438 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
4439 TempParm, Converted,
4440 SourceRange(TemplateLoc, RAngleLoc));
4441 if (Inst.isInvalid())
4444 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4445 TempParm = cast_or_null<TemplateTemplateParmDecl>(
4446 SubstDecl(TempParm, CurContext,
4447 MultiLevelTemplateArgumentList(TemplateArgs)));
4452 // C++1z [temp.local]p1: (DR1004)
4453 // When [the injected-class-name] is used [...] as a template-argument for
4454 // a template template-parameter [...] it refers to the class template
4456 if (Arg.getArgument().getKind() == TemplateArgument::Type) {
4457 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
4458 Arg.getTypeSourceInfo()->getTypeLoc());
4459 if (!ConvertedArg.getArgument().isNull())
4463 switch (Arg.getArgument().getKind()) {
4464 case TemplateArgument::Null:
4465 llvm_unreachable("Should never see a NULL template argument here");
4467 case TemplateArgument::Template:
4468 case TemplateArgument::TemplateExpansion:
4469 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
4472 Converted.push_back(Arg.getArgument());
4475 case TemplateArgument::Expression:
4476 case TemplateArgument::Type:
4477 // We have a template template parameter but the template
4478 // argument does not refer to a template.
4479 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
4480 << getLangOpts().CPlusPlus11;
4483 case TemplateArgument::Declaration:
4484 llvm_unreachable("Declaration argument with template template parameter");
4485 case TemplateArgument::Integral:
4486 llvm_unreachable("Integral argument with template template parameter");
4487 case TemplateArgument::NullPtr:
4488 llvm_unreachable("Null pointer argument with template template parameter");
4490 case TemplateArgument::Pack:
4491 llvm_unreachable("Caller must expand template argument packs");
4497 /// \brief Diagnose an arity mismatch in the
4498 static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
4499 SourceLocation TemplateLoc,
4500 TemplateArgumentListInfo &TemplateArgs) {
4501 TemplateParameterList *Params = Template->getTemplateParameters();
4502 unsigned NumParams = Params->size();
4503 unsigned NumArgs = TemplateArgs.size();
4506 if (NumArgs > NumParams)
4507 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
4508 TemplateArgs.getRAngleLoc());
4509 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
4510 << (NumArgs > NumParams)
4511 << (int)S.getTemplateNameKindForDiagnostics(TemplateName(Template))
4512 << Template << Range;
4513 S.Diag(Template->getLocation(), diag::note_template_decl_here)
4514 << Params->getSourceRange();
4518 /// \brief Check whether the template parameter is a pack expansion, and if so,
4519 /// determine the number of parameters produced by that expansion. For instance:
4522 /// template<typename ...Ts> struct A {
4523 /// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
4527 /// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
4528 /// is not a pack expansion, so returns an empty Optional.
4529 static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
4530 if (NonTypeTemplateParmDecl *NTTP
4531 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4532 if (NTTP->isExpandedParameterPack())
4533 return NTTP->getNumExpansionTypes();
4536 if (TemplateTemplateParmDecl *TTP
4537 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
4538 if (TTP->isExpandedParameterPack())
4539 return TTP->getNumExpansionTemplateParameters();
4545 /// Diagnose a missing template argument.
4546 template<typename TemplateParmDecl>
4547 static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
4549 const TemplateParmDecl *D,
4550 TemplateArgumentListInfo &Args) {
4551 // Dig out the most recent declaration of the template parameter; there may be
4552 // declarations of the template that are more recent than TD.
4553 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
4554 ->getTemplateParameters()
4555 ->getParam(D->getIndex()));
4557 // If there's a default argument that's not visible, diagnose that we're
4558 // missing a module import.
4559 llvm::SmallVector<Module*, 8> Modules;
4560 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
4561 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
4562 D->getDefaultArgumentLoc(), Modules,
4563 Sema::MissingImportKind::DefaultArgument,
4568 // FIXME: If there's a more recent default argument that *is* visible,
4569 // diagnose that it was declared too late.
4571 return diagnoseArityMismatch(S, TD, Loc, Args);
4574 /// \brief Check that the given template argument list is well-formed
4575 /// for specializing the given template.
4576 bool Sema::CheckTemplateArgumentList(
4577 TemplateDecl *Template, SourceLocation TemplateLoc,
4578 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
4579 SmallVectorImpl<TemplateArgument> &Converted,
4580 bool UpdateArgsWithConversions) {
4581 // Make a copy of the template arguments for processing. Only make the
4582 // changes at the end when successful in matching the arguments to the
4584 TemplateArgumentListInfo NewArgs = TemplateArgs;
4586 TemplateParameterList *Params = Template->getTemplateParameters();
4588 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
4590 // C++ [temp.arg]p1:
4591 // [...] The type and form of each template-argument specified in
4592 // a template-id shall match the type and form specified for the
4593 // corresponding parameter declared by the template in its
4594 // template-parameter-list.
4595 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
4596 SmallVector<TemplateArgument, 2> ArgumentPack;
4597 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
4598 LocalInstantiationScope InstScope(*this, true);
4599 for (TemplateParameterList::iterator Param = Params->begin(),
4600 ParamEnd = Params->end();
4601 Param != ParamEnd; /* increment in loop */) {
4602 // If we have an expanded parameter pack, make sure we don't have too
4604 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
4605 if (*Expansions == ArgumentPack.size()) {
4606 // We're done with this parameter pack. Pack up its arguments and add
4607 // them to the list.
4608 Converted.push_back(
4609 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4610 ArgumentPack.clear();
4612 // This argument is assigned to the next parameter.
4615 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
4616 // Not enough arguments for this parameter pack.
4617 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
4619 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
4621 Diag(Template->getLocation(), diag::note_template_decl_here)
4622 << Params->getSourceRange();
4627 if (ArgIdx < NumArgs) {
4628 // Check the template argument we were given.
4629 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
4630 TemplateLoc, RAngleLoc,
4631 ArgumentPack.size(), Converted))
4634 bool PackExpansionIntoNonPack =
4635 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
4636 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
4637 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
4638 // Core issue 1430: we have a pack expansion as an argument to an
4639 // alias template, and it's not part of a parameter pack. This
4640 // can't be canonicalized, so reject it now.
4641 Diag(NewArgs[ArgIdx].getLocation(),
4642 diag::err_alias_template_expansion_into_fixed_list)
4643 << NewArgs[ArgIdx].getSourceRange();
4644 Diag((*Param)->getLocation(), diag::note_template_param_here);
4648 // We're now done with this argument.
4651 if ((*Param)->isTemplateParameterPack()) {
4652 // The template parameter was a template parameter pack, so take the
4653 // deduced argument and place it on the argument pack. Note that we
4654 // stay on the same template parameter so that we can deduce more
4656 ArgumentPack.push_back(Converted.pop_back_val());
4658 // Move to the next template parameter.
4662 // If we just saw a pack expansion into a non-pack, then directly convert
4663 // the remaining arguments, because we don't know what parameters they'll
4665 if (PackExpansionIntoNonPack) {
4666 if (!ArgumentPack.empty()) {
4667 // If we were part way through filling in an expanded parameter pack,
4668 // fall back to just producing individual arguments.
4669 Converted.insert(Converted.end(),
4670 ArgumentPack.begin(), ArgumentPack.end());
4671 ArgumentPack.clear();
4674 while (ArgIdx < NumArgs) {
4675 Converted.push_back(NewArgs[ArgIdx].getArgument());
4685 // If we're checking a partial template argument list, we're done.
4686 if (PartialTemplateArgs) {
4687 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
4688 Converted.push_back(
4689 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4694 // If we have a template parameter pack with no more corresponding
4695 // arguments, just break out now and we'll fill in the argument pack below.
4696 if ((*Param)->isTemplateParameterPack()) {
4697 assert(!getExpandedPackSize(*Param) &&
4698 "Should have dealt with this already");
4700 // A non-expanded parameter pack before the end of the parameter list
4701 // only occurs for an ill-formed template parameter list, unless we've
4702 // got a partial argument list for a function template, so just bail out.
4703 if (Param + 1 != ParamEnd)
4706 Converted.push_back(
4707 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4708 ArgumentPack.clear();
4714 // Check whether we have a default argument.
4715 TemplateArgumentLoc Arg;
4717 // Retrieve the default template argument from the template
4718 // parameter. For each kind of template parameter, we substitute the
4719 // template arguments provided thus far and any "outer" template arguments
4720 // (when the template parameter was part of a nested template) into
4721 // the default argument.
4722 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
4723 if (!hasVisibleDefaultArgument(TTP))
4724 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
4727 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
4736 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
4738 } else if (NonTypeTemplateParmDecl *NTTP
4739 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
4740 if (!hasVisibleDefaultArgument(NTTP))
4741 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
4744 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
4752 Expr *Ex = E.getAs<Expr>();
4753 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
4755 TemplateTemplateParmDecl *TempParm
4756 = cast<TemplateTemplateParmDecl>(*Param);
4758 if (!hasVisibleDefaultArgument(TempParm))
4759 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
4762 NestedNameSpecifierLoc QualifierLoc;
4763 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
4772 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
4773 TempParm->getDefaultArgument().getTemplateNameLoc());
4776 // Introduce an instantiation record that describes where we are using
4777 // the default template argument. We're not actually instantiating a
4778 // template here, we just create this object to put a note into the
4780 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
4781 SourceRange(TemplateLoc, RAngleLoc));
4782 if (Inst.isInvalid())
4785 // Check the default template argument.
4786 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
4787 RAngleLoc, 0, Converted))
4790 // Core issue 150 (assumed resolution): if this is a template template
4791 // parameter, keep track of the default template arguments from the
4792 // template definition.
4793 if (isTemplateTemplateParameter)
4794 NewArgs.addArgument(Arg);
4796 // Move to the next template parameter and argument.
4801 // If we're performing a partial argument substitution, allow any trailing
4802 // pack expansions; they might be empty. This can happen even if
4803 // PartialTemplateArgs is false (the list of arguments is complete but
4804 // still dependent).
4805 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
4806 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
4807 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
4808 Converted.push_back(NewArgs[ArgIdx++].getArgument());
4811 // If we have any leftover arguments, then there were too many arguments.
4812 // Complain and fail.
4813 if (ArgIdx < NumArgs)
4814 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
4816 // No problems found with the new argument list, propagate changes back
4818 if (UpdateArgsWithConversions)
4819 TemplateArgs = std::move(NewArgs);
4825 class UnnamedLocalNoLinkageFinder
4826 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
4831 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
4834 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
4836 bool Visit(QualType T) {
4837 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
4840 #define TYPE(Class, Parent) \
4841 bool Visit##Class##Type(const Class##Type *);
4842 #define ABSTRACT_TYPE(Class, Parent) \
4843 bool Visit##Class##Type(const Class##Type *) { return false; }
4844 #define NON_CANONICAL_TYPE(Class, Parent) \
4845 bool Visit##Class##Type(const Class##Type *) { return false; }
4846 #include "clang/AST/TypeNodes.def"
4848 bool VisitTagDecl(const TagDecl *Tag);
4849 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
4851 } // end anonymous namespace
4853 bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
4857 bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
4858 return Visit(T->getElementType());
4861 bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
4862 return Visit(T->getPointeeType());
4865 bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
4866 const BlockPointerType* T) {
4867 return Visit(T->getPointeeType());
4870 bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
4871 const LValueReferenceType* T) {
4872 return Visit(T->getPointeeType());
4875 bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
4876 const RValueReferenceType* T) {
4877 return Visit(T->getPointeeType());
4880 bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
4881 const MemberPointerType* T) {
4882 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
4885 bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
4886 const ConstantArrayType* T) {
4887 return Visit(T->getElementType());
4890 bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
4891 const IncompleteArrayType* T) {
4892 return Visit(T->getElementType());
4895 bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
4896 const VariableArrayType* T) {
4897 return Visit(T->getElementType());
4900 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
4901 const DependentSizedArrayType* T) {
4902 return Visit(T->getElementType());
4905 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
4906 const DependentSizedExtVectorType* T) {
4907 return Visit(T->getElementType());
4910 bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
4911 return Visit(T->getElementType());
4914 bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
4915 return Visit(T->getElementType());
4918 bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
4919 const FunctionProtoType* T) {
4920 for (const auto &A : T->param_types()) {
4925 return Visit(T->getReturnType());
4928 bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
4929 const FunctionNoProtoType* T) {
4930 return Visit(T->getReturnType());
4933 bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
4934 const UnresolvedUsingType*) {
4938 bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
4942 bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
4943 return Visit(T->getUnderlyingType());
4946 bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
4950 bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
4951 const UnaryTransformType*) {
4955 bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
4956 return Visit(T->getDeducedType());
4959 bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
4960 const DeducedTemplateSpecializationType *T) {
4961 return Visit(T->getDeducedType());
4964 bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
4965 return VisitTagDecl(T->getDecl());
4968 bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
4969 return VisitTagDecl(T->getDecl());
4972 bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
4973 const TemplateTypeParmType*) {
4977 bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
4978 const SubstTemplateTypeParmPackType *) {
4982 bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
4983 const TemplateSpecializationType*) {
4987 bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
4988 const InjectedClassNameType* T) {
4989 return VisitTagDecl(T->getDecl());
4992 bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
4993 const DependentNameType* T) {
4994 return VisitNestedNameSpecifier(T->getQualifier());
4997 bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
4998 const DependentTemplateSpecializationType* T) {
4999 return VisitNestedNameSpecifier(T->getQualifier());
5002 bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
5003 const PackExpansionType* T) {
5004 return Visit(T->getPattern());
5007 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
5011 bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
5012 const ObjCInterfaceType *) {
5016 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
5017 const ObjCObjectPointerType *) {
5021 bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
5022 return Visit(T->getValueType());
5025 bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
5029 bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
5030 if (Tag->getDeclContext()->isFunctionOrMethod()) {
5031 S.Diag(SR.getBegin(),
5032 S.getLangOpts().CPlusPlus11 ?
5033 diag::warn_cxx98_compat_template_arg_local_type :
5034 diag::ext_template_arg_local_type)
5035 << S.Context.getTypeDeclType(Tag) << SR;
5039 if (!Tag->hasNameForLinkage()) {
5040 S.Diag(SR.getBegin(),
5041 S.getLangOpts().CPlusPlus11 ?
5042 diag::warn_cxx98_compat_template_arg_unnamed_type :
5043 diag::ext_template_arg_unnamed_type) << SR;
5044 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
5051 bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
5052 NestedNameSpecifier *NNS) {
5053 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
5056 switch (NNS->getKind()) {
5057 case NestedNameSpecifier::Identifier:
5058 case NestedNameSpecifier::Namespace:
5059 case NestedNameSpecifier::NamespaceAlias:
5060 case NestedNameSpecifier::Global:
5061 case NestedNameSpecifier::Super:
5064 case NestedNameSpecifier::TypeSpec:
5065 case NestedNameSpecifier::TypeSpecWithTemplate:
5066 return Visit(QualType(NNS->getAsType(), 0));
5068 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
5071 /// \brief Check a template argument against its corresponding
5072 /// template type parameter.
5074 /// This routine implements the semantics of C++ [temp.arg.type]. It
5075 /// returns true if an error occurred, and false otherwise.
5076 bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
5077 TypeSourceInfo *ArgInfo) {
5078 assert(ArgInfo && "invalid TypeSourceInfo");
5079 QualType Arg = ArgInfo->getType();
5080 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
5082 if (Arg->isVariablyModifiedType()) {
5083 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
5084 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
5085 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
5088 // C++03 [temp.arg.type]p2:
5089 // A local type, a type with no linkage, an unnamed type or a type
5090 // compounded from any of these types shall not be used as a
5091 // template-argument for a template type-parameter.
5093 // C++11 allows these, and even in C++03 we allow them as an extension with
5095 if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) {
5096 UnnamedLocalNoLinkageFinder Finder(*this, SR);
5097 (void)Finder.Visit(Context.getCanonicalType(Arg));
5103 enum NullPointerValueKind {
5109 /// \brief Determine whether the given template argument is a null pointer
5110 /// value of the appropriate type.
5111 static NullPointerValueKind
5112 isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
5113 QualType ParamType, Expr *Arg) {
5114 if (Arg->isValueDependent() || Arg->isTypeDependent())
5115 return NPV_NotNullPointer;
5117 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
5119 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
5121 if (!S.getLangOpts().CPlusPlus11)
5122 return NPV_NotNullPointer;
5124 // Determine whether we have a constant expression.
5125 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
5126 if (ArgRV.isInvalid())
5130 Expr::EvalResult EvalResult;
5131 SmallVector<PartialDiagnosticAt, 8> Notes;
5132 EvalResult.Diag = &Notes;
5133 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
5134 EvalResult.HasSideEffects) {
5135 SourceLocation DiagLoc = Arg->getExprLoc();
5137 // If our only note is the usual "invalid subexpression" note, just point
5138 // the caret at its location rather than producing an essentially
5140 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
5141 diag::note_invalid_subexpr_in_const_expr) {
5142 DiagLoc = Notes[0].first;
5146 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
5147 << Arg->getType() << Arg->getSourceRange();
5148 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
5149 S.Diag(Notes[I].first, Notes[I].second);
5151 S.Diag(Param->getLocation(), diag::note_template_param_here);
5155 // C++11 [temp.arg.nontype]p1:
5156 // - an address constant expression of type std::nullptr_t
5157 if (Arg->getType()->isNullPtrType())
5158 return NPV_NullPointer;
5160 // - a constant expression that evaluates to a null pointer value (4.10); or
5161 // - a constant expression that evaluates to a null member pointer value
5163 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
5164 (EvalResult.Val.isMemberPointer() &&
5165 !EvalResult.Val.getMemberPointerDecl())) {
5166 // If our expression has an appropriate type, we've succeeded.
5167 bool ObjCLifetimeConversion;
5168 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
5169 S.IsQualificationConversion(Arg->getType(), ParamType, false,
5170 ObjCLifetimeConversion))
5171 return NPV_NullPointer;
5173 // The types didn't match, but we know we got a null pointer; complain,
5174 // then recover as if the types were correct.
5175 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
5176 << Arg->getType() << ParamType << Arg->getSourceRange();
5177 S.Diag(Param->getLocation(), diag::note_template_param_here);
5178 return NPV_NullPointer;
5181 // If we don't have a null pointer value, but we do have a NULL pointer
5182 // constant, suggest a cast to the appropriate type.
5183 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
5184 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
5185 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
5186 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
5187 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
5189 S.Diag(Param->getLocation(), diag::note_template_param_here);
5190 return NPV_NullPointer;
5193 // FIXME: If we ever want to support general, address-constant expressions
5194 // as non-type template arguments, we should return the ExprResult here to
5195 // be interpreted by the caller.
5196 return NPV_NotNullPointer;
5199 /// \brief Checks whether the given template argument is compatible with its
5200 /// template parameter.
5201 static bool CheckTemplateArgumentIsCompatibleWithParameter(
5202 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
5203 Expr *Arg, QualType ArgType) {
5204 bool ObjCLifetimeConversion;
5205 if (ParamType->isPointerType() &&
5206 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
5207 S.IsQualificationConversion(ArgType, ParamType, false,
5208 ObjCLifetimeConversion)) {
5209 // For pointer-to-object types, qualification conversions are
5212 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
5213 if (!ParamRef->getPointeeType()->isFunctionType()) {
5214 // C++ [temp.arg.nontype]p5b3:
5215 // For a non-type template-parameter of type reference to
5216 // object, no conversions apply. The type referred to by the
5217 // reference may be more cv-qualified than the (otherwise
5218 // identical) type of the template- argument. The
5219 // template-parameter is bound directly to the
5220 // template-argument, which shall be an lvalue.
5222 // FIXME: Other qualifiers?
5223 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
5224 unsigned ArgQuals = ArgType.getCVRQualifiers();
5226 if ((ParamQuals | ArgQuals) != ParamQuals) {
5227 S.Diag(Arg->getLocStart(),
5228 diag::err_template_arg_ref_bind_ignores_quals)
5229 << ParamType << Arg->getType() << Arg->getSourceRange();
5230 S.Diag(Param->getLocation(), diag::note_template_param_here);
5236 // At this point, the template argument refers to an object or
5237 // function with external linkage. We now need to check whether the
5238 // argument and parameter types are compatible.
5239 if (!S.Context.hasSameUnqualifiedType(ArgType,
5240 ParamType.getNonReferenceType())) {
5241 // We can't perform this conversion or binding.
5242 if (ParamType->isReferenceType())
5243 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
5244 << ParamType << ArgIn->getType() << Arg->getSourceRange();
5246 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
5247 << ArgIn->getType() << ParamType << Arg->getSourceRange();
5248 S.Diag(Param->getLocation(), diag::note_template_param_here);
5256 /// \brief Checks whether the given template argument is the address
5257 /// of an object or function according to C++ [temp.arg.nontype]p1.
5259 CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
5260 NonTypeTemplateParmDecl *Param,
5263 TemplateArgument &Converted) {
5264 bool Invalid = false;
5266 QualType ArgType = Arg->getType();
5268 bool AddressTaken = false;
5269 SourceLocation AddrOpLoc;
5270 if (S.getLangOpts().MicrosoftExt) {
5271 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
5272 // dereference and address-of operators.
5273 Arg = Arg->IgnoreParenCasts();
5275 bool ExtWarnMSTemplateArg = false;
5276 UnaryOperatorKind FirstOpKind;
5277 SourceLocation FirstOpLoc;
5278 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5279 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
5280 if (UnOpKind == UO_Deref)
5281 ExtWarnMSTemplateArg = true;
5282 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
5283 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
5284 if (!AddrOpLoc.isValid()) {
5285 FirstOpKind = UnOpKind;
5286 FirstOpLoc = UnOp->getOperatorLoc();
5291 if (FirstOpLoc.isValid()) {
5292 if (ExtWarnMSTemplateArg)
5293 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
5294 << ArgIn->getSourceRange();
5296 if (FirstOpKind == UO_AddrOf)
5297 AddressTaken = true;
5298 else if (Arg->getType()->isPointerType()) {
5299 // We cannot let pointers get dereferenced here, that is obviously not a
5300 // constant expression.
5301 assert(FirstOpKind == UO_Deref);
5302 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5303 << Arg->getSourceRange();
5307 // See through any implicit casts we added to fix the type.
5308 Arg = Arg->IgnoreImpCasts();
5310 // C++ [temp.arg.nontype]p1:
5312 // A template-argument for a non-type, non-template
5313 // template-parameter shall be one of: [...]
5315 // -- the address of an object or function with external
5316 // linkage, including function templates and function
5317 // template-ids but excluding non-static class members,
5318 // expressed as & id-expression where the & is optional if
5319 // the name refers to a function or array, or if the
5320 // corresponding template-parameter is a reference; or
5322 // In C++98/03 mode, give an extension warning on any extra parentheses.
5323 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5324 bool ExtraParens = false;
5325 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
5326 if (!Invalid && !ExtraParens) {
5327 S.Diag(Arg->getLocStart(),
5328 S.getLangOpts().CPlusPlus11
5329 ? diag::warn_cxx98_compat_template_arg_extra_parens
5330 : diag::ext_template_arg_extra_parens)
5331 << Arg->getSourceRange();
5335 Arg = Parens->getSubExpr();
5338 while (SubstNonTypeTemplateParmExpr *subst =
5339 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5340 Arg = subst->getReplacement()->IgnoreImpCasts();
5342 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5343 if (UnOp->getOpcode() == UO_AddrOf) {
5344 Arg = UnOp->getSubExpr();
5345 AddressTaken = true;
5346 AddrOpLoc = UnOp->getOperatorLoc();
5350 while (SubstNonTypeTemplateParmExpr *subst =
5351 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5352 Arg = subst->getReplacement()->IgnoreImpCasts();
5355 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
5356 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
5358 // If our parameter has pointer type, check for a null template value.
5359 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
5360 NullPointerValueKind NPV;
5361 // dllimport'd entities aren't constant but are available inside of template
5363 if (Entity && Entity->hasAttr<DLLImportAttr>())
5364 NPV = NPV_NotNullPointer;
5366 NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
5368 case NPV_NullPointer:
5369 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
5370 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5371 /*isNullPtr=*/true);
5377 case NPV_NotNullPointer:
5382 // Stop checking the precise nature of the argument if it is value dependent,
5383 // it should be checked when instantiated.
5384 if (Arg->isValueDependent()) {
5385 Converted = TemplateArgument(ArgIn);
5389 if (isa<CXXUuidofExpr>(Arg)) {
5390 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
5391 ArgIn, Arg, ArgType))
5394 Converted = TemplateArgument(ArgIn);
5399 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5400 << Arg->getSourceRange();
5401 S.Diag(Param->getLocation(), diag::note_template_param_here);
5405 // Cannot refer to non-static data members
5406 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
5407 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
5408 << Entity << Arg->getSourceRange();
5409 S.Diag(Param->getLocation(), diag::note_template_param_here);
5413 // Cannot refer to non-static member functions
5414 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
5415 if (!Method->isStatic()) {
5416 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
5417 << Method << Arg->getSourceRange();
5418 S.Diag(Param->getLocation(), diag::note_template_param_here);
5423 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
5424 VarDecl *Var = dyn_cast<VarDecl>(Entity);
5426 // A non-type template argument must refer to an object or function.
5427 if (!Func && !Var) {
5428 // We found something, but we don't know specifically what it is.
5429 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
5430 << Arg->getSourceRange();
5431 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
5435 // Address / reference template args must have external linkage in C++98.
5436 if (Entity->getFormalLinkage() == InternalLinkage) {
5437 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
5438 diag::warn_cxx98_compat_template_arg_object_internal :
5439 diag::ext_template_arg_object_internal)
5440 << !Func << Entity << Arg->getSourceRange();
5441 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5443 } else if (!Entity->hasLinkage()) {
5444 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
5445 << !Func << Entity << Arg->getSourceRange();
5446 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5452 // If the template parameter has pointer type, the function decays.
5453 if (ParamType->isPointerType() && !AddressTaken)
5454 ArgType = S.Context.getPointerType(Func->getType());
5455 else if (AddressTaken && ParamType->isReferenceType()) {
5456 // If we originally had an address-of operator, but the
5457 // parameter has reference type, complain and (if things look
5458 // like they will work) drop the address-of operator.
5459 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
5460 ParamType.getNonReferenceType())) {
5461 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5463 S.Diag(Param->getLocation(), diag::note_template_param_here);
5467 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5469 << FixItHint::CreateRemoval(AddrOpLoc);
5470 S.Diag(Param->getLocation(), diag::note_template_param_here);
5472 ArgType = Func->getType();
5475 // A value of reference type is not an object.
5476 if (Var->getType()->isReferenceType()) {
5477 S.Diag(Arg->getLocStart(),
5478 diag::err_template_arg_reference_var)
5479 << Var->getType() << Arg->getSourceRange();
5480 S.Diag(Param->getLocation(), diag::note_template_param_here);
5484 // A template argument must have static storage duration.
5485 if (Var->getTLSKind()) {
5486 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
5487 << Arg->getSourceRange();
5488 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
5492 // If the template parameter has pointer type, we must have taken
5493 // the address of this object.
5494 if (ParamType->isReferenceType()) {
5496 // If we originally had an address-of operator, but the
5497 // parameter has reference type, complain and (if things look
5498 // like they will work) drop the address-of operator.
5499 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
5500 ParamType.getNonReferenceType())) {
5501 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5503 S.Diag(Param->getLocation(), diag::note_template_param_here);
5507 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5509 << FixItHint::CreateRemoval(AddrOpLoc);
5510 S.Diag(Param->getLocation(), diag::note_template_param_here);
5512 ArgType = Var->getType();
5514 } else if (!AddressTaken && ParamType->isPointerType()) {
5515 if (Var->getType()->isArrayType()) {
5516 // Array-to-pointer decay.
5517 ArgType = S.Context.getArrayDecayedType(Var->getType());
5519 // If the template parameter has pointer type but the address of
5520 // this object was not taken, complain and (possibly) recover by
5521 // taking the address of the entity.
5522 ArgType = S.Context.getPointerType(Var->getType());
5523 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
5524 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
5526 S.Diag(Param->getLocation(), diag::note_template_param_here);
5530 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
5532 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
5534 S.Diag(Param->getLocation(), diag::note_template_param_here);
5539 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
5543 // Create the template argument.
5545 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
5546 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
5550 /// \brief Checks whether the given template argument is a pointer to
5551 /// member constant according to C++ [temp.arg.nontype]p1.
5552 static bool CheckTemplateArgumentPointerToMember(Sema &S,
5553 NonTypeTemplateParmDecl *Param,
5556 TemplateArgument &Converted) {
5557 bool Invalid = false;
5559 // Check for a null pointer value.
5560 Expr *Arg = ResultArg;
5561 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
5564 case NPV_NullPointer:
5565 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
5566 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5569 case NPV_NotNullPointer:
5573 bool ObjCLifetimeConversion;
5574 if (S.IsQualificationConversion(Arg->getType(),
5575 ParamType.getNonReferenceType(),
5576 false, ObjCLifetimeConversion)) {
5577 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
5578 Arg->getValueKind()).get();
5580 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
5581 ParamType.getNonReferenceType())) {
5582 // We can't perform this conversion.
5583 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
5584 << Arg->getType() << ParamType << Arg->getSourceRange();
5585 S.Diag(Param->getLocation(), diag::note_template_param_here);
5589 // See through any implicit casts we added to fix the type.
5590 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
5591 Arg = Cast->getSubExpr();
5593 // C++ [temp.arg.nontype]p1:
5595 // A template-argument for a non-type, non-template
5596 // template-parameter shall be one of: [...]
5598 // -- a pointer to member expressed as described in 5.3.1.
5599 DeclRefExpr *DRE = nullptr;
5601 // In C++98/03 mode, give an extension warning on any extra parentheses.
5602 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5603 bool ExtraParens = false;
5604 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
5605 if (!Invalid && !ExtraParens) {
5606 S.Diag(Arg->getLocStart(),
5607 S.getLangOpts().CPlusPlus11 ?
5608 diag::warn_cxx98_compat_template_arg_extra_parens :
5609 diag::ext_template_arg_extra_parens)
5610 << Arg->getSourceRange();
5614 Arg = Parens->getSubExpr();
5617 while (SubstNonTypeTemplateParmExpr *subst =
5618 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5619 Arg = subst->getReplacement()->IgnoreImpCasts();
5621 // A pointer-to-member constant written &Class::member.
5622 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5623 if (UnOp->getOpcode() == UO_AddrOf) {
5624 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
5625 if (DRE && !DRE->getQualifier())
5629 // A constant of pointer-to-member type.
5630 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
5631 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
5632 if (VD->getType()->isMemberPointerType()) {
5633 if (isa<NonTypeTemplateParmDecl>(VD)) {
5634 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5635 Converted = TemplateArgument(Arg);
5637 VD = cast<ValueDecl>(VD->getCanonicalDecl());
5638 Converted = TemplateArgument(VD, ParamType);
5649 return S.Diag(Arg->getLocStart(),
5650 diag::err_template_arg_not_pointer_to_member_form)
5651 << Arg->getSourceRange();
5653 if (isa<FieldDecl>(DRE->getDecl()) ||
5654 isa<IndirectFieldDecl>(DRE->getDecl()) ||
5655 isa<CXXMethodDecl>(DRE->getDecl())) {
5656 assert((isa<FieldDecl>(DRE->getDecl()) ||
5657 isa<IndirectFieldDecl>(DRE->getDecl()) ||
5658 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
5659 "Only non-static member pointers can make it here");
5661 // Okay: this is the address of a non-static member, and therefore
5662 // a member pointer constant.
5663 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5664 Converted = TemplateArgument(Arg);
5666 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
5667 Converted = TemplateArgument(D, ParamType);
5672 // We found something else, but we don't know specifically what it is.
5673 S.Diag(Arg->getLocStart(),
5674 diag::err_template_arg_not_pointer_to_member_form)
5675 << Arg->getSourceRange();
5676 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
5680 /// \brief Check a template argument against its corresponding
5681 /// non-type template parameter.
5683 /// This routine implements the semantics of C++ [temp.arg.nontype].
5684 /// If an error occurred, it returns ExprError(); otherwise, it
5685 /// returns the converted template argument. \p ParamType is the
5686 /// type of the non-type template parameter after it has been instantiated.
5687 ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
5688 QualType ParamType, Expr *Arg,
5689 TemplateArgument &Converted,
5690 CheckTemplateArgumentKind CTAK) {
5691 SourceLocation StartLoc = Arg->getLocStart();
5693 // If the parameter type somehow involves auto, deduce the type now.
5694 if (getLangOpts().CPlusPlus1z && ParamType->isUndeducedType()) {
5695 // During template argument deduction, we allow 'decltype(auto)' to
5696 // match an arbitrary dependent argument.
5697 // FIXME: The language rules don't say what happens in this case.
5698 // FIXME: We get an opaque dependent type out of decltype(auto) if the
5699 // expression is merely instantiation-dependent; is this enough?
5700 if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) {
5701 auto *AT = dyn_cast<AutoType>(ParamType);
5702 if (AT && AT->isDecltypeAuto()) {
5703 Converted = TemplateArgument(Arg);
5708 // When checking a deduced template argument, deduce from its type even if
5709 // the type is dependent, in order to check the types of non-type template
5710 // arguments line up properly in partial ordering.
5711 Optional<unsigned> Depth;
5712 if (CTAK != CTAK_Specified)
5713 Depth = Param->getDepth() + 1;
5715 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()),
5716 Arg, ParamType, Depth) == DAR_Failed) {
5717 Diag(Arg->getExprLoc(),
5718 diag::err_non_type_template_parm_type_deduction_failure)
5719 << Param->getDeclName() << Param->getType() << Arg->getType()
5720 << Arg->getSourceRange();
5721 Diag(Param->getLocation(), diag::note_template_param_here);
5724 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
5725 // an error. The error message normally references the parameter
5726 // declaration, but here we'll pass the argument location because that's
5727 // where the parameter type is deduced.
5728 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
5729 if (ParamType.isNull()) {
5730 Diag(Param->getLocation(), diag::note_template_param_here);
5735 // We should have already dropped all cv-qualifiers by now.
5736 assert(!ParamType.hasQualifiers() &&
5737 "non-type template parameter type cannot be qualified");
5739 if (CTAK == CTAK_Deduced &&
5740 !Context.hasSameType(ParamType.getNonLValueExprType(Context),
5742 // FIXME: If either type is dependent, we skip the check. This isn't
5743 // correct, since during deduction we're supposed to have replaced each
5744 // template parameter with some unique (non-dependent) placeholder.
5745 // FIXME: If the argument type contains 'auto', we carry on and fail the
5746 // type check in order to force specific types to be more specialized than
5747 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
5749 if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
5750 !Arg->getType()->getContainedAutoType()) {
5751 Converted = TemplateArgument(Arg);
5754 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
5755 // we should actually be checking the type of the template argument in P,
5756 // not the type of the template argument deduced from A, against the
5757 // template parameter type.
5758 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
5760 << ParamType.getUnqualifiedType();
5761 Diag(Param->getLocation(), diag::note_template_param_here);
5765 // If either the parameter has a dependent type or the argument is
5766 // type-dependent, there's nothing we can check now.
5767 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
5768 // FIXME: Produce a cloned, canonical expression?
5769 Converted = TemplateArgument(Arg);
5773 // The initialization of the parameter from the argument is
5774 // a constant-evaluated context.
5775 EnterExpressionEvaluationContext ConstantEvaluated(
5776 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5778 if (getLangOpts().CPlusPlus1z) {
5779 // C++1z [temp.arg.nontype]p1:
5780 // A template-argument for a non-type template parameter shall be
5781 // a converted constant expression of the type of the template-parameter.
5783 ExprResult ArgResult = CheckConvertedConstantExpression(
5784 Arg, ParamType, Value, CCEK_TemplateArg);
5785 if (ArgResult.isInvalid())
5788 // For a value-dependent argument, CheckConvertedConstantExpression is
5789 // permitted (and expected) to be unable to determine a value.
5790 if (ArgResult.get()->isValueDependent()) {
5791 Converted = TemplateArgument(ArgResult.get());
5795 QualType CanonParamType = Context.getCanonicalType(ParamType);
5797 // Convert the APValue to a TemplateArgument.
5798 switch (Value.getKind()) {
5799 case APValue::Uninitialized:
5800 assert(ParamType->isNullPtrType());
5801 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
5804 assert(ParamType->isIntegralOrEnumerationType());
5805 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
5807 case APValue::MemberPointer: {
5808 assert(ParamType->isMemberPointerType());
5810 // FIXME: We need TemplateArgument representation and mangling for these.
5811 if (!Value.getMemberPointerPath().empty()) {
5812 Diag(Arg->getLocStart(),
5813 diag::err_template_arg_member_ptr_base_derived_not_supported)
5814 << Value.getMemberPointerDecl() << ParamType
5815 << Arg->getSourceRange();
5819 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
5820 Converted = VD ? TemplateArgument(VD, CanonParamType)
5821 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
5824 case APValue::LValue: {
5825 // For a non-type template-parameter of pointer or reference type,
5826 // the value of the constant expression shall not refer to
5827 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
5828 ParamType->isNullPtrType());
5829 // -- a temporary object
5830 // -- a string literal
5831 // -- the result of a typeid expression, or
5832 // -- a predefined __func__ variable
5833 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
5834 if (isa<CXXUuidofExpr>(E)) {
5835 Converted = TemplateArgument(const_cast<Expr*>(E));
5838 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5839 << Arg->getSourceRange();
5842 auto *VD = const_cast<ValueDecl *>(
5843 Value.getLValueBase().dyn_cast<const ValueDecl *>());
5845 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
5846 VD && VD->getType()->isArrayType() &&
5847 Value.getLValuePath()[0].ArrayIndex == 0 &&
5848 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
5849 // Per defect report (no number yet):
5850 // ... other than a pointer to the first element of a complete array
5852 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
5853 Value.isLValueOnePastTheEnd()) {
5854 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
5855 << Value.getAsString(Context, ParamType);
5858 assert((VD || !ParamType->isReferenceType()) &&
5859 "null reference should not be a constant expression");
5860 assert((!VD || !ParamType->isNullPtrType()) &&
5861 "non-null value of type nullptr_t?");
5862 Converted = VD ? TemplateArgument(VD, CanonParamType)
5863 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
5866 case APValue::AddrLabelDiff:
5867 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
5868 case APValue::Float:
5869 case APValue::ComplexInt:
5870 case APValue::ComplexFloat:
5871 case APValue::Vector:
5872 case APValue::Array:
5873 case APValue::Struct:
5874 case APValue::Union:
5875 llvm_unreachable("invalid kind for template argument");
5878 return ArgResult.get();
5881 // C++ [temp.arg.nontype]p5:
5882 // The following conversions are performed on each expression used
5883 // as a non-type template-argument. If a non-type
5884 // template-argument cannot be converted to the type of the
5885 // corresponding template-parameter then the program is
5887 if (ParamType->isIntegralOrEnumerationType()) {
5889 // -- for a non-type template-parameter of integral or
5890 // enumeration type, conversions permitted in a converted
5891 // constant expression are applied.
5894 // -- for a non-type template-parameter of integral or
5895 // enumeration type, integral promotions (4.5) and integral
5896 // conversions (4.7) are applied.
5898 if (getLangOpts().CPlusPlus11) {
5899 // C++ [temp.arg.nontype]p1:
5900 // A template-argument for a non-type, non-template template-parameter
5903 // -- for a non-type template-parameter of integral or enumeration
5904 // type, a converted constant expression of the type of the
5905 // template-parameter; or
5907 ExprResult ArgResult =
5908 CheckConvertedConstantExpression(Arg, ParamType, Value,
5910 if (ArgResult.isInvalid())
5913 // We can't check arbitrary value-dependent arguments.
5914 if (ArgResult.get()->isValueDependent()) {
5915 Converted = TemplateArgument(ArgResult.get());
5919 // Widen the argument value to sizeof(parameter type). This is almost
5920 // always a no-op, except when the parameter type is bool. In
5921 // that case, this may extend the argument from 1 bit to 8 bits.
5922 QualType IntegerType = ParamType;
5923 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
5924 IntegerType = Enum->getDecl()->getIntegerType();
5925 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
5927 Converted = TemplateArgument(Context, Value,
5928 Context.getCanonicalType(ParamType));
5932 ExprResult ArgResult = DefaultLvalueConversion(Arg);
5933 if (ArgResult.isInvalid())
5935 Arg = ArgResult.get();
5937 QualType ArgType = Arg->getType();
5939 // C++ [temp.arg.nontype]p1:
5940 // A template-argument for a non-type, non-template
5941 // template-parameter shall be one of:
5943 // -- an integral constant-expression of integral or enumeration
5945 // -- the name of a non-type template-parameter; or
5946 SourceLocation NonConstantLoc;
5948 if (!ArgType->isIntegralOrEnumerationType()) {
5949 Diag(Arg->getLocStart(),
5950 diag::err_template_arg_not_integral_or_enumeral)
5951 << ArgType << Arg->getSourceRange();
5952 Diag(Param->getLocation(), diag::note_template_param_here);
5954 } else if (!Arg->isValueDependent()) {
5955 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
5959 TmplArgICEDiagnoser(QualType T) : T(T) { }
5961 void diagnoseNotICE(Sema &S, SourceLocation Loc,
5962 SourceRange SR) override {
5963 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
5965 } Diagnoser(ArgType);
5967 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
5973 // From here on out, all we care about is the unqualified form
5974 // of the argument type.
5975 ArgType = ArgType.getUnqualifiedType();
5977 // Try to convert the argument to the parameter's type.
5978 if (Context.hasSameType(ParamType, ArgType)) {
5979 // Okay: no conversion necessary
5980 } else if (ParamType->isBooleanType()) {
5981 // This is an integral-to-boolean conversion.
5982 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
5983 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
5984 !ParamType->isEnumeralType()) {
5985 // This is an integral promotion or conversion.
5986 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
5988 // We can't perform this conversion.
5989 Diag(Arg->getLocStart(),
5990 diag::err_template_arg_not_convertible)
5991 << Arg->getType() << ParamType << Arg->getSourceRange();
5992 Diag(Param->getLocation(), diag::note_template_param_here);
5996 // Add the value of this argument to the list of converted
5997 // arguments. We use the bitwidth and signedness of the template
5999 if (Arg->isValueDependent()) {
6000 // The argument is value-dependent. Create a new
6001 // TemplateArgument with the converted expression.
6002 Converted = TemplateArgument(Arg);
6006 QualType IntegerType = Context.getCanonicalType(ParamType);
6007 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6008 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
6010 if (ParamType->isBooleanType()) {
6011 // Value must be zero or one.
6013 unsigned AllowedBits = Context.getTypeSize(IntegerType);
6014 if (Value.getBitWidth() != AllowedBits)
6015 Value = Value.extOrTrunc(AllowedBits);
6016 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
6018 llvm::APSInt OldValue = Value;
6020 // Coerce the template argument's value to the value it will have
6021 // based on the template parameter's type.
6022 unsigned AllowedBits = Context.getTypeSize(IntegerType);
6023 if (Value.getBitWidth() != AllowedBits)
6024 Value = Value.extOrTrunc(AllowedBits);
6025 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
6027 // Complain if an unsigned parameter received a negative value.
6028 if (IntegerType->isUnsignedIntegerOrEnumerationType()
6029 && (OldValue.isSigned() && OldValue.isNegative())) {
6030 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
6031 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6032 << Arg->getSourceRange();
6033 Diag(Param->getLocation(), diag::note_template_param_here);
6036 // Complain if we overflowed the template parameter's type.
6037 unsigned RequiredBits;
6038 if (IntegerType->isUnsignedIntegerOrEnumerationType())
6039 RequiredBits = OldValue.getActiveBits();
6040 else if (OldValue.isUnsigned())
6041 RequiredBits = OldValue.getActiveBits() + 1;
6043 RequiredBits = OldValue.getMinSignedBits();
6044 if (RequiredBits > AllowedBits) {
6045 Diag(Arg->getLocStart(),
6046 diag::warn_template_arg_too_large)
6047 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6048 << Arg->getSourceRange();
6049 Diag(Param->getLocation(), diag::note_template_param_here);
6053 Converted = TemplateArgument(Context, Value,
6054 ParamType->isEnumeralType()
6055 ? Context.getCanonicalType(ParamType)
6060 QualType ArgType = Arg->getType();
6061 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
6063 // Handle pointer-to-function, reference-to-function, and
6064 // pointer-to-member-function all in (roughly) the same way.
6065 if (// -- For a non-type template-parameter of type pointer to
6066 // function, only the function-to-pointer conversion (4.3) is
6067 // applied. If the template-argument represents a set of
6068 // overloaded functions (or a pointer to such), the matching
6069 // function is selected from the set (13.4).
6070 (ParamType->isPointerType() &&
6071 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
6072 // -- For a non-type template-parameter of type reference to
6073 // function, no conversions apply. If the template-argument
6074 // represents a set of overloaded functions, the matching
6075 // function is selected from the set (13.4).
6076 (ParamType->isReferenceType() &&
6077 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
6078 // -- For a non-type template-parameter of type pointer to
6079 // member function, no conversions apply. If the
6080 // template-argument represents a set of overloaded member
6081 // functions, the matching member function is selected from
6083 (ParamType->isMemberPointerType() &&
6084 ParamType->getAs<MemberPointerType>()->getPointeeType()
6085 ->isFunctionType())) {
6087 if (Arg->getType() == Context.OverloadTy) {
6088 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
6091 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
6094 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6095 ArgType = Arg->getType();
6100 if (!ParamType->isMemberPointerType()) {
6101 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6108 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6114 if (ParamType->isPointerType()) {
6115 // -- for a non-type template-parameter of type pointer to
6116 // object, qualification conversions (4.4) and the
6117 // array-to-pointer conversion (4.2) are applied.
6118 // C++0x also allows a value of std::nullptr_t.
6119 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
6120 "Only object pointers allowed here");
6122 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6129 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
6130 // -- For a non-type template-parameter of type reference to
6131 // object, no conversions apply. The type referred to by the
6132 // reference may be more cv-qualified than the (otherwise
6133 // identical) type of the template-argument. The
6134 // template-parameter is bound directly to the
6135 // template-argument, which must be an lvalue.
6136 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
6137 "Only object references allowed here");
6139 if (Arg->getType() == Context.OverloadTy) {
6140 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
6141 ParamRefType->getPointeeType(),
6144 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
6147 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6148 ArgType = Arg->getType();
6153 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6160 // Deal with parameters of type std::nullptr_t.
6161 if (ParamType->isNullPtrType()) {
6162 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6163 Converted = TemplateArgument(Arg);
6167 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
6168 case NPV_NotNullPointer:
6169 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
6170 << Arg->getType() << ParamType;
6171 Diag(Param->getLocation(), diag::note_template_param_here);
6177 case NPV_NullPointer:
6178 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6179 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
6185 // -- For a non-type template-parameter of type pointer to data
6186 // member, qualification conversions (4.4) are applied.
6187 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
6189 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6195 static void DiagnoseTemplateParameterListArityMismatch(
6196 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
6197 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
6199 /// \brief Check a template argument against its corresponding
6200 /// template template parameter.
6202 /// This routine implements the semantics of C++ [temp.arg.template].
6203 /// It returns true if an error occurred, and false otherwise.
6204 bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
6205 TemplateArgumentLoc &Arg,
6206 unsigned ArgumentPackIndex) {
6207 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
6208 TemplateDecl *Template = Name.getAsTemplateDecl();
6210 // Any dependent template name is fine.
6211 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
6215 if (Template->isInvalidDecl())
6218 // C++0x [temp.arg.template]p1:
6219 // A template-argument for a template template-parameter shall be
6220 // the name of a class template or an alias template, expressed as an
6221 // id-expression. When the template-argument names a class template, only
6222 // primary class templates are considered when matching the
6223 // template template argument with the corresponding parameter;
6224 // partial specializations are not considered even if their
6225 // parameter lists match that of the template template parameter.
6227 // Note that we also allow template template parameters here, which
6228 // will happen when we are dealing with, e.g., class template
6229 // partial specializations.
6230 if (!isa<ClassTemplateDecl>(Template) &&
6231 !isa<TemplateTemplateParmDecl>(Template) &&
6232 !isa<TypeAliasTemplateDecl>(Template) &&
6233 !isa<BuiltinTemplateDecl>(Template)) {
6234 assert(isa<FunctionTemplateDecl>(Template) &&
6235 "Only function templates are possible here");
6236 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
6237 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
6241 TemplateParameterList *Params = Param->getTemplateParameters();
6242 if (Param->isExpandedParameterPack())
6243 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
6245 // C++1z [temp.arg.template]p3: (DR 150)
6246 // A template-argument matches a template template-parameter P when P
6247 // is at least as specialized as the template-argument A.
6248 if (getLangOpts().RelaxedTemplateTemplateArgs) {
6249 // Quick check for the common case:
6250 // If P contains a parameter pack, then A [...] matches P if each of A's
6251 // template parameters matches the corresponding template parameter in
6252 // the template-parameter-list of P.
6253 if (TemplateParameterListsAreEqual(
6254 Template->getTemplateParameters(), Params, false,
6255 TPL_TemplateTemplateArgumentMatch, Arg.getLocation()))
6258 if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
6261 // FIXME: Produce better diagnostics for deduction failures.
6264 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
6267 TPL_TemplateTemplateArgumentMatch,
6271 /// \brief Given a non-type template argument that refers to a
6272 /// declaration and the type of its corresponding non-type template
6273 /// parameter, produce an expression that properly refers to that
6276 Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6278 SourceLocation Loc) {
6279 // C++ [temp.param]p8:
6281 // A non-type template-parameter of type "array of T" or
6282 // "function returning T" is adjusted to be of type "pointer to
6283 // T" or "pointer to function returning T", respectively.
6284 if (ParamType->isArrayType())
6285 ParamType = Context.getArrayDecayedType(ParamType);
6286 else if (ParamType->isFunctionType())
6287 ParamType = Context.getPointerType(ParamType);
6289 // For a NULL non-type template argument, return nullptr casted to the
6290 // parameter's type.
6291 if (Arg.getKind() == TemplateArgument::NullPtr) {
6292 return ImpCastExprToType(
6293 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
6295 ParamType->getAs<MemberPointerType>()
6296 ? CK_NullToMemberPointer
6297 : CK_NullToPointer);
6299 assert(Arg.getKind() == TemplateArgument::Declaration &&
6300 "Only declaration template arguments permitted here");
6302 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
6304 if (VD->getDeclContext()->isRecord() &&
6305 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
6306 isa<IndirectFieldDecl>(VD))) {
6307 // If the value is a class member, we might have a pointer-to-member.
6308 // Determine whether the non-type template template parameter is of
6309 // pointer-to-member type. If so, we need to build an appropriate
6310 // expression for a pointer-to-member, since a "normal" DeclRefExpr
6311 // would refer to the member itself.
6312 if (ParamType->isMemberPointerType()) {
6314 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
6315 NestedNameSpecifier *Qualifier
6316 = NestedNameSpecifier::Create(Context, nullptr, false,
6317 ClassType.getTypePtr());
6319 SS.MakeTrivial(Context, Qualifier, Loc);
6321 // The actual value-ness of this is unimportant, but for
6322 // internal consistency's sake, references to instance methods
6324 ExprValueKind VK = VK_LValue;
6325 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
6328 ExprResult RefExpr = BuildDeclRefExpr(VD,
6329 VD->getType().getNonReferenceType(),
6333 if (RefExpr.isInvalid())
6336 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
6338 // We might need to perform a trailing qualification conversion, since
6339 // the element type on the parameter could be more qualified than the
6340 // element type in the expression we constructed.
6341 bool ObjCLifetimeConversion;
6342 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
6343 ParamType.getUnqualifiedType(), false,
6344 ObjCLifetimeConversion))
6345 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
6347 assert(!RefExpr.isInvalid() &&
6348 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
6349 ParamType.getUnqualifiedType()));
6354 QualType T = VD->getType().getNonReferenceType();
6356 if (ParamType->isPointerType()) {
6357 // When the non-type template parameter is a pointer, take the
6358 // address of the declaration.
6359 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
6360 if (RefExpr.isInvalid())
6363 if (!Context.hasSameUnqualifiedType(ParamType->getPointeeType(), T) &&
6364 (T->isFunctionType() || T->isArrayType())) {
6365 // Decay functions and arrays unless we're forming a pointer to array.
6366 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
6367 if (RefExpr.isInvalid())
6373 // Take the address of everything else
6374 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
6377 ExprValueKind VK = VK_RValue;
6379 // If the non-type template parameter has reference type, qualify the
6380 // resulting declaration reference with the extra qualifiers on the
6381 // type that the reference refers to.
6382 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
6384 T = Context.getQualifiedType(T,
6385 TargetRef->getPointeeType().getQualifiers());
6386 } else if (isa<FunctionDecl>(VD)) {
6387 // References to functions are always lvalues.
6391 return BuildDeclRefExpr(VD, T, VK, Loc);
6394 /// \brief Construct a new expression that refers to the given
6395 /// integral template argument with the given source-location
6398 /// This routine takes care of the mapping from an integral template
6399 /// argument (which may have any integral type) to the appropriate
6402 Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6403 SourceLocation Loc) {
6404 assert(Arg.getKind() == TemplateArgument::Integral &&
6405 "Operation is only valid for integral template arguments");
6406 QualType OrigT = Arg.getIntegralType();
6408 // If this is an enum type that we're instantiating, we need to use an integer
6409 // type the same size as the enumerator. We don't want to build an
6410 // IntegerLiteral with enum type. The integer type of an enum type can be of
6411 // any integral type with C++11 enum classes, make sure we create the right
6412 // type of literal for it.
6414 if (const EnumType *ET = OrigT->getAs<EnumType>())
6415 T = ET->getDecl()->getIntegerType();
6418 if (T->isAnyCharacterType()) {
6419 // This does not need to handle u8 character literals because those are
6420 // of type char, and so can also be covered by an ASCII character literal.
6421 CharacterLiteral::CharacterKind Kind;
6422 if (T->isWideCharType())
6423 Kind = CharacterLiteral::Wide;
6424 else if (T->isChar16Type())
6425 Kind = CharacterLiteral::UTF16;
6426 else if (T->isChar32Type())
6427 Kind = CharacterLiteral::UTF32;
6429 Kind = CharacterLiteral::Ascii;
6431 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
6433 } else if (T->isBooleanType()) {
6434 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
6436 } else if (T->isNullPtrType()) {
6437 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
6439 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
6442 if (OrigT->isEnumeralType()) {
6443 // FIXME: This is a hack. We need a better way to handle substituted
6444 // non-type template parameters.
6445 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
6447 Context.getTrivialTypeSourceInfo(OrigT, Loc),
6454 /// \brief Match two template parameters within template parameter lists.
6455 static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
6457 Sema::TemplateParameterListEqualKind Kind,
6458 SourceLocation TemplateArgLoc) {
6459 // Check the actual kind (type, non-type, template).
6460 if (Old->getKind() != New->getKind()) {
6462 unsigned NextDiag = diag::err_template_param_different_kind;
6463 if (TemplateArgLoc.isValid()) {
6464 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6465 NextDiag = diag::note_template_param_different_kind;
6467 S.Diag(New->getLocation(), NextDiag)
6468 << (Kind != Sema::TPL_TemplateMatch);
6469 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
6470 << (Kind != Sema::TPL_TemplateMatch);
6476 // Check that both are parameter packs or neither are parameter packs.
6477 // However, if we are matching a template template argument to a
6478 // template template parameter, the template template parameter can have
6479 // a parameter pack where the template template argument does not.
6480 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
6481 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
6482 Old->isTemplateParameterPack())) {
6484 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
6485 if (TemplateArgLoc.isValid()) {
6486 S.Diag(TemplateArgLoc,
6487 diag::err_template_arg_template_params_mismatch);
6488 NextDiag = diag::note_template_parameter_pack_non_pack;
6491 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
6492 : isa<NonTypeTemplateParmDecl>(New)? 1
6494 S.Diag(New->getLocation(), NextDiag)
6495 << ParamKind << New->isParameterPack();
6496 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
6497 << ParamKind << Old->isParameterPack();
6503 // For non-type template parameters, check the type of the parameter.
6504 if (NonTypeTemplateParmDecl *OldNTTP
6505 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
6506 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
6508 // If we are matching a template template argument to a template
6509 // template parameter and one of the non-type template parameter types
6510 // is dependent, then we must wait until template instantiation time
6511 // to actually compare the arguments.
6512 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
6513 (OldNTTP->getType()->isDependentType() ||
6514 NewNTTP->getType()->isDependentType()))
6517 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
6519 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
6520 if (TemplateArgLoc.isValid()) {
6521 S.Diag(TemplateArgLoc,
6522 diag::err_template_arg_template_params_mismatch);
6523 NextDiag = diag::note_template_nontype_parm_different_type;
6525 S.Diag(NewNTTP->getLocation(), NextDiag)
6526 << NewNTTP->getType()
6527 << (Kind != Sema::TPL_TemplateMatch);
6528 S.Diag(OldNTTP->getLocation(),
6529 diag::note_template_nontype_parm_prev_declaration)
6530 << OldNTTP->getType();
6539 // For template template parameters, check the template parameter types.
6540 // The template parameter lists of template template
6541 // parameters must agree.
6542 if (TemplateTemplateParmDecl *OldTTP
6543 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
6544 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
6545 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
6546 OldTTP->getTemplateParameters(),
6548 (Kind == Sema::TPL_TemplateMatch
6549 ? Sema::TPL_TemplateTemplateParmMatch
6557 /// \brief Diagnose a known arity mismatch when comparing template argument
6560 void DiagnoseTemplateParameterListArityMismatch(Sema &S,
6561 TemplateParameterList *New,
6562 TemplateParameterList *Old,
6563 Sema::TemplateParameterListEqualKind Kind,
6564 SourceLocation TemplateArgLoc) {
6565 unsigned NextDiag = diag::err_template_param_list_different_arity;
6566 if (TemplateArgLoc.isValid()) {
6567 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6568 NextDiag = diag::note_template_param_list_different_arity;
6570 S.Diag(New->getTemplateLoc(), NextDiag)
6571 << (New->size() > Old->size())
6572 << (Kind != Sema::TPL_TemplateMatch)
6573 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
6574 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
6575 << (Kind != Sema::TPL_TemplateMatch)
6576 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
6579 /// \brief Determine whether the given template parameter lists are
6582 /// \param New The new template parameter list, typically written in the
6583 /// source code as part of a new template declaration.
6585 /// \param Old The old template parameter list, typically found via
6586 /// name lookup of the template declared with this template parameter
6589 /// \param Complain If true, this routine will produce a diagnostic if
6590 /// the template parameter lists are not equivalent.
6592 /// \param Kind describes how we are to match the template parameter lists.
6594 /// \param TemplateArgLoc If this source location is valid, then we
6595 /// are actually checking the template parameter list of a template
6596 /// argument (New) against the template parameter list of its
6597 /// corresponding template template parameter (Old). We produce
6598 /// slightly different diagnostics in this scenario.
6600 /// \returns True if the template parameter lists are equal, false
6603 Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
6604 TemplateParameterList *Old,
6606 TemplateParameterListEqualKind Kind,
6607 SourceLocation TemplateArgLoc) {
6608 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
6610 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6616 // C++0x [temp.arg.template]p3:
6617 // A template-argument matches a template template-parameter (call it P)
6618 // when each of the template parameters in the template-parameter-list of
6619 // the template-argument's corresponding class template or alias template
6620 // (call it A) matches the corresponding template parameter in the
6621 // template-parameter-list of P. [...]
6622 TemplateParameterList::iterator NewParm = New->begin();
6623 TemplateParameterList::iterator NewParmEnd = New->end();
6624 for (TemplateParameterList::iterator OldParm = Old->begin(),
6625 OldParmEnd = Old->end();
6626 OldParm != OldParmEnd; ++OldParm) {
6627 if (Kind != TPL_TemplateTemplateArgumentMatch ||
6628 !(*OldParm)->isTemplateParameterPack()) {
6629 if (NewParm == NewParmEnd) {
6631 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6637 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
6638 Kind, TemplateArgLoc))
6645 // C++0x [temp.arg.template]p3:
6646 // [...] When P's template- parameter-list contains a template parameter
6647 // pack (14.5.3), the template parameter pack will match zero or more
6648 // template parameters or template parameter packs in the
6649 // template-parameter-list of A with the same type and form as the
6650 // template parameter pack in P (ignoring whether those template
6651 // parameters are template parameter packs).
6652 for (; NewParm != NewParmEnd; ++NewParm) {
6653 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
6654 Kind, TemplateArgLoc))
6659 // Make sure we exhausted all of the arguments.
6660 if (NewParm != NewParmEnd) {
6662 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6671 /// \brief Check whether a template can be declared within this scope.
6673 /// If the template declaration is valid in this scope, returns
6674 /// false. Otherwise, issues a diagnostic and returns true.
6676 Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
6680 // Find the nearest enclosing declaration scope.
6681 while ((S->getFlags() & Scope::DeclScope) == 0 ||
6682 (S->getFlags() & Scope::TemplateParamScope) != 0)
6686 // A template [...] shall not have C linkage.
6687 DeclContext *Ctx = S->getEntity();
6688 if (Ctx && Ctx->isExternCContext()) {
6689 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
6690 << TemplateParams->getSourceRange();
6691 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
6692 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
6695 Ctx = Ctx->getRedeclContext();
6698 // A template-declaration can appear only as a namespace scope or
6699 // class scope declaration.
6701 if (Ctx->isFileContext())
6703 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
6704 // C++ [temp.mem]p2:
6705 // A local class shall not have member templates.
6706 if (RD->isLocalClass())
6707 return Diag(TemplateParams->getTemplateLoc(),
6708 diag::err_template_inside_local_class)
6709 << TemplateParams->getSourceRange();
6715 return Diag(TemplateParams->getTemplateLoc(),
6716 diag::err_template_outside_namespace_or_class_scope)
6717 << TemplateParams->getSourceRange();
6720 /// \brief Determine what kind of template specialization the given declaration
6722 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
6724 return TSK_Undeclared;
6726 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
6727 return Record->getTemplateSpecializationKind();
6728 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
6729 return Function->getTemplateSpecializationKind();
6730 if (VarDecl *Var = dyn_cast<VarDecl>(D))
6731 return Var->getTemplateSpecializationKind();
6733 return TSK_Undeclared;
6736 /// \brief Check whether a specialization is well-formed in the current
6739 /// This routine determines whether a template specialization can be declared
6740 /// in the current context (C++ [temp.expl.spec]p2).
6742 /// \param S the semantic analysis object for which this check is being
6745 /// \param Specialized the entity being specialized or instantiated, which
6746 /// may be a kind of template (class template, function template, etc.) or
6747 /// a member of a class template (member function, static data member,
6750 /// \param PrevDecl the previous declaration of this entity, if any.
6752 /// \param Loc the location of the explicit specialization or instantiation of
6755 /// \param IsPartialSpecialization whether this is a partial specialization of
6756 /// a class template.
6758 /// \returns true if there was an error that we cannot recover from, false
6760 static bool CheckTemplateSpecializationScope(Sema &S,
6761 NamedDecl *Specialized,
6762 NamedDecl *PrevDecl,
6764 bool IsPartialSpecialization) {
6765 // Keep these "kind" numbers in sync with the %select statements in the
6766 // various diagnostics emitted by this routine.
6768 if (isa<ClassTemplateDecl>(Specialized))
6769 EntityKind = IsPartialSpecialization? 1 : 0;
6770 else if (isa<VarTemplateDecl>(Specialized))
6771 EntityKind = IsPartialSpecialization ? 3 : 2;
6772 else if (isa<FunctionTemplateDecl>(Specialized))
6774 else if (isa<CXXMethodDecl>(Specialized))
6776 else if (isa<VarDecl>(Specialized))
6778 else if (isa<RecordDecl>(Specialized))
6780 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
6783 S.Diag(Loc, diag::err_template_spec_unknown_kind)
6784 << S.getLangOpts().CPlusPlus11;
6785 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
6789 // C++ [temp.expl.spec]p2:
6790 // An explicit specialization shall be declared in the namespace
6791 // of which the template is a member, or, for member templates, in
6792 // the namespace of which the enclosing class or enclosing class
6793 // template is a member. An explicit specialization of a member
6794 // function, member class or static data member of a class
6795 // template shall be declared in the namespace of which the class
6796 // template is a member. Such a declaration may also be a
6797 // definition. If the declaration is not a definition, the
6798 // specialization may be defined later in the name- space in which
6799 // the explicit specialization was declared, or in a namespace
6800 // that encloses the one in which the explicit specialization was
6802 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6803 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
6808 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
6809 if (S.getLangOpts().MicrosoftExt) {
6810 // Do not warn for class scope explicit specialization during
6811 // instantiation, warning was already emitted during pattern
6812 // semantic analysis.
6813 if (!S.inTemplateInstantiation())
6814 S.Diag(Loc, diag::ext_function_specialization_in_class)
6817 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
6823 if (S.CurContext->isRecord() &&
6824 !S.CurContext->Equals(Specialized->getDeclContext())) {
6825 // Make sure that we're specializing in the right record context.
6826 // Otherwise, things can go horribly wrong.
6827 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
6832 // C++ [temp.class.spec]p6:
6833 // A class template partial specialization may be declared or redeclared
6834 // in any namespace scope in which its definition may be defined (14.5.1
6836 DeclContext *SpecializedContext
6837 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
6838 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
6840 // Make sure that this redeclaration (or definition) occurs in an enclosing
6842 // Note that HandleDeclarator() performs this check for explicit
6843 // specializations of function templates, static data members, and member
6844 // functions, so we skip the check here for those kinds of entities.
6845 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
6846 // Should we refactor that check, so that it occurs later?
6847 if (!DC->Encloses(SpecializedContext) &&
6848 !(isa<FunctionTemplateDecl>(Specialized) ||
6849 isa<FunctionDecl>(Specialized) ||
6850 isa<VarTemplateDecl>(Specialized) ||
6851 isa<VarDecl>(Specialized))) {
6852 if (isa<TranslationUnitDecl>(SpecializedContext))
6853 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
6854 << EntityKind << Specialized;
6855 else if (isa<NamespaceDecl>(SpecializedContext)) {
6856 int Diag = diag::err_template_spec_redecl_out_of_scope;
6857 if (S.getLangOpts().MicrosoftExt)
6858 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
6859 S.Diag(Loc, Diag) << EntityKind << Specialized
6860 << cast<NamedDecl>(SpecializedContext);
6862 llvm_unreachable("unexpected namespace context for specialization");
6864 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
6865 } else if ((!PrevDecl ||
6866 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
6867 getTemplateSpecializationKind(PrevDecl) ==
6868 TSK_ImplicitInstantiation)) {
6869 // C++ [temp.exp.spec]p2:
6870 // An explicit specialization shall be declared in the namespace of which
6871 // the template is a member, or, for member templates, in the namespace
6872 // of which the enclosing class or enclosing class template is a member.
6873 // An explicit specialization of a member function, member class or
6874 // static data member of a class template shall be declared in the
6875 // namespace of which the class template is a member.
6877 // C++11 [temp.expl.spec]p2:
6878 // An explicit specialization shall be declared in a namespace enclosing
6879 // the specialized template.
6880 // C++11 [temp.explicit]p3:
6881 // An explicit instantiation shall appear in an enclosing namespace of its
6883 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
6884 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
6885 if (isa<TranslationUnitDecl>(SpecializedContext)) {
6886 assert(!IsCPlusPlus11Extension &&
6887 "DC encloses TU but isn't in enclosing namespace set");
6888 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
6889 << EntityKind << Specialized;
6890 } else if (isa<NamespaceDecl>(SpecializedContext)) {
6892 if (!IsCPlusPlus11Extension)
6893 Diag = diag::err_template_spec_decl_out_of_scope;
6894 else if (!S.getLangOpts().CPlusPlus11)
6895 Diag = diag::ext_template_spec_decl_out_of_scope;
6897 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
6899 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
6902 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
6909 static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
6910 if (!E->isTypeDependent())
6911 return SourceLocation();
6912 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
6913 Checker.TraverseStmt(E);
6914 if (Checker.MatchLoc.isInvalid())
6915 return E->getSourceRange();
6916 return Checker.MatchLoc;
6919 static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
6920 if (!TL.getType()->isDependentType())
6921 return SourceLocation();
6922 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
6923 Checker.TraverseTypeLoc(TL);
6924 if (Checker.MatchLoc.isInvalid())
6925 return TL.getSourceRange();
6926 return Checker.MatchLoc;
6929 /// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
6930 /// that checks non-type template partial specialization arguments.
6931 static bool CheckNonTypeTemplatePartialSpecializationArgs(
6932 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
6933 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
6934 for (unsigned I = 0; I != NumArgs; ++I) {
6935 if (Args[I].getKind() == TemplateArgument::Pack) {
6936 if (CheckNonTypeTemplatePartialSpecializationArgs(
6937 S, TemplateNameLoc, Param, Args[I].pack_begin(),
6938 Args[I].pack_size(), IsDefaultArgument))
6944 if (Args[I].getKind() != TemplateArgument::Expression)
6947 Expr *ArgExpr = Args[I].getAsExpr();
6949 // We can have a pack expansion of any of the bullets below.
6950 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
6951 ArgExpr = Expansion->getPattern();
6953 // Strip off any implicit casts we added as part of type checking.
6954 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
6955 ArgExpr = ICE->getSubExpr();
6957 // C++ [temp.class.spec]p8:
6958 // A non-type argument is non-specialized if it is the name of a
6959 // non-type parameter. All other non-type arguments are
6962 // Below, we check the two conditions that only apply to
6963 // specialized non-type arguments, so skip any non-specialized
6965 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
6966 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
6969 // C++ [temp.class.spec]p9:
6970 // Within the argument list of a class template partial
6971 // specialization, the following restrictions apply:
6972 // -- A partially specialized non-type argument expression
6973 // shall not involve a template parameter of the partial
6974 // specialization except when the argument expression is a
6975 // simple identifier.
6976 // -- The type of a template parameter corresponding to a
6977 // specialized non-type argument shall not be dependent on a
6978 // parameter of the specialization.
6979 // DR1315 removes the first bullet, leaving an incoherent set of rules.
6980 // We implement a compromise between the original rules and DR1315:
6981 // -- A specialized non-type template argument shall not be
6982 // type-dependent and the corresponding template parameter
6983 // shall have a non-dependent type.
6984 SourceRange ParamUseRange =
6985 findTemplateParameterInType(Param->getDepth(), ArgExpr);
6986 if (ParamUseRange.isValid()) {
6987 if (IsDefaultArgument) {
6988 S.Diag(TemplateNameLoc,
6989 diag::err_dependent_non_type_arg_in_partial_spec);
6990 S.Diag(ParamUseRange.getBegin(),
6991 diag::note_dependent_non_type_default_arg_in_partial_spec)
6994 S.Diag(ParamUseRange.getBegin(),
6995 diag::err_dependent_non_type_arg_in_partial_spec)
7001 ParamUseRange = findTemplateParameter(
7002 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
7003 if (ParamUseRange.isValid()) {
7004 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
7005 diag::err_dependent_typed_non_type_arg_in_partial_spec)
7006 << Param->getType();
7007 S.Diag(Param->getLocation(), diag::note_template_param_here)
7008 << (IsDefaultArgument ? ParamUseRange : SourceRange())
7017 /// \brief Check the non-type template arguments of a class template
7018 /// partial specialization according to C++ [temp.class.spec]p9.
7020 /// \param TemplateNameLoc the location of the template name.
7021 /// \param PrimaryTemplate the template parameters of the primary class
7023 /// \param NumExplicit the number of explicitly-specified template arguments.
7024 /// \param TemplateArgs the template arguments of the class template
7025 /// partial specialization.
7027 /// \returns \c true if there was an error, \c false otherwise.
7028 bool Sema::CheckTemplatePartialSpecializationArgs(
7029 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
7030 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
7031 // We have to be conservative when checking a template in a dependent
7033 if (PrimaryTemplate->getDeclContext()->isDependentContext())
7036 TemplateParameterList *TemplateParams =
7037 PrimaryTemplate->getTemplateParameters();
7038 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7039 NonTypeTemplateParmDecl *Param
7040 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
7044 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
7045 Param, &TemplateArgs[I],
7046 1, I >= NumExplicit))
7054 Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
7056 SourceLocation KWLoc,
7057 SourceLocation ModulePrivateLoc,
7058 TemplateIdAnnotation &TemplateId,
7059 AttributeList *Attr,
7060 MultiTemplateParamsArg
7061 TemplateParameterLists,
7062 SkipBodyInfo *SkipBody) {
7063 assert(TUK != TUK_Reference && "References are not specializations");
7065 CXXScopeSpec &SS = TemplateId.SS;
7067 // NOTE: KWLoc is the location of the tag keyword. This will instead
7068 // store the location of the outermost template keyword in the declaration.
7069 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
7070 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
7071 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
7072 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
7073 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
7075 // Find the class template we're specializing
7076 TemplateName Name = TemplateId.Template.get();
7077 ClassTemplateDecl *ClassTemplate
7078 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
7080 if (!ClassTemplate) {
7081 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
7082 << (Name.getAsTemplateDecl() &&
7083 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
7087 bool isMemberSpecialization = false;
7088 bool isPartialSpecialization = false;
7090 // Check the validity of the template headers that introduce this
7092 // FIXME: We probably shouldn't complain about these headers for
7093 // friend declarations.
7094 bool Invalid = false;
7095 TemplateParameterList *TemplateParams =
7096 MatchTemplateParametersToScopeSpecifier(
7097 KWLoc, TemplateNameLoc, SS, &TemplateId,
7098 TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
7103 if (TemplateParams && TemplateParams->size() > 0) {
7104 isPartialSpecialization = true;
7106 if (TUK == TUK_Friend) {
7107 Diag(KWLoc, diag::err_partial_specialization_friend)
7108 << SourceRange(LAngleLoc, RAngleLoc);
7112 // C++ [temp.class.spec]p10:
7113 // The template parameter list of a specialization shall not
7114 // contain default template argument values.
7115 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7116 Decl *Param = TemplateParams->getParam(I);
7117 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
7118 if (TTP->hasDefaultArgument()) {
7119 Diag(TTP->getDefaultArgumentLoc(),
7120 diag::err_default_arg_in_partial_spec);
7121 TTP->removeDefaultArgument();
7123 } else if (NonTypeTemplateParmDecl *NTTP
7124 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
7125 if (Expr *DefArg = NTTP->getDefaultArgument()) {
7126 Diag(NTTP->getDefaultArgumentLoc(),
7127 diag::err_default_arg_in_partial_spec)
7128 << DefArg->getSourceRange();
7129 NTTP->removeDefaultArgument();
7132 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
7133 if (TTP->hasDefaultArgument()) {
7134 Diag(TTP->getDefaultArgument().getLocation(),
7135 diag::err_default_arg_in_partial_spec)
7136 << TTP->getDefaultArgument().getSourceRange();
7137 TTP->removeDefaultArgument();
7141 } else if (TemplateParams) {
7142 if (TUK == TUK_Friend)
7143 Diag(KWLoc, diag::err_template_spec_friend)
7144 << FixItHint::CreateRemoval(
7145 SourceRange(TemplateParams->getTemplateLoc(),
7146 TemplateParams->getRAngleLoc()))
7147 << SourceRange(LAngleLoc, RAngleLoc);
7149 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
7152 // Check that the specialization uses the same tag kind as the
7153 // original template.
7154 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7155 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
7156 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
7157 Kind, TUK == TUK_Definition, KWLoc,
7158 ClassTemplate->getIdentifier())) {
7159 Diag(KWLoc, diag::err_use_with_wrong_tag)
7161 << FixItHint::CreateReplacement(KWLoc,
7162 ClassTemplate->getTemplatedDecl()->getKindName());
7163 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
7164 diag::note_previous_use);
7165 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7168 // Translate the parser's template argument list in our AST format.
7169 TemplateArgumentListInfo TemplateArgs =
7170 makeTemplateArgumentListInfo(*this, TemplateId);
7172 // Check for unexpanded parameter packs in any of the template arguments.
7173 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7174 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
7175 UPPC_PartialSpecialization))
7178 // Check that the template argument list is well-formed for this
7180 SmallVector<TemplateArgument, 4> Converted;
7181 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7182 TemplateArgs, false, Converted))
7185 // Find the class template (partial) specialization declaration that
7186 // corresponds to these arguments.
7187 if (isPartialSpecialization) {
7188 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
7189 TemplateArgs.size(), Converted))
7192 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
7193 // also do it during instantiation.
7194 bool InstantiationDependent;
7195 if (!Name.isDependent() &&
7196 !TemplateSpecializationType::anyDependentTemplateArguments(
7197 TemplateArgs.arguments(), InstantiationDependent)) {
7198 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
7199 << ClassTemplate->getDeclName();
7200 isPartialSpecialization = false;
7204 void *InsertPos = nullptr;
7205 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
7207 if (isPartialSpecialization)
7208 // FIXME: Template parameter list matters, too
7209 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
7211 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
7213 ClassTemplateSpecializationDecl *Specialization = nullptr;
7215 // Check whether we can declare a class template specialization in
7216 // the current scope.
7217 if (TUK != TUK_Friend &&
7218 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
7220 isPartialSpecialization))
7223 // The canonical type
7225 if (isPartialSpecialization) {
7226 // Build the canonical type that describes the converted template
7227 // arguments of the class template partial specialization.
7228 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7229 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
7232 if (Context.hasSameType(CanonType,
7233 ClassTemplate->getInjectedClassNameSpecialization())) {
7234 // C++ [temp.class.spec]p9b3:
7236 // -- The argument list of the specialization shall not be identical
7237 // to the implicit argument list of the primary template.
7239 // This rule has since been removed, because it's redundant given DR1495,
7240 // but we keep it because it produces better diagnostics and recovery.
7241 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
7242 << /*class template*/0 << (TUK == TUK_Definition)
7243 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
7244 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
7245 ClassTemplate->getIdentifier(),
7249 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
7250 /*FriendLoc*/SourceLocation(),
7251 TemplateParameterLists.size() - 1,
7252 TemplateParameterLists.data());
7255 // Create a new class template partial specialization declaration node.
7256 ClassTemplatePartialSpecializationDecl *PrevPartial
7257 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
7258 ClassTemplatePartialSpecializationDecl *Partial
7259 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
7260 ClassTemplate->getDeclContext(),
7261 KWLoc, TemplateNameLoc,
7268 SetNestedNameSpecifier(Partial, SS);
7269 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
7270 Partial->setTemplateParameterListsInfo(
7271 Context, TemplateParameterLists.drop_back(1));
7275 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
7276 Specialization = Partial;
7278 // If we are providing an explicit specialization of a member class
7279 // template specialization, make a note of that.
7280 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
7281 PrevPartial->setMemberSpecialization();
7283 CheckTemplatePartialSpecialization(Partial);
7285 // Create a new class template specialization declaration node for
7286 // this explicit specialization or friend declaration.
7288 = ClassTemplateSpecializationDecl::Create(Context, Kind,
7289 ClassTemplate->getDeclContext(),
7290 KWLoc, TemplateNameLoc,
7294 SetNestedNameSpecifier(Specialization, SS);
7295 if (TemplateParameterLists.size() > 0) {
7296 Specialization->setTemplateParameterListsInfo(Context,
7297 TemplateParameterLists);
7301 ClassTemplate->AddSpecialization(Specialization, InsertPos);
7303 if (CurContext->isDependentContext()) {
7304 // -fms-extensions permits specialization of nested classes without
7305 // fully specializing the outer class(es).
7306 assert(getLangOpts().MicrosoftExt &&
7307 "Only possible with -fms-extensions!");
7308 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7309 CanonType = Context.getTemplateSpecializationType(
7310 CanonTemplate, Converted);
7312 CanonType = Context.getTypeDeclType(Specialization);
7316 // C++ [temp.expl.spec]p6:
7317 // If a template, a member template or the member of a class template is
7318 // explicitly specialized then that specialization shall be declared
7319 // before the first use of that specialization that would cause an implicit
7320 // instantiation to take place, in every translation unit in which such a
7321 // use occurs; no diagnostic is required.
7322 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
7324 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
7325 // Is there any previous explicit specialization declaration?
7326 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7333 SourceRange Range(TemplateNameLoc, RAngleLoc);
7334 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
7335 << Context.getTypeDeclType(Specialization) << Range;
7337 Diag(PrevDecl->getPointOfInstantiation(),
7338 diag::note_instantiation_required_here)
7339 << (PrevDecl->getTemplateSpecializationKind()
7340 != TSK_ImplicitInstantiation);
7345 // If this is not a friend, note that this is an explicit specialization.
7346 if (TUK != TUK_Friend)
7347 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
7349 // Check that this isn't a redefinition of this specialization.
7350 if (TUK == TUK_Definition) {
7351 RecordDecl *Def = Specialization->getDefinition();
7352 NamedDecl *Hidden = nullptr;
7353 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
7354 SkipBody->ShouldSkip = true;
7355 makeMergedDefinitionVisible(Hidden, KWLoc);
7356 // From here on out, treat this as just a redeclaration.
7357 TUK = TUK_Declaration;
7359 SourceRange Range(TemplateNameLoc, RAngleLoc);
7360 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
7361 Diag(Def->getLocation(), diag::note_previous_definition);
7362 Specialization->setInvalidDecl();
7368 ProcessDeclAttributeList(S, Specialization, Attr);
7370 // Add alignment attributes if necessary; these attributes are checked when
7371 // the ASTContext lays out the structure.
7372 if (TUK == TUK_Definition) {
7373 AddAlignmentAttributesForRecord(Specialization);
7374 AddMsStructLayoutForRecord(Specialization);
7377 if (ModulePrivateLoc.isValid())
7378 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
7379 << (isPartialSpecialization? 1 : 0)
7380 << FixItHint::CreateRemoval(ModulePrivateLoc);
7382 // Build the fully-sugared type for this class template
7383 // specialization as the user wrote in the specialization
7384 // itself. This means that we'll pretty-print the type retrieved
7385 // from the specialization's declaration the way that the user
7386 // actually wrote the specialization, rather than formatting the
7387 // name based on the "canonical" representation used to store the
7388 // template arguments in the specialization.
7389 TypeSourceInfo *WrittenTy
7390 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7391 TemplateArgs, CanonType);
7392 if (TUK != TUK_Friend) {
7393 Specialization->setTypeAsWritten(WrittenTy);
7394 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
7397 // C++ [temp.expl.spec]p9:
7398 // A template explicit specialization is in the scope of the
7399 // namespace in which the template was defined.
7401 // We actually implement this paragraph where we set the semantic
7402 // context (in the creation of the ClassTemplateSpecializationDecl),
7403 // but we also maintain the lexical context where the actual
7404 // definition occurs.
7405 Specialization->setLexicalDeclContext(CurContext);
7407 // We may be starting the definition of this specialization.
7408 if (TUK == TUK_Definition)
7409 Specialization->startDefinition();
7411 if (TUK == TUK_Friend) {
7412 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
7416 Friend->setAccess(AS_public);
7417 CurContext->addDecl(Friend);
7419 // Add the specialization into its lexical context, so that it can
7420 // be seen when iterating through the list of declarations in that
7421 // context. However, specializations are not found by name lookup.
7422 CurContext->addDecl(Specialization);
7424 return Specialization;
7427 Decl *Sema::ActOnTemplateDeclarator(Scope *S,
7428 MultiTemplateParamsArg TemplateParameterLists,
7430 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
7431 ActOnDocumentableDecl(NewDecl);
7435 /// \brief Strips various properties off an implicit instantiation
7436 /// that has just been explicitly specialized.
7437 static void StripImplicitInstantiation(NamedDecl *D) {
7438 D->dropAttr<DLLImportAttr>();
7439 D->dropAttr<DLLExportAttr>();
7441 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
7442 FD->setInlineSpecified(false);
7445 /// \brief Compute the diagnostic location for an explicit instantiation
7446 // declaration or definition.
7447 static SourceLocation DiagLocForExplicitInstantiation(
7448 NamedDecl* D, SourceLocation PointOfInstantiation) {
7449 // Explicit instantiations following a specialization have no effect and
7450 // hence no PointOfInstantiation. In that case, walk decl backwards
7451 // until a valid name loc is found.
7452 SourceLocation PrevDiagLoc = PointOfInstantiation;
7453 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
7454 Prev = Prev->getPreviousDecl()) {
7455 PrevDiagLoc = Prev->getLocation();
7457 assert(PrevDiagLoc.isValid() &&
7458 "Explicit instantiation without point of instantiation?");
7462 /// \brief Diagnose cases where we have an explicit template specialization
7463 /// before/after an explicit template instantiation, producing diagnostics
7464 /// for those cases where they are required and determining whether the
7465 /// new specialization/instantiation will have any effect.
7467 /// \param NewLoc the location of the new explicit specialization or
7470 /// \param NewTSK the kind of the new explicit specialization or instantiation.
7472 /// \param PrevDecl the previous declaration of the entity.
7474 /// \param PrevTSK the kind of the old explicit specialization or instantiatin.
7476 /// \param PrevPointOfInstantiation if valid, indicates where the previus
7477 /// declaration was instantiated (either implicitly or explicitly).
7479 /// \param HasNoEffect will be set to true to indicate that the new
7480 /// specialization or instantiation has no effect and should be ignored.
7482 /// \returns true if there was an error that should prevent the introduction of
7483 /// the new declaration into the AST, false otherwise.
7485 Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
7486 TemplateSpecializationKind NewTSK,
7487 NamedDecl *PrevDecl,
7488 TemplateSpecializationKind PrevTSK,
7489 SourceLocation PrevPointOfInstantiation,
7490 bool &HasNoEffect) {
7491 HasNoEffect = false;
7494 case TSK_Undeclared:
7495 case TSK_ImplicitInstantiation:
7497 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
7498 "previous declaration must be implicit!");
7501 case TSK_ExplicitSpecialization:
7503 case TSK_Undeclared:
7504 case TSK_ExplicitSpecialization:
7505 // Okay, we're just specializing something that is either already
7506 // explicitly specialized or has merely been mentioned without any
7510 case TSK_ImplicitInstantiation:
7511 if (PrevPointOfInstantiation.isInvalid()) {
7512 // The declaration itself has not actually been instantiated, so it is
7513 // still okay to specialize it.
7514 StripImplicitInstantiation(PrevDecl);
7519 case TSK_ExplicitInstantiationDeclaration:
7520 case TSK_ExplicitInstantiationDefinition:
7521 assert((PrevTSK == TSK_ImplicitInstantiation ||
7522 PrevPointOfInstantiation.isValid()) &&
7523 "Explicit instantiation without point of instantiation?");
7525 // C++ [temp.expl.spec]p6:
7526 // If a template, a member template or the member of a class template
7527 // is explicitly specialized then that specialization shall be declared
7528 // before the first use of that specialization that would cause an
7529 // implicit instantiation to take place, in every translation unit in
7530 // which such a use occurs; no diagnostic is required.
7531 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
7532 // Is there any previous explicit specialization declaration?
7533 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
7537 Diag(NewLoc, diag::err_specialization_after_instantiation)
7539 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
7540 << (PrevTSK != TSK_ImplicitInstantiation);
7545 case TSK_ExplicitInstantiationDeclaration:
7547 case TSK_ExplicitInstantiationDeclaration:
7548 // This explicit instantiation declaration is redundant (that's okay).
7552 case TSK_Undeclared:
7553 case TSK_ImplicitInstantiation:
7554 // We're explicitly instantiating something that may have already been
7555 // implicitly instantiated; that's fine.
7558 case TSK_ExplicitSpecialization:
7559 // C++0x [temp.explicit]p4:
7560 // For a given set of template parameters, if an explicit instantiation
7561 // of a template appears after a declaration of an explicit
7562 // specialization for that template, the explicit instantiation has no
7567 case TSK_ExplicitInstantiationDefinition:
7568 // C++0x [temp.explicit]p10:
7569 // If an entity is the subject of both an explicit instantiation
7570 // declaration and an explicit instantiation definition in the same
7571 // translation unit, the definition shall follow the declaration.
7573 diag::err_explicit_instantiation_declaration_after_definition);
7575 // Explicit instantiations following a specialization have no effect and
7576 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
7577 // until a valid name loc is found.
7578 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
7579 diag::note_explicit_instantiation_definition_here);
7584 case TSK_ExplicitInstantiationDefinition:
7586 case TSK_Undeclared:
7587 case TSK_ImplicitInstantiation:
7588 // We're explicitly instantiating something that may have already been
7589 // implicitly instantiated; that's fine.
7592 case TSK_ExplicitSpecialization:
7593 // C++ DR 259, C++0x [temp.explicit]p4:
7594 // For a given set of template parameters, if an explicit
7595 // instantiation of a template appears after a declaration of
7596 // an explicit specialization for that template, the explicit
7597 // instantiation has no effect.
7598 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
7600 Diag(PrevDecl->getLocation(),
7601 diag::note_previous_template_specialization);
7605 case TSK_ExplicitInstantiationDeclaration:
7606 // We're explicity instantiating a definition for something for which we
7607 // were previously asked to suppress instantiations. That's fine.
7609 // C++0x [temp.explicit]p4:
7610 // For a given set of template parameters, if an explicit instantiation
7611 // of a template appears after a declaration of an explicit
7612 // specialization for that template, the explicit instantiation has no
7614 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
7615 // Is there any previous explicit specialization declaration?
7616 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7624 case TSK_ExplicitInstantiationDefinition:
7625 // C++0x [temp.spec]p5:
7626 // For a given template and a given set of template-arguments,
7627 // - an explicit instantiation definition shall appear at most once
7630 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
7631 Diag(NewLoc, (getLangOpts().MSVCCompat)
7632 ? diag::ext_explicit_instantiation_duplicate
7633 : diag::err_explicit_instantiation_duplicate)
7635 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
7636 diag::note_previous_explicit_instantiation);
7642 llvm_unreachable("Missing specialization/instantiation case?");
7645 /// \brief Perform semantic analysis for the given dependent function
7646 /// template specialization.
7648 /// The only possible way to get a dependent function template specialization
7649 /// is with a friend declaration, like so:
7652 /// template \<class T> void foo(T);
7653 /// template \<class T> class A {
7654 /// friend void foo<>(T);
7658 /// There really isn't any useful analysis we can do here, so we
7659 /// just store the information.
7661 Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
7662 const TemplateArgumentListInfo &ExplicitTemplateArgs,
7663 LookupResult &Previous) {
7664 // Remove anything from Previous that isn't a function template in
7665 // the correct context.
7666 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
7667 LookupResult::Filter F = Previous.makeFilter();
7668 while (F.hasNext()) {
7669 NamedDecl *D = F.next()->getUnderlyingDecl();
7670 if (!isa<FunctionTemplateDecl>(D) ||
7671 !FDLookupContext->InEnclosingNamespaceSetOf(
7672 D->getDeclContext()->getRedeclContext()))
7677 // Should this be diagnosed here?
7678 if (Previous.empty()) return true;
7680 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
7681 ExplicitTemplateArgs);
7685 /// \brief Perform semantic analysis for the given function template
7688 /// This routine performs all of the semantic analysis required for an
7689 /// explicit function template specialization. On successful completion,
7690 /// the function declaration \p FD will become a function template
7693 /// \param FD the function declaration, which will be updated to become a
7694 /// function template specialization.
7696 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
7697 /// if any. Note that this may be valid info even when 0 arguments are
7698 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
7699 /// as it anyway contains info on the angle brackets locations.
7701 /// \param Previous the set of declarations that may be specialized by
7702 /// this function specialization.
7703 bool Sema::CheckFunctionTemplateSpecialization(
7704 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
7705 LookupResult &Previous) {
7706 // The set of function template specializations that could match this
7707 // explicit function template specialization.
7708 UnresolvedSet<8> Candidates;
7709 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
7710 /*ForTakingAddress=*/false);
7712 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
7713 ConvertedTemplateArgs;
7715 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
7716 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7718 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
7719 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
7720 // Only consider templates found within the same semantic lookup scope as
7722 if (!FDLookupContext->InEnclosingNamespaceSetOf(
7723 Ovl->getDeclContext()->getRedeclContext()))
7726 // When matching a constexpr member function template specialization
7727 // against the primary template, we don't yet know whether the
7728 // specialization has an implicit 'const' (because we don't know whether
7729 // it will be a static member function until we know which template it
7730 // specializes), so adjust it now assuming it specializes this template.
7731 QualType FT = FD->getType();
7732 if (FD->isConstexpr()) {
7733 CXXMethodDecl *OldMD =
7734 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
7735 if (OldMD && OldMD->isConst()) {
7736 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
7737 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7738 EPI.TypeQuals |= Qualifiers::Const;
7739 FT = Context.getFunctionType(FPT->getReturnType(),
7740 FPT->getParamTypes(), EPI);
7744 TemplateArgumentListInfo Args;
7745 if (ExplicitTemplateArgs)
7746 Args = *ExplicitTemplateArgs;
7748 // C++ [temp.expl.spec]p11:
7749 // A trailing template-argument can be left unspecified in the
7750 // template-id naming an explicit function template specialization
7751 // provided it can be deduced from the function argument type.
7752 // Perform template argument deduction to determine whether we may be
7753 // specializing this template.
7754 // FIXME: It is somewhat wasteful to build
7755 TemplateDeductionInfo Info(FailedCandidates.getLocation());
7756 FunctionDecl *Specialization = nullptr;
7757 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
7758 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
7759 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
7761 // Template argument deduction failed; record why it failed, so
7762 // that we can provide nifty diagnostics.
7763 FailedCandidates.addCandidate().set(
7764 I.getPair(), FunTmpl->getTemplatedDecl(),
7765 MakeDeductionFailureInfo(Context, TDK, Info));
7770 // Target attributes are part of the cuda function signature, so
7771 // the deduced template's cuda target must match that of the
7772 // specialization. Given that C++ template deduction does not
7773 // take target attributes into account, we reject candidates
7774 // here that have a different target.
7775 if (LangOpts.CUDA &&
7776 IdentifyCUDATarget(Specialization,
7777 /* IgnoreImplicitHDAttributes = */ true) !=
7778 IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttributes = */ true)) {
7779 FailedCandidates.addCandidate().set(
7780 I.getPair(), FunTmpl->getTemplatedDecl(),
7781 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
7785 // Record this candidate.
7786 if (ExplicitTemplateArgs)
7787 ConvertedTemplateArgs[Specialization] = std::move(Args);
7788 Candidates.addDecl(Specialization, I.getAccess());
7792 // Find the most specialized function template.
7793 UnresolvedSetIterator Result = getMostSpecialized(
7794 Candidates.begin(), Candidates.end(), FailedCandidates,
7796 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
7797 PDiag(diag::err_function_template_spec_ambiguous)
7798 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
7799 PDiag(diag::note_function_template_spec_matched));
7801 if (Result == Candidates.end())
7804 // Ignore access information; it doesn't figure into redeclaration checking.
7805 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
7807 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
7808 // an explicit specialization (14.8.3) [...] of a concept definition.
7809 if (Specialization->getPrimaryTemplate()->isConcept()) {
7810 Diag(FD->getLocation(), diag::err_concept_specialized)
7811 << 0 /*function*/ << 1 /*explicitly specialized*/;
7812 Diag(Specialization->getLocation(), diag::note_previous_declaration);
7816 FunctionTemplateSpecializationInfo *SpecInfo
7817 = Specialization->getTemplateSpecializationInfo();
7818 assert(SpecInfo && "Function template specialization info missing?");
7820 // Note: do not overwrite location info if previous template
7821 // specialization kind was explicit.
7822 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
7823 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
7824 Specialization->setLocation(FD->getLocation());
7825 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
7826 // function can differ from the template declaration with respect to
7827 // the constexpr specifier.
7828 Specialization->setConstexpr(FD->isConstexpr());
7831 // FIXME: Check if the prior specialization has a point of instantiation.
7832 // If so, we have run afoul of .
7834 // If this is a friend declaration, then we're not really declaring
7835 // an explicit specialization.
7836 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
7838 // Check the scope of this explicit specialization.
7840 CheckTemplateSpecializationScope(*this,
7841 Specialization->getPrimaryTemplate(),
7842 Specialization, FD->getLocation(),
7846 // C++ [temp.expl.spec]p6:
7847 // If a template, a member template or the member of a class template is
7848 // explicitly specialized then that specialization shall be declared
7849 // before the first use of that specialization that would cause an implicit
7850 // instantiation to take place, in every translation unit in which such a
7851 // use occurs; no diagnostic is required.
7852 bool HasNoEffect = false;
7854 CheckSpecializationInstantiationRedecl(FD->getLocation(),
7855 TSK_ExplicitSpecialization,
7857 SpecInfo->getTemplateSpecializationKind(),
7858 SpecInfo->getPointOfInstantiation(),
7862 // Mark the prior declaration as an explicit specialization, so that later
7863 // clients know that this is an explicit specialization.
7865 // Since explicit specializations do not inherit '=delete' from their
7866 // primary function template - check if the 'specialization' that was
7867 // implicitly generated (during template argument deduction for partial
7868 // ordering) from the most specialized of all the function templates that
7869 // 'FD' could have been specializing, has a 'deleted' definition. If so,
7870 // first check that it was implicitly generated during template argument
7871 // deduction by making sure it wasn't referenced, and then reset the deleted
7872 // flag to not-deleted, so that we can inherit that information from 'FD'.
7873 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
7874 !Specialization->getCanonicalDecl()->isReferenced()) {
7876 Specialization->getCanonicalDecl() == Specialization &&
7877 "This must be the only existing declaration of this specialization");
7878 Specialization->setDeletedAsWritten(false);
7880 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
7881 MarkUnusedFileScopedDecl(Specialization);
7884 // Turn the given function declaration into a function template
7885 // specialization, with the template arguments from the previous
7887 // Take copies of (semantic and syntactic) template argument lists.
7888 const TemplateArgumentList* TemplArgs = new (Context)
7889 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
7890 FD->setFunctionTemplateSpecialization(
7891 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
7892 SpecInfo->getTemplateSpecializationKind(),
7893 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
7895 // A function template specialization inherits the target attributes
7896 // of its template. (We require the attributes explicitly in the
7897 // code to match, but a template may have implicit attributes by
7898 // virtue e.g. of being constexpr, and it passes these implicit
7899 // attributes on to its specializations.)
7901 inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
7903 // The "previous declaration" for this function template specialization is
7904 // the prior function template specialization.
7906 Previous.addDecl(Specialization);
7910 /// \brief Perform semantic analysis for the given non-template member
7913 /// This routine performs all of the semantic analysis required for an
7914 /// explicit member function specialization. On successful completion,
7915 /// the function declaration \p FD will become a member function
7918 /// \param Member the member declaration, which will be updated to become a
7921 /// \param Previous the set of declarations, one of which may be specialized
7922 /// by this function specialization; the set will be modified to contain the
7923 /// redeclared member.
7925 Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
7926 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
7928 // Try to find the member we are instantiating.
7929 NamedDecl *FoundInstantiation = nullptr;
7930 NamedDecl *Instantiation = nullptr;
7931 NamedDecl *InstantiatedFrom = nullptr;
7932 MemberSpecializationInfo *MSInfo = nullptr;
7934 if (Previous.empty()) {
7935 // Nowhere to look anyway.
7936 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
7937 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7939 NamedDecl *D = (*I)->getUnderlyingDecl();
7940 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
7941 QualType Adjusted = Function->getType();
7942 if (!hasExplicitCallingConv(Adjusted))
7943 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
7944 if (Context.hasSameType(Adjusted, Method->getType())) {
7945 FoundInstantiation = *I;
7946 Instantiation = Method;
7947 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
7948 MSInfo = Method->getMemberSpecializationInfo();
7953 } else if (isa<VarDecl>(Member)) {
7955 if (Previous.isSingleResult() &&
7956 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
7957 if (PrevVar->isStaticDataMember()) {
7958 FoundInstantiation = Previous.getRepresentativeDecl();
7959 Instantiation = PrevVar;
7960 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
7961 MSInfo = PrevVar->getMemberSpecializationInfo();
7963 } else if (isa<RecordDecl>(Member)) {
7964 CXXRecordDecl *PrevRecord;
7965 if (Previous.isSingleResult() &&
7966 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
7967 FoundInstantiation = Previous.getRepresentativeDecl();
7968 Instantiation = PrevRecord;
7969 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
7970 MSInfo = PrevRecord->getMemberSpecializationInfo();
7972 } else if (isa<EnumDecl>(Member)) {
7974 if (Previous.isSingleResult() &&
7975 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
7976 FoundInstantiation = Previous.getRepresentativeDecl();
7977 Instantiation = PrevEnum;
7978 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
7979 MSInfo = PrevEnum->getMemberSpecializationInfo();
7983 if (!Instantiation) {
7984 // There is no previous declaration that matches. Since member
7985 // specializations are always out-of-line, the caller will complain about
7986 // this mismatch later.
7990 // If this is a friend, just bail out here before we start turning
7991 // things into explicit specializations.
7992 if (Member->getFriendObjectKind() != Decl::FOK_None) {
7993 // Preserve instantiation information.
7994 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
7995 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
7996 cast<CXXMethodDecl>(InstantiatedFrom),
7997 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
7998 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
7999 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
8000 cast<CXXRecordDecl>(InstantiatedFrom),
8001 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
8005 Previous.addDecl(FoundInstantiation);
8009 // Make sure that this is a specialization of a member.
8010 if (!InstantiatedFrom) {
8011 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
8013 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
8017 // C++ [temp.expl.spec]p6:
8018 // If a template, a member template or the member of a class template is
8019 // explicitly specialized then that specialization shall be declared
8020 // before the first use of that specialization that would cause an implicit
8021 // instantiation to take place, in every translation unit in which such a
8022 // use occurs; no diagnostic is required.
8023 assert(MSInfo && "Member specialization info missing?");
8025 bool HasNoEffect = false;
8026 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
8027 TSK_ExplicitSpecialization,
8029 MSInfo->getTemplateSpecializationKind(),
8030 MSInfo->getPointOfInstantiation(),
8034 // Check the scope of this explicit specialization.
8035 if (CheckTemplateSpecializationScope(*this,
8037 Instantiation, Member->getLocation(),
8041 // Note that this is an explicit instantiation of a member.
8042 // the original declaration to note that it is an explicit specialization
8043 // (if it was previously an implicit instantiation). This latter step
8044 // makes bookkeeping easier.
8045 if (isa<FunctionDecl>(Member)) {
8046 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
8047 if (InstantiationFunction->getTemplateSpecializationKind() ==
8048 TSK_ImplicitInstantiation) {
8049 InstantiationFunction->setTemplateSpecializationKind(
8050 TSK_ExplicitSpecialization);
8051 InstantiationFunction->setLocation(Member->getLocation());
8052 // Explicit specializations of member functions of class templates do not
8053 // inherit '=delete' from the member function they are specializing.
8054 if (InstantiationFunction->isDeleted()) {
8055 assert(InstantiationFunction->getCanonicalDecl() ==
8056 InstantiationFunction);
8057 InstantiationFunction->setDeletedAsWritten(false);
8061 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
8062 cast<CXXMethodDecl>(InstantiatedFrom),
8063 TSK_ExplicitSpecialization);
8064 MarkUnusedFileScopedDecl(InstantiationFunction);
8065 } else if (isa<VarDecl>(Member)) {
8066 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
8067 if (InstantiationVar->getTemplateSpecializationKind() ==
8068 TSK_ImplicitInstantiation) {
8069 InstantiationVar->setTemplateSpecializationKind(
8070 TSK_ExplicitSpecialization);
8071 InstantiationVar->setLocation(Member->getLocation());
8074 cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
8075 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8076 MarkUnusedFileScopedDecl(InstantiationVar);
8077 } else if (isa<CXXRecordDecl>(Member)) {
8078 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
8079 if (InstantiationClass->getTemplateSpecializationKind() ==
8080 TSK_ImplicitInstantiation) {
8081 InstantiationClass->setTemplateSpecializationKind(
8082 TSK_ExplicitSpecialization);
8083 InstantiationClass->setLocation(Member->getLocation());
8086 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
8087 cast<CXXRecordDecl>(InstantiatedFrom),
8088 TSK_ExplicitSpecialization);
8090 assert(isa<EnumDecl>(Member) && "Only member enums remain");
8091 EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
8092 if (InstantiationEnum->getTemplateSpecializationKind() ==
8093 TSK_ImplicitInstantiation) {
8094 InstantiationEnum->setTemplateSpecializationKind(
8095 TSK_ExplicitSpecialization);
8096 InstantiationEnum->setLocation(Member->getLocation());
8099 cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
8100 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8103 // Save the caller the trouble of having to figure out which declaration
8104 // this specialization matches.
8106 Previous.addDecl(FoundInstantiation);
8110 /// \brief Check the scope of an explicit instantiation.
8112 /// \returns true if a serious error occurs, false otherwise.
8113 static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
8114 SourceLocation InstLoc,
8115 bool WasQualifiedName) {
8116 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
8117 DeclContext *CurContext = S.CurContext->getRedeclContext();
8119 if (CurContext->isRecord()) {
8120 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
8125 // C++11 [temp.explicit]p3:
8126 // An explicit instantiation shall appear in an enclosing namespace of its
8127 // template. If the name declared in the explicit instantiation is an
8128 // unqualified name, the explicit instantiation shall appear in the
8129 // namespace where its template is declared or, if that namespace is inline
8130 // (7.3.1), any namespace from its enclosing namespace set.
8132 // This is DR275, which we do not retroactively apply to C++98/03.
8133 if (WasQualifiedName) {
8134 if (CurContext->Encloses(OrigContext))
8137 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
8141 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
8142 if (WasQualifiedName)
8144 S.getLangOpts().CPlusPlus11?
8145 diag::err_explicit_instantiation_out_of_scope :
8146 diag::warn_explicit_instantiation_out_of_scope_0x)
8150 S.getLangOpts().CPlusPlus11?
8151 diag::err_explicit_instantiation_unqualified_wrong_namespace :
8152 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
8156 S.getLangOpts().CPlusPlus11?
8157 diag::err_explicit_instantiation_must_be_global :
8158 diag::warn_explicit_instantiation_must_be_global_0x)
8160 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
8164 /// \brief Determine whether the given scope specifier has a template-id in it.
8165 static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
8169 // C++11 [temp.explicit]p3:
8170 // If the explicit instantiation is for a member function, a member class
8171 // or a static data member of a class template specialization, the name of
8172 // the class template specialization in the qualified-id for the member
8173 // name shall be a simple-template-id.
8175 // C++98 has the same restriction, just worded differently.
8176 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
8177 NNS = NNS->getPrefix())
8178 if (const Type *T = NNS->getAsType())
8179 if (isa<TemplateSpecializationType>(T))
8185 /// Make a dllexport or dllimport attr on a class template specialization take
8187 static void dllExportImportClassTemplateSpecialization(
8188 Sema &S, ClassTemplateSpecializationDecl *Def) {
8189 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
8190 assert(A && "dllExportImportClassTemplateSpecialization called "
8191 "on Def without dllexport or dllimport");
8193 // We reject explicit instantiations in class scope, so there should
8194 // never be any delayed exported classes to worry about.
8195 assert(S.DelayedDllExportClasses.empty() &&
8196 "delayed exports present at explicit instantiation");
8197 S.checkClassLevelDLLAttribute(Def);
8199 // Propagate attribute to base class templates.
8200 for (auto &B : Def->bases()) {
8201 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
8202 B.getType()->getAsCXXRecordDecl()))
8203 S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getLocStart());
8206 S.referenceDLLExportedClassMethods();
8209 // Explicit instantiation of a class template specialization
8211 Sema::ActOnExplicitInstantiation(Scope *S,
8212 SourceLocation ExternLoc,
8213 SourceLocation TemplateLoc,
8215 SourceLocation KWLoc,
8216 const CXXScopeSpec &SS,
8217 TemplateTy TemplateD,
8218 SourceLocation TemplateNameLoc,
8219 SourceLocation LAngleLoc,
8220 ASTTemplateArgsPtr TemplateArgsIn,
8221 SourceLocation RAngleLoc,
8222 AttributeList *Attr) {
8223 // Find the class template we're specializing
8224 TemplateName Name = TemplateD.get();
8225 TemplateDecl *TD = Name.getAsTemplateDecl();
8226 // Check that the specialization uses the same tag kind as the
8227 // original template.
8228 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8229 assert(Kind != TTK_Enum &&
8230 "Invalid enum tag in class template explicit instantiation!");
8232 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
8234 if (!ClassTemplate) {
8235 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
8236 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
8237 Diag(TD->getLocation(), diag::note_previous_use);
8241 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
8242 Kind, /*isDefinition*/false, KWLoc,
8243 ClassTemplate->getIdentifier())) {
8244 Diag(KWLoc, diag::err_use_with_wrong_tag)
8246 << FixItHint::CreateReplacement(KWLoc,
8247 ClassTemplate->getTemplatedDecl()->getKindName());
8248 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8249 diag::note_previous_use);
8250 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8253 // C++0x [temp.explicit]p2:
8254 // There are two forms of explicit instantiation: an explicit instantiation
8255 // definition and an explicit instantiation declaration. An explicit
8256 // instantiation declaration begins with the extern keyword. [...]
8257 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
8258 ? TSK_ExplicitInstantiationDefinition
8259 : TSK_ExplicitInstantiationDeclaration;
8261 if (TSK == TSK_ExplicitInstantiationDeclaration) {
8262 // Check for dllexport class template instantiation declarations.
8263 for (AttributeList *A = Attr; A; A = A->getNext()) {
8264 if (A->getKind() == AttributeList::AT_DLLExport) {
8266 diag::warn_attribute_dllexport_explicit_instantiation_decl);
8267 Diag(A->getLoc(), diag::note_attribute);
8272 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
8274 diag::warn_attribute_dllexport_explicit_instantiation_decl);
8275 Diag(A->getLocation(), diag::note_attribute);
8279 // In MSVC mode, dllimported explicit instantiation definitions are treated as
8280 // instantiation declarations for most purposes.
8281 bool DLLImportExplicitInstantiationDef = false;
8282 if (TSK == TSK_ExplicitInstantiationDefinition &&
8283 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
8284 // Check for dllimport class template instantiation definitions.
8286 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
8287 for (AttributeList *A = Attr; A; A = A->getNext()) {
8288 if (A->getKind() == AttributeList::AT_DLLImport)
8290 if (A->getKind() == AttributeList::AT_DLLExport) {
8291 // dllexport trumps dllimport here.
8297 TSK = TSK_ExplicitInstantiationDeclaration;
8298 DLLImportExplicitInstantiationDef = true;
8302 // Translate the parser's template argument list in our AST format.
8303 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
8304 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
8306 // Check that the template argument list is well-formed for this
8308 SmallVector<TemplateArgument, 4> Converted;
8309 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
8310 TemplateArgs, false, Converted))
8313 // Find the class template specialization declaration that
8314 // corresponds to these arguments.
8315 void *InsertPos = nullptr;
8316 ClassTemplateSpecializationDecl *PrevDecl
8317 = ClassTemplate->findSpecialization(Converted, InsertPos);
8319 TemplateSpecializationKind PrevDecl_TSK
8320 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
8322 // C++0x [temp.explicit]p2:
8323 // [...] An explicit instantiation shall appear in an enclosing
8324 // namespace of its template. [...]
8326 // This is C++ DR 275.
8327 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
8331 ClassTemplateSpecializationDecl *Specialization = nullptr;
8333 bool HasNoEffect = false;
8335 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
8336 PrevDecl, PrevDecl_TSK,
8337 PrevDecl->getPointOfInstantiation(),
8341 // Even though HasNoEffect == true means that this explicit instantiation
8342 // has no effect on semantics, we go on to put its syntax in the AST.
8344 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
8345 PrevDecl_TSK == TSK_Undeclared) {
8346 // Since the only prior class template specialization with these
8347 // arguments was referenced but not declared, reuse that
8348 // declaration node as our own, updating the source location
8349 // for the template name to reflect our new declaration.
8350 // (Other source locations will be updated later.)
8351 Specialization = PrevDecl;
8352 Specialization->setLocation(TemplateNameLoc);
8356 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
8357 DLLImportExplicitInstantiationDef) {
8358 // The new specialization might add a dllimport attribute.
8359 HasNoEffect = false;
8363 if (!Specialization) {
8364 // Create a new class template specialization declaration node for
8365 // this explicit specialization.
8367 = ClassTemplateSpecializationDecl::Create(Context, Kind,
8368 ClassTemplate->getDeclContext(),
8369 KWLoc, TemplateNameLoc,
8373 SetNestedNameSpecifier(Specialization, SS);
8375 if (!HasNoEffect && !PrevDecl) {
8376 // Insert the new specialization.
8377 ClassTemplate->AddSpecialization(Specialization, InsertPos);
8381 // Build the fully-sugared type for this explicit instantiation as
8382 // the user wrote in the explicit instantiation itself. This means
8383 // that we'll pretty-print the type retrieved from the
8384 // specialization's declaration the way that the user actually wrote
8385 // the explicit instantiation, rather than formatting the name based
8386 // on the "canonical" representation used to store the template
8387 // arguments in the specialization.
8388 TypeSourceInfo *WrittenTy
8389 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
8391 Context.getTypeDeclType(Specialization));
8392 Specialization->setTypeAsWritten(WrittenTy);
8394 // Set source locations for keywords.
8395 Specialization->setExternLoc(ExternLoc);
8396 Specialization->setTemplateKeywordLoc(TemplateLoc);
8397 Specialization->setBraceRange(SourceRange());
8399 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
8401 ProcessDeclAttributeList(S, Specialization, Attr);
8403 // Add the explicit instantiation into its lexical context. However,
8404 // since explicit instantiations are never found by name lookup, we
8405 // just put it into the declaration context directly.
8406 Specialization->setLexicalDeclContext(CurContext);
8407 CurContext->addDecl(Specialization);
8409 // Syntax is now OK, so return if it has no other effect on semantics.
8411 // Set the template specialization kind.
8412 Specialization->setTemplateSpecializationKind(TSK);
8413 return Specialization;
8416 // C++ [temp.explicit]p3:
8417 // A definition of a class template or class member template
8418 // shall be in scope at the point of the explicit instantiation of
8419 // the class template or class member template.
8421 // This check comes when we actually try to perform the
8423 ClassTemplateSpecializationDecl *Def
8424 = cast_or_null<ClassTemplateSpecializationDecl>(
8425 Specialization->getDefinition());
8427 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
8428 else if (TSK == TSK_ExplicitInstantiationDefinition) {
8429 MarkVTableUsed(TemplateNameLoc, Specialization, true);
8430 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
8433 // Instantiate the members of this class template specialization.
8434 Def = cast_or_null<ClassTemplateSpecializationDecl>(
8435 Specialization->getDefinition());
8437 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
8438 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
8439 // TSK_ExplicitInstantiationDefinition
8440 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
8441 (TSK == TSK_ExplicitInstantiationDefinition ||
8442 DLLImportExplicitInstantiationDef)) {
8443 // FIXME: Need to notify the ASTMutationListener that we did this.
8444 Def->setTemplateSpecializationKind(TSK);
8446 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
8447 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8448 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
8449 // In the MS ABI, an explicit instantiation definition can add a dll
8450 // attribute to a template with a previous instantiation declaration.
8451 // MinGW doesn't allow this.
8452 auto *A = cast<InheritableAttr>(
8453 getDLLAttr(Specialization)->clone(getASTContext()));
8454 A->setInherited(true);
8456 dllExportImportClassTemplateSpecialization(*this, Def);
8460 // Fix a TSK_ImplicitInstantiation followed by a
8461 // TSK_ExplicitInstantiationDefinition
8462 bool NewlyDLLExported =
8463 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
8464 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
8465 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8466 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
8467 // In the MS ABI, an explicit instantiation definition can add a dll
8468 // attribute to a template with a previous implicit instantiation.
8469 // MinGW doesn't allow this. We limit clang to only adding dllexport, to
8470 // avoid potentially strange codegen behavior. For example, if we extend
8471 // this conditional to dllimport, and we have a source file calling a
8472 // method on an implicitly instantiated template class instance and then
8473 // declaring a dllimport explicit instantiation definition for the same
8474 // template class, the codegen for the method call will not respect the
8475 // dllimport, while it will with cl. The Def will already have the DLL
8476 // attribute, since the Def and Specialization will be the same in the
8477 // case of Old_TSK == TSK_ImplicitInstantiation, and we already added the
8478 // attribute to the Specialization; we just need to make it take effect.
8479 assert(Def == Specialization &&
8480 "Def and Specialization should match for implicit instantiation");
8481 dllExportImportClassTemplateSpecialization(*this, Def);
8484 // Set the template specialization kind. Make sure it is set before
8485 // instantiating the members which will trigger ASTConsumer callbacks.
8486 Specialization->setTemplateSpecializationKind(TSK);
8487 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
8490 // Set the template specialization kind.
8491 Specialization->setTemplateSpecializationKind(TSK);
8494 return Specialization;
8497 // Explicit instantiation of a member class of a class template.
8499 Sema::ActOnExplicitInstantiation(Scope *S,
8500 SourceLocation ExternLoc,
8501 SourceLocation TemplateLoc,
8503 SourceLocation KWLoc,
8505 IdentifierInfo *Name,
8506 SourceLocation NameLoc,
8507 AttributeList *Attr) {
8510 bool IsDependent = false;
8511 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
8512 KWLoc, SS, Name, NameLoc, Attr, AS_none,
8513 /*ModulePrivateLoc=*/SourceLocation(),
8514 MultiTemplateParamsArg(), Owned, IsDependent,
8515 SourceLocation(), false, TypeResult(),
8516 /*IsTypeSpecifier*/false);
8517 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
8522 TagDecl *Tag = cast<TagDecl>(TagD);
8523 assert(!Tag->isEnum() && "shouldn't see enumerations here");
8525 if (Tag->isInvalidDecl())
8528 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
8529 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
8531 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
8532 << Context.getTypeDeclType(Record);
8533 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
8537 // C++0x [temp.explicit]p2:
8538 // If the explicit instantiation is for a class or member class, the
8539 // elaborated-type-specifier in the declaration shall include a
8540 // simple-template-id.
8542 // C++98 has the same restriction, just worded differently.
8543 if (!ScopeSpecifierHasTemplateId(SS))
8544 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
8545 << Record << SS.getRange();
8547 // C++0x [temp.explicit]p2:
8548 // There are two forms of explicit instantiation: an explicit instantiation
8549 // definition and an explicit instantiation declaration. An explicit
8550 // instantiation declaration begins with the extern keyword. [...]
8551 TemplateSpecializationKind TSK
8552 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
8553 : TSK_ExplicitInstantiationDeclaration;
8555 // C++0x [temp.explicit]p2:
8556 // [...] An explicit instantiation shall appear in an enclosing
8557 // namespace of its template. [...]
8559 // This is C++ DR 275.
8560 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
8562 // Verify that it is okay to explicitly instantiate here.
8563 CXXRecordDecl *PrevDecl
8564 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
8565 if (!PrevDecl && Record->getDefinition())
8568 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
8569 bool HasNoEffect = false;
8570 assert(MSInfo && "No member specialization information?");
8571 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
8573 MSInfo->getTemplateSpecializationKind(),
8574 MSInfo->getPointOfInstantiation(),
8581 CXXRecordDecl *RecordDef
8582 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
8584 // C++ [temp.explicit]p3:
8585 // A definition of a member class of a class template shall be in scope
8586 // at the point of an explicit instantiation of the member class.
8588 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
8590 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
8591 << 0 << Record->getDeclName() << Record->getDeclContext();
8592 Diag(Pattern->getLocation(), diag::note_forward_declaration)
8596 if (InstantiateClass(NameLoc, Record, Def,
8597 getTemplateInstantiationArgs(Record),
8601 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
8607 // Instantiate all of the members of the class.
8608 InstantiateClassMembers(NameLoc, RecordDef,
8609 getTemplateInstantiationArgs(Record), TSK);
8611 if (TSK == TSK_ExplicitInstantiationDefinition)
8612 MarkVTableUsed(NameLoc, RecordDef, true);
8614 // FIXME: We don't have any representation for explicit instantiations of
8615 // member classes. Such a representation is not needed for compilation, but it
8616 // should be available for clients that want to see all of the declarations in
8621 DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
8622 SourceLocation ExternLoc,
8623 SourceLocation TemplateLoc,
8625 // Explicit instantiations always require a name.
8626 // TODO: check if/when DNInfo should replace Name.
8627 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8628 DeclarationName Name = NameInfo.getName();
8630 if (!D.isInvalidType())
8631 Diag(D.getDeclSpec().getLocStart(),
8632 diag::err_explicit_instantiation_requires_name)
8633 << D.getDeclSpec().getSourceRange()
8634 << D.getSourceRange();
8639 // The scope passed in may not be a decl scope. Zip up the scope tree until
8640 // we find one that is.
8641 while ((S->getFlags() & Scope::DeclScope) == 0 ||
8642 (S->getFlags() & Scope::TemplateParamScope) != 0)
8645 // Determine the type of the declaration.
8646 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
8647 QualType R = T->getType();
8652 // A storage-class-specifier shall not be specified in [...] an explicit
8653 // instantiation (14.7.2) directive.
8654 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
8655 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
8658 } else if (D.getDeclSpec().getStorageClassSpec()
8659 != DeclSpec::SCS_unspecified) {
8660 // Complain about then remove the storage class specifier.
8661 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
8662 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8664 D.getMutableDeclSpec().ClearStorageClassSpecs();
8667 // C++0x [temp.explicit]p1:
8668 // [...] An explicit instantiation of a function template shall not use the
8669 // inline or constexpr specifiers.
8670 // Presumably, this also applies to member functions of class templates as
8672 if (D.getDeclSpec().isInlineSpecified())
8673 Diag(D.getDeclSpec().getInlineSpecLoc(),
8674 getLangOpts().CPlusPlus11 ?
8675 diag::err_explicit_instantiation_inline :
8676 diag::warn_explicit_instantiation_inline_0x)
8677 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8678 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
8679 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
8680 // not already specified.
8681 Diag(D.getDeclSpec().getConstexprSpecLoc(),
8682 diag::err_explicit_instantiation_constexpr);
8684 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8685 // applied only to the definition of a function template or variable template,
8686 // declared in namespace scope.
8687 if (D.getDeclSpec().isConceptSpecified()) {
8688 Diag(D.getDeclSpec().getConceptSpecLoc(),
8689 diag::err_concept_specified_specialization) << 0;
8693 // A deduction guide is not on the list of entities that can be explicitly
8695 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8696 Diag(D.getDeclSpec().getLocStart(), diag::err_deduction_guide_specialized)
8697 << /*explicit instantiation*/ 0;
8701 // C++0x [temp.explicit]p2:
8702 // There are two forms of explicit instantiation: an explicit instantiation
8703 // definition and an explicit instantiation declaration. An explicit
8704 // instantiation declaration begins with the extern keyword. [...]
8705 TemplateSpecializationKind TSK
8706 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
8707 : TSK_ExplicitInstantiationDeclaration;
8709 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
8710 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
8712 if (!R->isFunctionType()) {
8713 // C++ [temp.explicit]p1:
8714 // A [...] static data member of a class template can be explicitly
8715 // instantiated from the member definition associated with its class
8717 // C++1y [temp.explicit]p1:
8718 // A [...] variable [...] template specialization can be explicitly
8719 // instantiated from its template.
8720 if (Previous.isAmbiguous())
8723 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
8724 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
8726 if (!PrevTemplate) {
8727 if (!Prev || !Prev->isStaticDataMember()) {
8728 // We expect to see a data data member here.
8729 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
8731 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
8733 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
8737 if (!Prev->getInstantiatedFromStaticDataMember()) {
8738 // FIXME: Check for explicit specialization?
8739 Diag(D.getIdentifierLoc(),
8740 diag::err_explicit_instantiation_data_member_not_instantiated)
8742 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
8743 // FIXME: Can we provide a note showing where this was declared?
8747 // Explicitly instantiate a variable template.
8749 // C++1y [dcl.spec.auto]p6:
8750 // ... A program that uses auto or decltype(auto) in a context not
8751 // explicitly allowed in this section is ill-formed.
8753 // This includes auto-typed variable template instantiations.
8754 if (R->isUndeducedType()) {
8755 Diag(T->getTypeLoc().getLocStart(),
8756 diag::err_auto_not_allowed_var_inst);
8760 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
8761 // C++1y [temp.explicit]p3:
8762 // If the explicit instantiation is for a variable, the unqualified-id
8763 // in the declaration shall be a template-id.
8764 Diag(D.getIdentifierLoc(),
8765 diag::err_explicit_instantiation_without_template_id)
8767 Diag(PrevTemplate->getLocation(),
8768 diag::note_explicit_instantiation_here);
8772 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
8773 // explicit instantiation (14.8.2) [...] of a concept definition.
8774 if (PrevTemplate->isConcept()) {
8775 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
8776 << 1 /*variable*/ << 0 /*explicitly instantiated*/;
8777 Diag(PrevTemplate->getLocation(), diag::note_previous_declaration);
8781 // Translate the parser's template argument list into our AST format.
8782 TemplateArgumentListInfo TemplateArgs =
8783 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
8785 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
8786 D.getIdentifierLoc(), TemplateArgs);
8787 if (Res.isInvalid())
8790 // Ignore access control bits, we don't need them for redeclaration
8792 Prev = cast<VarDecl>(Res.get());
8795 // C++0x [temp.explicit]p2:
8796 // If the explicit instantiation is for a member function, a member class
8797 // or a static data member of a class template specialization, the name of
8798 // the class template specialization in the qualified-id for the member
8799 // name shall be a simple-template-id.
8801 // C++98 has the same restriction, just worded differently.
8803 // This does not apply to variable template specializations, where the
8804 // template-id is in the unqualified-id instead.
8805 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
8806 Diag(D.getIdentifierLoc(),
8807 diag::ext_explicit_instantiation_without_qualified_id)
8808 << Prev << D.getCXXScopeSpec().getRange();
8810 // Check the scope of this explicit instantiation.
8811 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
8813 // Verify that it is okay to explicitly instantiate here.
8814 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
8815 SourceLocation POI = Prev->getPointOfInstantiation();
8816 bool HasNoEffect = false;
8817 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
8818 PrevTSK, POI, HasNoEffect))
8822 // Instantiate static data member or variable template.
8824 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
8826 // Merge attributes.
8827 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
8828 ProcessDeclAttributeList(S, Prev, Attr);
8830 if (TSK == TSK_ExplicitInstantiationDefinition)
8831 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
8834 // Check the new variable specialization against the parsed input.
8835 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
8836 Diag(T->getTypeLoc().getLocStart(),
8837 diag::err_invalid_var_template_spec_type)
8838 << 0 << PrevTemplate << R << Prev->getType();
8839 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
8840 << 2 << PrevTemplate->getDeclName();
8844 // FIXME: Create an ExplicitInstantiation node?
8845 return (Decl*) nullptr;
8848 // If the declarator is a template-id, translate the parser's template
8849 // argument list into our AST format.
8850 bool HasExplicitTemplateArgs = false;
8851 TemplateArgumentListInfo TemplateArgs;
8852 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
8853 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
8854 HasExplicitTemplateArgs = true;
8857 // C++ [temp.explicit]p1:
8858 // A [...] function [...] can be explicitly instantiated from its template.
8859 // A member function [...] of a class template can be explicitly
8860 // instantiated from the member definition associated with its class
8862 UnresolvedSet<8> Matches;
8863 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
8864 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
8865 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
8867 NamedDecl *Prev = *P;
8868 if (!HasExplicitTemplateArgs) {
8869 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
8870 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
8871 /*AdjustExceptionSpec*/true);
8872 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
8875 Matches.addDecl(Method, P.getAccess());
8876 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
8882 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
8886 TemplateDeductionInfo Info(FailedCandidates.getLocation());
8887 FunctionDecl *Specialization = nullptr;
8888 if (TemplateDeductionResult TDK
8889 = DeduceTemplateArguments(FunTmpl,
8890 (HasExplicitTemplateArgs ? &TemplateArgs
8892 R, Specialization, Info)) {
8893 // Keep track of almost-matches.
8894 FailedCandidates.addCandidate()
8895 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
8896 MakeDeductionFailureInfo(Context, TDK, Info));
8901 // Target attributes are part of the cuda function signature, so
8902 // the cuda target of the instantiated function must match that of its
8903 // template. Given that C++ template deduction does not take
8904 // target attributes into account, we reject candidates here that
8905 // have a different target.
8906 if (LangOpts.CUDA &&
8907 IdentifyCUDATarget(Specialization,
8908 /* IgnoreImplicitHDAttributes = */ true) !=
8909 IdentifyCUDATarget(Attr)) {
8910 FailedCandidates.addCandidate().set(
8911 P.getPair(), FunTmpl->getTemplatedDecl(),
8912 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
8916 Matches.addDecl(Specialization, P.getAccess());
8919 // Find the most specialized function template specialization.
8920 UnresolvedSetIterator Result = getMostSpecialized(
8921 Matches.begin(), Matches.end(), FailedCandidates,
8922 D.getIdentifierLoc(),
8923 PDiag(diag::err_explicit_instantiation_not_known) << Name,
8924 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
8925 PDiag(diag::note_explicit_instantiation_candidate));
8927 if (Result == Matches.end())
8930 // Ignore access control bits, we don't need them for redeclaration checking.
8931 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
8933 // C++11 [except.spec]p4
8934 // In an explicit instantiation an exception-specification may be specified,
8935 // but is not required.
8936 // If an exception-specification is specified in an explicit instantiation
8937 // directive, it shall be compatible with the exception-specifications of
8938 // other declarations of that function.
8939 if (auto *FPT = R->getAs<FunctionProtoType>())
8940 if (FPT->hasExceptionSpec()) {
8942 diag::err_mismatched_exception_spec_explicit_instantiation;
8943 if (getLangOpts().MicrosoftExt)
8944 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
8945 bool Result = CheckEquivalentExceptionSpec(
8946 PDiag(DiagID) << Specialization->getType(),
8947 PDiag(diag::note_explicit_instantiation_here),
8948 Specialization->getType()->getAs<FunctionProtoType>(),
8949 Specialization->getLocation(), FPT, D.getLocStart());
8950 // In Microsoft mode, mismatching exception specifications just cause a
8952 if (!getLangOpts().MicrosoftExt && Result)
8956 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
8957 Diag(D.getIdentifierLoc(),
8958 diag::err_explicit_instantiation_member_function_not_instantiated)
8960 << (Specialization->getTemplateSpecializationKind() ==
8961 TSK_ExplicitSpecialization);
8962 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
8966 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
8967 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
8968 PrevDecl = Specialization;
8971 bool HasNoEffect = false;
8972 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
8974 PrevDecl->getTemplateSpecializationKind(),
8975 PrevDecl->getPointOfInstantiation(),
8979 // FIXME: We may still want to build some representation of this
8980 // explicit specialization.
8982 return (Decl*) nullptr;
8985 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
8987 ProcessDeclAttributeList(S, Specialization, Attr);
8989 if (Specialization->isDefined()) {
8990 // Let the ASTConsumer know that this function has been explicitly
8991 // instantiated now, and its linkage might have changed.
8992 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
8993 } else if (TSK == TSK_ExplicitInstantiationDefinition)
8994 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
8996 // C++0x [temp.explicit]p2:
8997 // If the explicit instantiation is for a member function, a member class
8998 // or a static data member of a class template specialization, the name of
8999 // the class template specialization in the qualified-id for the member
9000 // name shall be a simple-template-id.
9002 // C++98 has the same restriction, just worded differently.
9003 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
9004 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
9005 D.getCXXScopeSpec().isSet() &&
9006 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
9007 Diag(D.getIdentifierLoc(),
9008 diag::ext_explicit_instantiation_without_qualified_id)
9009 << Specialization << D.getCXXScopeSpec().getRange();
9011 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
9012 // explicit instantiation (14.8.2) [...] of a concept definition.
9013 if (FunTmpl && FunTmpl->isConcept() &&
9014 !D.getDeclSpec().isConceptSpecified()) {
9015 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
9016 << 0 /*function*/ << 0 /*explicitly instantiated*/;
9017 Diag(FunTmpl->getLocation(), diag::note_previous_declaration);
9021 CheckExplicitInstantiationScope(*this,
9022 FunTmpl? (NamedDecl *)FunTmpl
9023 : Specialization->getInstantiatedFromMemberFunction(),
9024 D.getIdentifierLoc(),
9025 D.getCXXScopeSpec().isSet());
9027 // FIXME: Create some kind of ExplicitInstantiationDecl here.
9028 return (Decl*) nullptr;
9032 Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
9033 const CXXScopeSpec &SS, IdentifierInfo *Name,
9034 SourceLocation TagLoc, SourceLocation NameLoc) {
9035 // This has to hold, because SS is expected to be defined.
9036 assert(Name && "Expected a name in a dependent tag");
9038 NestedNameSpecifier *NNS = SS.getScopeRep();
9042 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9044 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
9045 Diag(NameLoc, diag::err_dependent_tag_decl)
9046 << (TUK == TUK_Definition) << Kind << SS.getRange();
9050 // Create the resulting type.
9051 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9052 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
9054 // Create type-source location information for this type.
9056 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
9057 TL.setElaboratedKeywordLoc(TagLoc);
9058 TL.setQualifierLoc(SS.getWithLocInContext(Context));
9059 TL.setNameLoc(NameLoc);
9060 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
9064 Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
9065 const CXXScopeSpec &SS, const IdentifierInfo &II,
9066 SourceLocation IdLoc) {
9070 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9072 getLangOpts().CPlusPlus11 ?
9073 diag::warn_cxx98_compat_typename_outside_of_template :
9074 diag::ext_typename_outside_of_template)
9075 << FixItHint::CreateRemoval(TypenameLoc);
9077 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9078 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
9079 TypenameLoc, QualifierLoc, II, IdLoc);
9083 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9084 if (isa<DependentNameType>(T)) {
9085 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
9086 TL.setElaboratedKeywordLoc(TypenameLoc);
9087 TL.setQualifierLoc(QualifierLoc);
9088 TL.setNameLoc(IdLoc);
9090 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
9091 TL.setElaboratedKeywordLoc(TypenameLoc);
9092 TL.setQualifierLoc(QualifierLoc);
9093 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
9096 return CreateParsedType(T, TSI);
9100 Sema::ActOnTypenameType(Scope *S,
9101 SourceLocation TypenameLoc,
9102 const CXXScopeSpec &SS,
9103 SourceLocation TemplateKWLoc,
9104 TemplateTy TemplateIn,
9105 IdentifierInfo *TemplateII,
9106 SourceLocation TemplateIILoc,
9107 SourceLocation LAngleLoc,
9108 ASTTemplateArgsPtr TemplateArgsIn,
9109 SourceLocation RAngleLoc) {
9110 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9112 getLangOpts().CPlusPlus11 ?
9113 diag::warn_cxx98_compat_typename_outside_of_template :
9114 diag::ext_typename_outside_of_template)
9115 << FixItHint::CreateRemoval(TypenameLoc);
9117 // Strangely, non-type results are not ignored by this lookup, so the
9118 // program is ill-formed if it finds an injected-class-name.
9119 if (TypenameLoc.isValid()) {
9121 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
9122 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
9124 diag::ext_out_of_line_qualified_id_type_names_constructor)
9125 << TemplateII << 0 /*injected-class-name used as template name*/
9126 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
9130 // Translate the parser's template argument list in our AST format.
9131 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9132 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
9134 TemplateName Template = TemplateIn.get();
9135 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
9136 // Construct a dependent template specialization type.
9137 assert(DTN && "dependent template has non-dependent name?");
9138 assert(DTN->getQualifier() == SS.getScopeRep());
9139 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
9140 DTN->getQualifier(),
9141 DTN->getIdentifier(),
9144 // Create source-location information for this type.
9145 TypeLocBuilder Builder;
9146 DependentTemplateSpecializationTypeLoc SpecTL
9147 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
9148 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
9149 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
9150 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
9151 SpecTL.setTemplateNameLoc(TemplateIILoc);
9152 SpecTL.setLAngleLoc(LAngleLoc);
9153 SpecTL.setRAngleLoc(RAngleLoc);
9154 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9155 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
9156 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
9159 QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
9163 // Provide source-location information for the template specialization type.
9164 TypeLocBuilder Builder;
9165 TemplateSpecializationTypeLoc SpecTL
9166 = Builder.push<TemplateSpecializationTypeLoc>(T);
9167 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
9168 SpecTL.setTemplateNameLoc(TemplateIILoc);
9169 SpecTL.setLAngleLoc(LAngleLoc);
9170 SpecTL.setRAngleLoc(RAngleLoc);
9171 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9172 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
9174 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
9175 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
9176 TL.setElaboratedKeywordLoc(TypenameLoc);
9177 TL.setQualifierLoc(SS.getWithLocInContext(Context));
9179 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
9180 return CreateParsedType(T, TSI);
9184 /// Determine whether this failed name lookup should be treated as being
9185 /// disabled by a usage of std::enable_if.
9186 static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
9187 SourceRange &CondRange) {
9188 // We must be looking for a ::type...
9189 if (!II.isStr("type"))
9192 // ... within an explicitly-written template specialization...
9193 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
9195 TypeLoc EnableIfTy = NNS.getTypeLoc();
9196 TemplateSpecializationTypeLoc EnableIfTSTLoc =
9197 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
9198 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
9200 const TemplateSpecializationType *EnableIfTST =
9201 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
9203 // ... which names a complete class template declaration...
9204 const TemplateDecl *EnableIfDecl =
9205 EnableIfTST->getTemplateName().getAsTemplateDecl();
9206 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
9209 // ... called "enable_if".
9210 const IdentifierInfo *EnableIfII =
9211 EnableIfDecl->getDeclName().getAsIdentifierInfo();
9212 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
9215 // Assume the first template argument is the condition.
9216 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
9220 /// \brief Build the type that describes a C++ typename specifier,
9221 /// e.g., "typename T::type".
9223 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
9224 SourceLocation KeywordLoc,
9225 NestedNameSpecifierLoc QualifierLoc,
9226 const IdentifierInfo &II,
9227 SourceLocation IILoc) {
9229 SS.Adopt(QualifierLoc);
9231 DeclContext *Ctx = computeDeclContext(SS);
9233 // If the nested-name-specifier is dependent and couldn't be
9234 // resolved to a type, build a typename type.
9235 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
9236 return Context.getDependentNameType(Keyword,
9237 QualifierLoc.getNestedNameSpecifier(),
9241 // If the nested-name-specifier refers to the current instantiation,
9242 // the "typename" keyword itself is superfluous. In C++03, the
9243 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
9244 // allows such extraneous "typename" keywords, and we retroactively
9245 // apply this DR to C++03 code with only a warning. In any case we continue.
9247 if (RequireCompleteDeclContext(SS, Ctx))
9250 DeclarationName Name(&II);
9251 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
9252 LookupQualifiedName(Result, Ctx, SS);
9253 unsigned DiagID = 0;
9254 Decl *Referenced = nullptr;
9255 switch (Result.getResultKind()) {
9256 case LookupResult::NotFound: {
9257 // If we're looking up 'type' within a template named 'enable_if', produce
9258 // a more specific diagnostic.
9259 SourceRange CondRange;
9260 if (isEnableIf(QualifierLoc, II, CondRange)) {
9261 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
9262 << Ctx << CondRange;
9266 DiagID = diag::err_typename_nested_not_found;
9270 case LookupResult::FoundUnresolvedValue: {
9271 // We found a using declaration that is a value. Most likely, the using
9272 // declaration itself is meant to have the 'typename' keyword.
9273 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
9275 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
9276 << Name << Ctx << FullRange;
9277 if (UnresolvedUsingValueDecl *Using
9278 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
9279 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
9280 Diag(Loc, diag::note_using_value_decl_missing_typename)
9281 << FixItHint::CreateInsertion(Loc, "typename ");
9284 // Fall through to create a dependent typename type, from which we can recover
9287 case LookupResult::NotFoundInCurrentInstantiation:
9288 // Okay, it's a member of an unknown instantiation.
9289 return Context.getDependentNameType(Keyword,
9290 QualifierLoc.getNestedNameSpecifier(),
9293 case LookupResult::Found:
9294 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
9295 // C++ [class.qual]p2:
9296 // In a lookup in which function names are not ignored and the
9297 // nested-name-specifier nominates a class C, if the name specified
9298 // after the nested-name-specifier, when looked up in C, is the
9299 // injected-class-name of C [...] then the name is instead considered
9300 // to name the constructor of class C.
9302 // Unlike in an elaborated-type-specifier, function names are not ignored
9303 // in typename-specifier lookup. However, they are ignored in all the
9304 // contexts where we form a typename type with no keyword (that is, in
9305 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
9307 // FIXME: That's not strictly true: mem-initializer-id lookup does not
9308 // ignore functions, but that appears to be an oversight.
9309 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
9310 auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
9311 if (Keyword == ETK_Typename && LookupRD && FoundRD &&
9312 FoundRD->isInjectedClassName() &&
9313 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
9314 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
9315 << &II << 1 << 0 /*'typename' keyword used*/;
9317 // We found a type. Build an ElaboratedType, since the
9318 // typename-specifier was just sugar.
9319 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
9320 return Context.getElaboratedType(Keyword,
9321 QualifierLoc.getNestedNameSpecifier(),
9322 Context.getTypeDeclType(Type));
9325 // C++ [dcl.type.simple]p2:
9326 // A type-specifier of the form
9327 // typename[opt] nested-name-specifier[opt] template-name
9328 // is a placeholder for a deduced class type [...].
9329 if (getLangOpts().CPlusPlus1z) {
9330 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
9331 return Context.getElaboratedType(
9332 Keyword, QualifierLoc.getNestedNameSpecifier(),
9333 Context.getDeducedTemplateSpecializationType(TemplateName(TD),
9334 QualType(), false));
9338 DiagID = diag::err_typename_nested_not_type;
9339 Referenced = Result.getFoundDecl();
9342 case LookupResult::FoundOverloaded:
9343 DiagID = diag::err_typename_nested_not_type;
9344 Referenced = *Result.begin();
9347 case LookupResult::Ambiguous:
9351 // If we get here, it's because name lookup did not find a
9352 // type. Emit an appropriate diagnostic and return an error.
9353 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
9355 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
9357 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
9363 // See Sema::RebuildTypeInCurrentInstantiation
9364 class CurrentInstantiationRebuilder
9365 : public TreeTransform<CurrentInstantiationRebuilder> {
9367 DeclarationName Entity;
9370 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
9372 CurrentInstantiationRebuilder(Sema &SemaRef,
9374 DeclarationName Entity)
9375 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
9376 Loc(Loc), Entity(Entity) { }
9378 /// \brief Determine whether the given type \p T has already been
9381 /// For the purposes of type reconstruction, a type has already been
9382 /// transformed if it is NULL or if it is not dependent.
9383 bool AlreadyTransformed(QualType T) {
9384 return T.isNull() || !T->isDependentType();
9387 /// \brief Returns the location of the entity whose type is being
9389 SourceLocation getBaseLocation() { return Loc; }
9391 /// \brief Returns the name of the entity whose type is being rebuilt.
9392 DeclarationName getBaseEntity() { return Entity; }
9394 /// \brief Sets the "base" location and entity when that
9395 /// information is known based on another transformation.
9396 void setBase(SourceLocation Loc, DeclarationName Entity) {
9398 this->Entity = Entity;
9401 ExprResult TransformLambdaExpr(LambdaExpr *E) {
9402 // Lambdas never need to be transformed.
9406 } // end anonymous namespace
9408 /// \brief Rebuilds a type within the context of the current instantiation.
9410 /// The type \p T is part of the type of an out-of-line member definition of
9411 /// a class template (or class template partial specialization) that was parsed
9412 /// and constructed before we entered the scope of the class template (or
9413 /// partial specialization thereof). This routine will rebuild that type now
9414 /// that we have entered the declarator's scope, which may produce different
9415 /// canonical types, e.g.,
9418 /// template<typename T>
9420 /// typedef T* pointer;
9424 /// template<typename T>
9425 /// typename X<T>::pointer X<T>::data() { ... }
9428 /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
9429 /// since we do not know that we can look into X<T> when we parsed the type.
9430 /// This function will rebuild the type, performing the lookup of "pointer"
9431 /// in X<T> and returning an ElaboratedType whose canonical type is the same
9432 /// as the canonical type of T*, allowing the return types of the out-of-line
9433 /// definition and the declaration to match.
9434 TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
9436 DeclarationName Name) {
9437 if (!T || !T->getType()->isDependentType())
9440 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
9441 return Rebuilder.TransformType(T);
9444 ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
9445 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
9447 return Rebuilder.TransformExpr(E);
9450 bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
9454 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9455 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
9457 NestedNameSpecifierLoc Rebuilt
9458 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
9466 /// \brief Rebuild the template parameters now that we know we're in a current
9468 bool Sema::RebuildTemplateParamsInCurrentInstantiation(
9469 TemplateParameterList *Params) {
9470 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
9471 Decl *Param = Params->getParam(I);
9473 // There is nothing to rebuild in a type parameter.
9474 if (isa<TemplateTypeParmDecl>(Param))
9477 // Rebuild the template parameter list of a template template parameter.
9478 if (TemplateTemplateParmDecl *TTP
9479 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
9480 if (RebuildTemplateParamsInCurrentInstantiation(
9481 TTP->getTemplateParameters()))
9487 // Rebuild the type of a non-type template parameter.
9488 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
9489 TypeSourceInfo *NewTSI
9490 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
9491 NTTP->getLocation(),
9492 NTTP->getDeclName());
9496 if (NewTSI != NTTP->getTypeSourceInfo()) {
9497 NTTP->setTypeSourceInfo(NewTSI);
9498 NTTP->setType(NewTSI->getType());
9505 /// \brief Produces a formatted string that describes the binding of
9506 /// template parameters to template arguments.
9508 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
9509 const TemplateArgumentList &Args) {
9510 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
9514 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
9515 const TemplateArgument *Args,
9517 SmallString<128> Str;
9518 llvm::raw_svector_ostream Out(Str);
9520 if (!Params || Params->size() == 0 || NumArgs == 0)
9521 return std::string();
9523 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
9532 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
9533 Out << Id->getName();
9539 Args[I].print(getPrintingPolicy(), Out);
9546 void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
9547 CachedTokens &Toks) {
9551 auto LPT = llvm::make_unique<LateParsedTemplate>();
9553 // Take tokens to avoid allocations
9554 LPT->Toks.swap(Toks);
9556 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
9558 FD->setLateTemplateParsed(true);
9561 void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
9564 FD->setLateTemplateParsed(false);
9567 bool Sema::IsInsideALocalClassWithinATemplateFunction() {
9568 DeclContext *DC = CurContext;
9571 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
9572 const FunctionDecl *FD = RD->isLocalClass();
9573 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
9574 } else if (DC->isTranslationUnit() || DC->isNamespace())
9577 DC = DC->getParent();
9583 /// \brief Walk the path from which a declaration was instantiated, and check
9584 /// that every explicit specialization along that path is visible. This enforces
9585 /// C++ [temp.expl.spec]/6:
9587 /// If a template, a member template or a member of a class template is
9588 /// explicitly specialized then that specialization shall be declared before
9589 /// the first use of that specialization that would cause an implicit
9590 /// instantiation to take place, in every translation unit in which such a
9591 /// use occurs; no diagnostic is required.
9593 /// and also C++ [temp.class.spec]/1:
9595 /// A partial specialization shall be declared before the first use of a
9596 /// class template specialization that would make use of the partial
9597 /// specialization as the result of an implicit or explicit instantiation
9598 /// in every translation unit in which such a use occurs; no diagnostic is
9600 class ExplicitSpecializationVisibilityChecker {
9603 llvm::SmallVector<Module *, 8> Modules;
9606 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
9609 void check(NamedDecl *ND) {
9610 if (auto *FD = dyn_cast<FunctionDecl>(ND))
9611 return checkImpl(FD);
9612 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
9613 return checkImpl(RD);
9614 if (auto *VD = dyn_cast<VarDecl>(ND))
9615 return checkImpl(VD);
9616 if (auto *ED = dyn_cast<EnumDecl>(ND))
9617 return checkImpl(ED);
9621 void diagnose(NamedDecl *D, bool IsPartialSpec) {
9622 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
9623 : Sema::MissingImportKind::ExplicitSpecialization;
9624 const bool Recover = true;
9626 // If we got a custom set of modules (because only a subset of the
9627 // declarations are interesting), use them, otherwise let
9628 // diagnoseMissingImport intelligently pick some.
9629 if (Modules.empty())
9630 S.diagnoseMissingImport(Loc, D, Kind, Recover);
9632 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
9635 // Check a specific declaration. There are three problematic cases:
9637 // 1) The declaration is an explicit specialization of a template
9639 // 2) The declaration is an explicit specialization of a member of an
9641 // 3) The declaration is an instantiation of a template, and that template
9642 // is an explicit specialization of a member of a templated class.
9644 // We don't need to go any deeper than that, as the instantiation of the
9645 // surrounding class / etc is not triggered by whatever triggered this
9646 // instantiation, and thus should be checked elsewhere.
9647 template<typename SpecDecl>
9648 void checkImpl(SpecDecl *Spec) {
9649 bool IsHiddenExplicitSpecialization = false;
9650 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
9651 IsHiddenExplicitSpecialization =
9652 Spec->getMemberSpecializationInfo()
9653 ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
9654 : !S.hasVisibleDeclaration(Spec);
9656 checkInstantiated(Spec);
9659 if (IsHiddenExplicitSpecialization)
9660 diagnose(Spec->getMostRecentDecl(), false);
9663 void checkInstantiated(FunctionDecl *FD) {
9664 if (auto *TD = FD->getPrimaryTemplate())
9668 void checkInstantiated(CXXRecordDecl *RD) {
9669 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
9673 auto From = SD->getSpecializedTemplateOrPartial();
9674 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
9677 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
9678 if (!S.hasVisibleDeclaration(TD))
9684 void checkInstantiated(VarDecl *RD) {
9685 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
9689 auto From = SD->getSpecializedTemplateOrPartial();
9690 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
9693 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
9694 if (!S.hasVisibleDeclaration(TD))
9700 void checkInstantiated(EnumDecl *FD) {}
9702 template<typename TemplDecl>
9703 void checkTemplate(TemplDecl *TD) {
9704 if (TD->isMemberSpecialization()) {
9705 if (!S.hasVisibleMemberSpecialization(TD, &Modules))
9706 diagnose(TD->getMostRecentDecl(), false);
9710 } // end anonymous namespace
9712 void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
9713 if (!getLangOpts().Modules)
9716 ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
9719 /// \brief Check whether a template partial specialization that we've discovered
9720 /// is hidden, and produce suitable diagnostics if so.
9721 void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
9723 llvm::SmallVector<Module *, 8> Modules;
9724 if (!hasVisibleDeclaration(Spec, &Modules))
9725 diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
9726 MissingImportKind::PartialSpecialization,