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 /// [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 /// 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();
108 // 'using Dependent::foo;' can resolve to a template name.
109 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
110 // injected-class-name).
111 if (isa<UnresolvedUsingValueDecl>(D))
117 void Sema::FilterAcceptableTemplateNames(LookupResult &R,
118 bool AllowFunctionTemplates) {
119 // The set of class templates we've already seen.
120 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
121 LookupResult::Filter filter = R.makeFilter();
122 while (filter.hasNext()) {
123 NamedDecl *Orig = filter.next();
124 NamedDecl *Repl = isAcceptableTemplateName(Context, Orig,
125 AllowFunctionTemplates);
128 else if (Repl != Orig) {
130 // C++ [temp.local]p3:
131 // A lookup that finds an injected-class-name (10.2) can result in an
132 // ambiguity in certain cases (for example, if it is found in more than
133 // one base class). If all of the injected-class-names that are found
134 // refer to specializations of the same class template, and if the name
135 // is used as a template-name, the reference refers to the class
136 // template itself and not a specialization thereof, and is not
138 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
139 if (!ClassTemplates.insert(ClassTmpl).second) {
144 // FIXME: we promote access to public here as a workaround to
145 // the fact that LookupResult doesn't let us remember that we
146 // found this template through a particular injected class name,
147 // which means we end up doing nasty things to the invariants.
148 // Pretending that access is public is *much* safer.
149 filter.replace(Repl, AS_public);
155 bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
156 bool AllowFunctionTemplates) {
157 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
158 if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
164 TemplateNameKind Sema::isTemplateName(Scope *S,
166 bool hasTemplateKeyword,
167 const UnqualifiedId &Name,
168 ParsedType ObjectTypePtr,
169 bool EnteringContext,
170 TemplateTy &TemplateResult,
171 bool &MemberOfUnknownSpecialization) {
172 assert(getLangOpts().CPlusPlus && "No template names in C!");
174 DeclarationName TName;
175 MemberOfUnknownSpecialization = false;
177 switch (Name.getKind()) {
178 case UnqualifiedIdKind::IK_Identifier:
179 TName = DeclarationName(Name.Identifier);
182 case UnqualifiedIdKind::IK_OperatorFunctionId:
183 TName = Context.DeclarationNames.getCXXOperatorName(
184 Name.OperatorFunctionId.Operator);
187 case UnqualifiedIdKind::IK_LiteralOperatorId:
188 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
192 return TNK_Non_template;
195 QualType ObjectType = ObjectTypePtr.get();
197 LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
198 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
199 MemberOfUnknownSpecialization))
200 return TNK_Non_template;
201 if (R.empty()) return TNK_Non_template;
202 if (R.isAmbiguous()) {
203 // Suppress diagnostics; we'll redo this lookup later.
204 R.suppressDiagnostics();
206 // FIXME: we might have ambiguous templates, in which case we
207 // should at least parse them properly!
208 return TNK_Non_template;
211 TemplateName Template;
212 TemplateNameKind TemplateKind;
214 unsigned ResultCount = R.end() - R.begin();
215 if (ResultCount > 1) {
216 // We assume that we'll preserve the qualifier from a function
217 // template name in other ways.
218 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
219 TemplateKind = TNK_Function_template;
221 // We'll do this lookup again later.
222 R.suppressDiagnostics();
223 } else if (isa<UnresolvedUsingValueDecl>((*R.begin())->getUnderlyingDecl())) {
224 // We don't yet know whether this is a template-name or not.
225 MemberOfUnknownSpecialization = true;
226 return TNK_Non_template;
228 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
230 if (SS.isSet() && !SS.isInvalid()) {
231 NestedNameSpecifier *Qualifier = SS.getScopeRep();
232 Template = Context.getQualifiedTemplateName(Qualifier,
233 hasTemplateKeyword, TD);
235 Template = TemplateName(TD);
238 if (isa<FunctionTemplateDecl>(TD)) {
239 TemplateKind = TNK_Function_template;
241 // We'll do this lookup again later.
242 R.suppressDiagnostics();
244 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
245 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
246 isa<BuiltinTemplateDecl>(TD));
248 isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template;
252 TemplateResult = TemplateTy::make(Template);
256 bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
257 SourceLocation NameLoc,
258 ParsedTemplateTy *Template) {
260 bool MemberOfUnknownSpecialization = false;
262 // We could use redeclaration lookup here, but we don't need to: the
263 // syntactic form of a deduction guide is enough to identify it even
264 // if we can't look up the template name at all.
265 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
266 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
267 /*EnteringContext*/ false,
268 MemberOfUnknownSpecialization))
271 if (R.empty()) return false;
272 if (R.isAmbiguous()) {
273 // FIXME: Diagnose an ambiguity if we find at least one template.
274 R.suppressDiagnostics();
278 // We only treat template-names that name type templates as valid deduction
280 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
281 if (!TD || !getAsTypeTemplateDecl(TD))
285 *Template = TemplateTy::make(TemplateName(TD));
289 bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
290 SourceLocation IILoc,
292 const CXXScopeSpec *SS,
293 TemplateTy &SuggestedTemplate,
294 TemplateNameKind &SuggestedKind) {
295 // We can't recover unless there's a dependent scope specifier preceding the
297 // FIXME: Typo correction?
298 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
299 computeDeclContext(*SS))
302 // The code is missing a 'template' keyword prior to the dependent template
304 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
305 Diag(IILoc, diag::err_template_kw_missing)
306 << Qualifier << II.getName()
307 << FixItHint::CreateInsertion(IILoc, "template ");
309 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
310 SuggestedKind = TNK_Dependent_template_name;
314 bool Sema::LookupTemplateName(LookupResult &Found,
315 Scope *S, CXXScopeSpec &SS,
317 bool EnteringContext,
318 bool &MemberOfUnknownSpecialization,
319 SourceLocation TemplateKWLoc) {
320 // Determine where to perform name lookup
321 MemberOfUnknownSpecialization = false;
322 DeclContext *LookupCtx = nullptr;
323 bool IsDependent = false;
324 if (!ObjectType.isNull()) {
325 // This nested-name-specifier occurs in a member access expression, e.g.,
326 // x->B::f, and we are looking into the type of the object.
327 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
328 LookupCtx = computeDeclContext(ObjectType);
329 IsDependent = !LookupCtx;
330 assert((IsDependent || !ObjectType->isIncompleteType() ||
331 ObjectType->castAs<TagType>()->isBeingDefined()) &&
332 "Caller should have completed object type");
334 // Template names cannot appear inside an Objective-C class or object type.
335 if (ObjectType->isObjCObjectOrInterfaceType()) {
339 } else if (SS.isSet()) {
340 // This nested-name-specifier occurs after another nested-name-specifier,
341 // so long into the context associated with the prior nested-name-specifier.
342 LookupCtx = computeDeclContext(SS, EnteringContext);
343 IsDependent = !LookupCtx;
345 // The declaration context must be complete.
346 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
350 bool ObjectTypeSearchedInScope = false;
351 bool AllowFunctionTemplatesInLookup = true;
353 // Perform "qualified" name lookup into the declaration context we
354 // computed, which is either the type of the base of a member access
355 // expression or the declaration context associated with a prior
356 // nested-name-specifier.
357 LookupQualifiedName(Found, LookupCtx);
359 // FIXME: The C++ standard does not clearly specify what happens in the
360 // case where the object type is dependent, and implementations vary. In
361 // Clang, we treat a name after a . or -> as a template-name if lookup
362 // finds a non-dependent member or member of the current instantiation that
363 // is a type template, or finds no such members and lookup in the context
364 // of the postfix-expression finds a type template. In the latter case, the
365 // name is nonetheless dependent, and we may resolve it to a member of an
366 // unknown specialization when we come to instantiate the template.
367 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
370 if (!SS.isSet() && (ObjectType.isNull() || Found.empty())) {
371 // C++ [basic.lookup.classref]p1:
372 // In a class member access expression (5.2.5), if the . or -> token is
373 // immediately followed by an identifier followed by a <, the
374 // identifier must be looked up to determine whether the < is the
375 // beginning of a template argument list (14.2) or a less-than operator.
376 // The identifier is first looked up in the class of the object
377 // expression. If the identifier is not found, it is then looked up in
378 // the context of the entire postfix-expression and shall name a class
381 LookupName(Found, S);
383 if (!ObjectType.isNull()) {
384 // FIXME: We should filter out all non-type templates here, particularly
385 // variable templates and concepts. But the exclusion of alias templates
386 // and template template parameters is a wording defect.
387 AllowFunctionTemplatesInLookup = false;
388 ObjectTypeSearchedInScope = true;
391 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
394 if (Found.empty() && !IsDependent) {
395 // If we did not find any names, attempt to correct any typos.
396 DeclarationName Name = Found.getLookupName();
398 // Simple filter callback that, for keywords, only accepts the C++ *_cast
399 auto FilterCCC = llvm::make_unique<CorrectionCandidateCallback>();
400 FilterCCC->WantTypeSpecifiers = false;
401 FilterCCC->WantExpressionKeywords = false;
402 FilterCCC->WantRemainingKeywords = false;
403 FilterCCC->WantCXXNamedCasts = true;
404 if (TypoCorrection Corrected = CorrectTypo(
405 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS,
406 std::move(FilterCCC), CTK_ErrorRecovery, LookupCtx)) {
407 Found.setLookupName(Corrected.getCorrection());
408 if (auto *ND = Corrected.getFoundDecl())
410 FilterAcceptableTemplateNames(Found);
411 if (!Found.empty()) {
413 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
414 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
415 Name.getAsString() == CorrectedStr;
416 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
417 << Name << LookupCtx << DroppedSpecifier
420 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
424 Found.setLookupName(Name);
428 NamedDecl *ExampleLookupResult =
429 Found.empty() ? nullptr : Found.getRepresentativeDecl();
430 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
433 MemberOfUnknownSpecialization = true;
437 // If a 'template' keyword was used, a lookup that finds only non-template
438 // names is an error.
439 if (ExampleLookupResult && TemplateKWLoc.isValid()) {
440 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
441 << Found.getLookupName() << SS.getRange();
442 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
443 diag::note_template_kw_refers_to_non_template)
444 << Found.getLookupName();
451 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
452 !getLangOpts().CPlusPlus11) {
453 // C++03 [basic.lookup.classref]p1:
454 // [...] If the lookup in the class of the object expression finds a
455 // template, the name is also looked up in the context of the entire
456 // postfix-expression and [...]
458 // Note: C++11 does not perform this second lookup.
459 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
461 LookupName(FoundOuter, S);
462 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
464 if (FoundOuter.empty()) {
465 // - if the name is not found, the name found in the class of the
466 // object expression is used, otherwise
467 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
468 FoundOuter.isAmbiguous()) {
469 // - if the name is found in the context of the entire
470 // postfix-expression and does not name a class template, the name
471 // found in the class of the object expression is used, otherwise
473 } else if (!Found.isSuppressingDiagnostics()) {
474 // - if the name found is a class template, it must refer to the same
475 // entity as the one found in the class of the object expression,
476 // otherwise the program is ill-formed.
477 if (!Found.isSingleResult() ||
478 Found.getFoundDecl()->getCanonicalDecl()
479 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
480 Diag(Found.getNameLoc(),
481 diag::ext_nested_name_member_ref_lookup_ambiguous)
482 << Found.getLookupName()
484 Diag(Found.getRepresentativeDecl()->getLocation(),
485 diag::note_ambig_member_ref_object_type)
487 Diag(FoundOuter.getFoundDecl()->getLocation(),
488 diag::note_ambig_member_ref_scope);
490 // Recover by taking the template that we found in the object
491 // expression's type.
499 void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
501 SourceLocation Greater) {
502 if (TemplateName.isInvalid())
505 DeclarationNameInfo NameInfo;
507 LookupNameKind LookupKind;
509 DeclContext *LookupCtx = nullptr;
510 NamedDecl *Found = nullptr;
511 bool MissingTemplateKeyword = false;
513 // Figure out what name we looked up.
514 if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
515 NameInfo = DRE->getNameInfo();
516 SS.Adopt(DRE->getQualifierLoc());
517 LookupKind = LookupOrdinaryName;
518 Found = DRE->getFoundDecl();
519 } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
520 NameInfo = ME->getMemberNameInfo();
521 SS.Adopt(ME->getQualifierLoc());
522 LookupKind = LookupMemberName;
523 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
524 Found = ME->getMemberDecl();
525 } else if (auto *DSDRE =
526 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
527 NameInfo = DSDRE->getNameInfo();
528 SS.Adopt(DSDRE->getQualifierLoc());
529 MissingTemplateKeyword = true;
530 } else if (auto *DSME =
531 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
532 NameInfo = DSME->getMemberNameInfo();
533 SS.Adopt(DSME->getQualifierLoc());
534 MissingTemplateKeyword = true;
536 llvm_unreachable("unexpected kind of potential template name");
539 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
541 if (MissingTemplateKeyword) {
542 Diag(NameInfo.getLocStart(), diag::err_template_kw_missing)
543 << "" << NameInfo.getName().getAsString()
544 << SourceRange(Less, Greater);
548 // Try to correct the name by looking for templates and C++ named casts.
549 struct TemplateCandidateFilter : CorrectionCandidateCallback {
550 TemplateCandidateFilter() {
551 WantTypeSpecifiers = false;
552 WantExpressionKeywords = false;
553 WantRemainingKeywords = false;
554 WantCXXNamedCasts = true;
556 bool ValidateCandidate(const TypoCorrection &Candidate) override {
557 if (auto *ND = Candidate.getCorrectionDecl())
558 return isAcceptableTemplateName(ND->getASTContext(), ND, true);
559 return Candidate.isKeyword();
563 DeclarationName Name = NameInfo.getName();
564 if (TypoCorrection Corrected =
565 CorrectTypo(NameInfo, LookupKind, S, &SS,
566 llvm::make_unique<TemplateCandidateFilter>(),
567 CTK_ErrorRecovery, LookupCtx)) {
568 auto *ND = Corrected.getFoundDecl();
570 ND = isAcceptableTemplateName(Context, ND,
571 /*AllowFunctionTemplates*/ true);
572 if (ND || Corrected.isKeyword()) {
574 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
575 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
576 Name.getAsString() == CorrectedStr;
577 diagnoseTypo(Corrected,
578 PDiag(diag::err_non_template_in_member_template_id_suggest)
579 << Name << LookupCtx << DroppedSpecifier
580 << SS.getRange(), false);
582 diagnoseTypo(Corrected,
583 PDiag(diag::err_non_template_in_template_id_suggest)
587 Diag(Found->getLocation(),
588 diag::note_non_template_in_template_id_found);
593 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
594 << Name << SourceRange(Less, Greater);
596 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
599 /// ActOnDependentIdExpression - Handle a dependent id-expression that
600 /// was just parsed. This is only possible with an explicit scope
601 /// specifier naming a dependent type.
603 Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
604 SourceLocation TemplateKWLoc,
605 const DeclarationNameInfo &NameInfo,
606 bool isAddressOfOperand,
607 const TemplateArgumentListInfo *TemplateArgs) {
608 DeclContext *DC = getFunctionLevelDeclContext();
610 // C++11 [expr.prim.general]p12:
611 // An id-expression that denotes a non-static data member or non-static
612 // member function of a class can only be used:
614 // - if that id-expression denotes a non-static data member and it
615 // appears in an unevaluated operand.
617 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
618 // CXXDependentScopeMemberExpr. The former can instantiate to either
619 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
620 // always a MemberExpr.
621 bool MightBeCxx11UnevalField =
622 getLangOpts().CPlusPlus11 && isUnevaluatedContext();
624 // Check if the nested name specifier is an enum type.
626 if (NestedNameSpecifier *NNS = SS.getScopeRep())
627 IsEnum = dyn_cast_or_null<EnumType>(NNS->getAsType());
629 if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
630 isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
631 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
633 // Since the 'this' expression is synthesized, we don't need to
634 // perform the double-lookup check.
635 NamedDecl *FirstQualifierInScope = nullptr;
637 return CXXDependentScopeMemberExpr::Create(
638 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
639 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
640 FirstQualifierInScope, NameInfo, TemplateArgs);
643 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
647 Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
648 SourceLocation TemplateKWLoc,
649 const DeclarationNameInfo &NameInfo,
650 const TemplateArgumentListInfo *TemplateArgs) {
651 return DependentScopeDeclRefExpr::Create(
652 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
657 /// Determine whether we would be unable to instantiate this template (because
658 /// it either has no definition, or is in the process of being instantiated).
659 bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
660 NamedDecl *Instantiation,
661 bool InstantiatedFromMember,
662 const NamedDecl *Pattern,
663 const NamedDecl *PatternDef,
664 TemplateSpecializationKind TSK,
665 bool Complain /*= true*/) {
666 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
667 isa<VarDecl>(Instantiation));
669 bool IsEntityBeingDefined = false;
670 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
671 IsEntityBeingDefined = TD->isBeingDefined();
673 if (PatternDef && !IsEntityBeingDefined) {
674 NamedDecl *SuggestedDef = nullptr;
675 if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
676 /*OnlyNeedComplete*/false)) {
677 // If we're allowed to diagnose this and recover, do so.
678 bool Recover = Complain && !isSFINAEContext();
680 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
681 Sema::MissingImportKind::Definition, Recover);
687 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
690 llvm::Optional<unsigned> Note;
691 QualType InstantiationTy;
692 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
693 InstantiationTy = Context.getTypeDeclType(TD);
695 Diag(PointOfInstantiation,
696 diag::err_template_instantiate_within_definition)
697 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
699 // Not much point in noting the template declaration here, since
700 // we're lexically inside it.
701 Instantiation->setInvalidDecl();
702 } else if (InstantiatedFromMember) {
703 if (isa<FunctionDecl>(Instantiation)) {
704 Diag(PointOfInstantiation,
705 diag::err_explicit_instantiation_undefined_member)
706 << /*member function*/ 1 << Instantiation->getDeclName()
707 << Instantiation->getDeclContext();
708 Note = diag::note_explicit_instantiation_here;
710 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
711 Diag(PointOfInstantiation,
712 diag::err_implicit_instantiate_member_undefined)
714 Note = diag::note_member_declared_at;
717 if (isa<FunctionDecl>(Instantiation)) {
718 Diag(PointOfInstantiation,
719 diag::err_explicit_instantiation_undefined_func_template)
721 Note = diag::note_explicit_instantiation_here;
722 } else if (isa<TagDecl>(Instantiation)) {
723 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
724 << (TSK != TSK_ImplicitInstantiation)
726 Note = diag::note_template_decl_here;
728 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
729 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
730 Diag(PointOfInstantiation,
731 diag::err_explicit_instantiation_undefined_var_template)
733 Instantiation->setInvalidDecl();
735 Diag(PointOfInstantiation,
736 diag::err_explicit_instantiation_undefined_member)
737 << /*static data member*/ 2 << Instantiation->getDeclName()
738 << Instantiation->getDeclContext();
739 Note = diag::note_explicit_instantiation_here;
742 if (Note) // Diagnostics were emitted.
743 Diag(Pattern->getLocation(), Note.getValue());
745 // In general, Instantiation isn't marked invalid to get more than one
746 // error for multiple undefined instantiations. But the code that does
747 // explicit declaration -> explicit definition conversion can't handle
748 // invalid declarations, so mark as invalid in that case.
749 if (TSK == TSK_ExplicitInstantiationDeclaration)
750 Instantiation->setInvalidDecl();
754 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
755 /// that the template parameter 'PrevDecl' is being shadowed by a new
756 /// declaration at location Loc. Returns true to indicate that this is
757 /// an error, and false otherwise.
758 void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
759 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
761 // Microsoft Visual C++ permits template parameters to be shadowed.
762 if (getLangOpts().MicrosoftExt)
765 // C++ [temp.local]p4:
766 // A template-parameter shall not be redeclared within its
767 // scope (including nested scopes).
768 Diag(Loc, diag::err_template_param_shadow)
769 << cast<NamedDecl>(PrevDecl)->getDeclName();
770 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
773 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
774 /// the parameter D to reference the templated declaration and return a pointer
775 /// to the template declaration. Otherwise, do nothing to D and return null.
776 TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
777 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
778 D = Temp->getTemplatedDecl();
784 ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
785 SourceLocation EllipsisLoc) const {
786 assert(Kind == Template &&
787 "Only template template arguments can be pack expansions here");
788 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
789 "Template template argument pack expansion without packs");
790 ParsedTemplateArgument Result(*this);
791 Result.EllipsisLoc = EllipsisLoc;
795 static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
796 const ParsedTemplateArgument &Arg) {
798 switch (Arg.getKind()) {
799 case ParsedTemplateArgument::Type: {
801 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
803 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
804 return TemplateArgumentLoc(TemplateArgument(T), DI);
807 case ParsedTemplateArgument::NonType: {
808 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
809 return TemplateArgumentLoc(TemplateArgument(E), E);
812 case ParsedTemplateArgument::Template: {
813 TemplateName Template = Arg.getAsTemplate().get();
814 TemplateArgument TArg;
815 if (Arg.getEllipsisLoc().isValid())
816 TArg = TemplateArgument(Template, Optional<unsigned int>());
819 return TemplateArgumentLoc(TArg,
820 Arg.getScopeSpec().getWithLocInContext(
823 Arg.getEllipsisLoc());
827 llvm_unreachable("Unhandled parsed template argument");
830 /// Translates template arguments as provided by the parser
831 /// into template arguments used by semantic analysis.
832 void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
833 TemplateArgumentListInfo &TemplateArgs) {
834 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
835 TemplateArgs.addArgument(translateTemplateArgument(*this,
839 static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
841 IdentifierInfo *Name) {
842 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
843 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
844 if (PrevDecl && PrevDecl->isTemplateParameter())
845 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
848 /// Convert a parsed type into a parsed template argument. This is mostly
849 /// trivial, except that we may have parsed a C++17 deduced class template
850 /// specialization type, in which case we should form a template template
851 /// argument instead of a type template argument.
852 ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) {
853 TypeSourceInfo *TInfo;
854 QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
856 return ParsedTemplateArgument();
857 assert(TInfo && "template argument with no location");
859 // If we might have formed a deduced template specialization type, convert
860 // it to a template template argument.
861 if (getLangOpts().CPlusPlus17) {
862 TypeLoc TL = TInfo->getTypeLoc();
863 SourceLocation EllipsisLoc;
864 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
865 EllipsisLoc = PET.getEllipsisLoc();
866 TL = PET.getPatternLoc();
870 if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
871 SS.Adopt(ET.getQualifierLoc());
872 TL = ET.getNamedTypeLoc();
875 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
876 TemplateName Name = DTST.getTypePtr()->getTemplateName();
878 Name = Context.getQualifiedTemplateName(SS.getScopeRep(),
879 /*HasTemplateKeyword*/ false,
880 Name.getAsTemplateDecl());
881 ParsedTemplateArgument Result(SS, TemplateTy::make(Name),
882 DTST.getTemplateNameLoc());
883 if (EllipsisLoc.isValid())
884 Result = Result.getTemplatePackExpansion(EllipsisLoc);
889 // This is a normal type template argument. Note, if the type template
890 // argument is an injected-class-name for a template, it has a dual nature
891 // and can be used as either a type or a template. We handle that in
892 // convertTypeTemplateArgumentToTemplate.
893 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
894 ParsedType.get().getAsOpaquePtr(),
895 TInfo->getTypeLoc().getLocStart());
898 /// ActOnTypeParameter - Called when a C++ template type parameter
899 /// (e.g., "typename T") has been parsed. Typename specifies whether
900 /// the keyword "typename" was used to declare the type parameter
901 /// (otherwise, "class" was used), and KeyLoc is the location of the
902 /// "class" or "typename" keyword. ParamName is the name of the
903 /// parameter (NULL indicates an unnamed template parameter) and
904 /// ParamNameLoc is the location of the parameter name (if any).
905 /// If the type parameter has a default argument, it will be added
906 /// later via ActOnTypeParameterDefault.
907 NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
908 SourceLocation EllipsisLoc,
909 SourceLocation KeyLoc,
910 IdentifierInfo *ParamName,
911 SourceLocation ParamNameLoc,
912 unsigned Depth, unsigned Position,
913 SourceLocation EqualLoc,
914 ParsedType DefaultArg) {
915 assert(S->isTemplateParamScope() &&
916 "Template type parameter not in template parameter scope!");
918 SourceLocation Loc = ParamNameLoc;
922 bool IsParameterPack = EllipsisLoc.isValid();
923 TemplateTypeParmDecl *Param
924 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
925 KeyLoc, Loc, Depth, Position, ParamName,
926 Typename, IsParameterPack);
927 Param->setAccess(AS_public);
930 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
932 // Add the template parameter into the current scope.
934 IdResolver.AddDecl(Param);
937 // C++0x [temp.param]p9:
938 // A default template-argument may be specified for any kind of
939 // template-parameter that is not a template parameter pack.
940 if (DefaultArg && IsParameterPack) {
941 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
942 DefaultArg = nullptr;
945 // Handle the default argument, if provided.
947 TypeSourceInfo *DefaultTInfo;
948 GetTypeFromParser(DefaultArg, &DefaultTInfo);
950 assert(DefaultTInfo && "expected source information for type");
952 // Check for unexpanded parameter packs.
953 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
954 UPPC_DefaultArgument))
957 // Check the template argument itself.
958 if (CheckTemplateArgument(Param, DefaultTInfo)) {
959 Param->setInvalidDecl();
963 Param->setDefaultArgument(DefaultTInfo);
969 /// Check that the type of a non-type template parameter is
972 /// \returns the (possibly-promoted) parameter type if valid;
973 /// otherwise, produces a diagnostic and returns a NULL type.
974 QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
975 SourceLocation Loc) {
976 if (TSI->getType()->isUndeducedType()) {
977 // C++1z [temp.dep.expr]p3:
978 // An id-expression is type-dependent if it contains
979 // - an identifier associated by name lookup with a non-type
980 // template-parameter declared with a type that contains a
981 // placeholder type (7.1.7.4),
982 TSI = SubstAutoTypeSourceInfo(TSI, Context.DependentTy);
985 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
988 QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
989 SourceLocation Loc) {
990 // We don't allow variably-modified types as the type of non-type template
992 if (T->isVariablyModifiedType()) {
993 Diag(Loc, diag::err_variably_modified_nontype_template_param)
998 // C++ [temp.param]p4:
1000 // A non-type template-parameter shall have one of the following
1001 // (optionally cv-qualified) types:
1003 // -- integral or enumeration type,
1004 if (T->isIntegralOrEnumerationType() ||
1005 // -- pointer to object or pointer to function,
1006 T->isPointerType() ||
1007 // -- reference to object or reference to function,
1008 T->isReferenceType() ||
1009 // -- pointer to member,
1010 T->isMemberPointerType() ||
1011 // -- std::nullptr_t.
1012 T->isNullPtrType() ||
1013 // If T is a dependent type, we can't do the check now, so we
1014 // assume that it is well-formed.
1015 T->isDependentType() ||
1016 // Allow use of auto in template parameter declarations.
1017 T->isUndeducedType()) {
1018 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1019 // are ignored when determining its type.
1020 return T.getUnqualifiedType();
1023 // C++ [temp.param]p8:
1025 // A non-type template-parameter of type "array of T" or
1026 // "function returning T" is adjusted to be of type "pointer to
1027 // T" or "pointer to function returning T", respectively.
1028 else if (T->isArrayType() || T->isFunctionType())
1029 return Context.getDecayedType(T);
1031 Diag(Loc, diag::err_template_nontype_parm_bad_type)
1037 NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
1040 SourceLocation EqualLoc,
1042 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
1044 // Check that we have valid decl-specifiers specified.
1045 auto CheckValidDeclSpecifiers = [this, &D] {
1048 // template-parameter:
1050 // parameter-declaration
1052 // ... A storage class shall not be specified in a template-parameter
1055 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1056 // of a parameter-declaration
1057 const DeclSpec &DS = D.getDeclSpec();
1058 auto EmitDiag = [this](SourceLocation Loc) {
1059 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1060 << FixItHint::CreateRemoval(Loc);
1062 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
1063 EmitDiag(DS.getStorageClassSpecLoc());
1065 if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
1066 EmitDiag(DS.getThreadStorageClassSpecLoc());
1069 // The inline specifier can be applied only to the declaration or
1070 // definition of a variable or function.
1072 if (DS.isInlineSpecified())
1073 EmitDiag(DS.getInlineSpecLoc());
1075 // [dcl.constexpr]p1:
1076 // The constexpr specifier shall be applied only to the definition of a
1077 // variable or variable template or the declaration of a function or
1078 // function template.
1080 if (DS.isConstexprSpecified())
1081 EmitDiag(DS.getConstexprSpecLoc());
1083 // [dcl.fct.spec]p1:
1084 // Function-specifiers can be used only in function declarations.
1086 if (DS.isVirtualSpecified())
1087 EmitDiag(DS.getVirtualSpecLoc());
1089 if (DS.isExplicitSpecified())
1090 EmitDiag(DS.getExplicitSpecLoc());
1092 if (DS.isNoreturnSpecified())
1093 EmitDiag(DS.getNoreturnSpecLoc());
1096 CheckValidDeclSpecifiers();
1098 if (TInfo->getType()->isUndeducedType()) {
1099 Diag(D.getIdentifierLoc(),
1100 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1101 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1104 assert(S->isTemplateParamScope() &&
1105 "Non-type template parameter not in template parameter scope!");
1106 bool Invalid = false;
1108 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
1110 T = Context.IntTy; // Recover with an 'int' type.
1114 IdentifierInfo *ParamName = D.getIdentifier();
1115 bool IsParameterPack = D.hasEllipsis();
1116 NonTypeTemplateParmDecl *Param
1117 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1119 D.getIdentifierLoc(),
1120 Depth, Position, ParamName, T,
1121 IsParameterPack, TInfo);
1122 Param->setAccess(AS_public);
1125 Param->setInvalidDecl();
1128 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
1131 // Add the template parameter into the current scope.
1133 IdResolver.AddDecl(Param);
1136 // C++0x [temp.param]p9:
1137 // A default template-argument may be specified for any kind of
1138 // template-parameter that is not a template parameter pack.
1139 if (Default && IsParameterPack) {
1140 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1144 // Check the well-formedness of the default template argument, if provided.
1146 // Check for unexpanded parameter packs.
1147 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
1150 TemplateArgument Converted;
1151 ExprResult DefaultRes =
1152 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
1153 if (DefaultRes.isInvalid()) {
1154 Param->setInvalidDecl();
1157 Default = DefaultRes.get();
1159 Param->setDefaultArgument(Default);
1165 /// ActOnTemplateTemplateParameter - Called when a C++ template template
1166 /// parameter (e.g. T in template <template \<typename> class T> class array)
1167 /// has been parsed. S is the current scope.
1168 NamedDecl *Sema::ActOnTemplateTemplateParameter(Scope* S,
1169 SourceLocation TmpLoc,
1170 TemplateParameterList *Params,
1171 SourceLocation EllipsisLoc,
1172 IdentifierInfo *Name,
1173 SourceLocation NameLoc,
1176 SourceLocation EqualLoc,
1177 ParsedTemplateArgument Default) {
1178 assert(S->isTemplateParamScope() &&
1179 "Template template parameter not in template parameter scope!");
1181 // Construct the parameter object.
1182 bool IsParameterPack = EllipsisLoc.isValid();
1183 TemplateTemplateParmDecl *Param =
1184 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1185 NameLoc.isInvalid()? TmpLoc : NameLoc,
1186 Depth, Position, IsParameterPack,
1188 Param->setAccess(AS_public);
1190 // If the template template parameter has a name, then link the identifier
1191 // into the scope and lookup mechanisms.
1193 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1196 IdResolver.AddDecl(Param);
1199 if (Params->size() == 0) {
1200 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1201 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1202 Param->setInvalidDecl();
1205 // C++0x [temp.param]p9:
1206 // A default template-argument may be specified for any kind of
1207 // template-parameter that is not a template parameter pack.
1208 if (IsParameterPack && !Default.isInvalid()) {
1209 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1210 Default = ParsedTemplateArgument();
1213 if (!Default.isInvalid()) {
1214 // Check only that we have a template template argument. We don't want to
1215 // try to check well-formedness now, because our template template parameter
1216 // might have dependent types in its template parameters, which we wouldn't
1217 // be able to match now.
1219 // If none of the template template parameter's template arguments mention
1220 // other template parameters, we could actually perform more checking here.
1221 // However, it isn't worth doing.
1222 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
1223 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1224 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1225 << DefaultArg.getSourceRange();
1229 // Check for unexpanded parameter packs.
1230 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
1231 DefaultArg.getArgument().getAsTemplate(),
1232 UPPC_DefaultArgument))
1235 Param->setDefaultArgument(Context, DefaultArg);
1241 /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
1242 /// constrained by RequiresClause, that contains the template parameters in
1244 TemplateParameterList *
1245 Sema::ActOnTemplateParameterList(unsigned Depth,
1246 SourceLocation ExportLoc,
1247 SourceLocation TemplateLoc,
1248 SourceLocation LAngleLoc,
1249 ArrayRef<NamedDecl *> Params,
1250 SourceLocation RAngleLoc,
1251 Expr *RequiresClause) {
1252 if (ExportLoc.isValid())
1253 Diag(ExportLoc, diag::warn_template_export_unsupported);
1255 return TemplateParameterList::Create(
1256 Context, TemplateLoc, LAngleLoc,
1257 llvm::makeArrayRef(Params.data(), Params.size()),
1258 RAngleLoc, RequiresClause);
1261 static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
1263 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
1266 DeclResult Sema::CheckClassTemplate(
1267 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1268 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1269 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1270 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1271 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1272 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1273 assert(TemplateParams && TemplateParams->size() > 0 &&
1274 "No template parameters");
1275 assert(TUK != TUK_Reference && "Can only declare or define class templates");
1276 bool Invalid = false;
1278 // Check that we can declare a template here.
1279 if (CheckTemplateDeclScope(S, TemplateParams))
1282 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1283 assert(Kind != TTK_Enum && "can't build template of enumerated type");
1285 // There is no such thing as an unnamed class template.
1287 Diag(KWLoc, diag::err_template_unnamed_class);
1291 // Find any previous declaration with this name. For a friend with no
1292 // scope explicitly specified, we only look for tag declarations (per
1293 // C++11 [basic.lookup.elab]p2).
1294 DeclContext *SemanticContext;
1295 LookupResult Previous(*this, Name, NameLoc,
1296 (SS.isEmpty() && TUK == TUK_Friend)
1297 ? LookupTagName : LookupOrdinaryName,
1298 forRedeclarationInCurContext());
1299 if (SS.isNotEmpty() && !SS.isInvalid()) {
1300 SemanticContext = computeDeclContext(SS, true);
1301 if (!SemanticContext) {
1302 // FIXME: Horrible, horrible hack! We can't currently represent this
1303 // in the AST, and historically we have just ignored such friend
1304 // class templates, so don't complain here.
1305 Diag(NameLoc, TUK == TUK_Friend
1306 ? diag::warn_template_qualified_friend_ignored
1307 : diag::err_template_qualified_declarator_no_match)
1308 << SS.getScopeRep() << SS.getRange();
1309 return TUK != TUK_Friend;
1312 if (RequireCompleteDeclContext(SS, SemanticContext))
1315 // If we're adding a template to a dependent context, we may need to
1316 // rebuilding some of the types used within the template parameter list,
1317 // now that we know what the current instantiation is.
1318 if (SemanticContext->isDependentContext()) {
1319 ContextRAII SavedContext(*this, SemanticContext);
1320 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1322 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
1323 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc, false);
1325 LookupQualifiedName(Previous, SemanticContext);
1327 SemanticContext = CurContext;
1329 // C++14 [class.mem]p14:
1330 // If T is the name of a class, then each of the following shall have a
1331 // name different from T:
1332 // -- every member template of class T
1333 if (TUK != TUK_Friend &&
1334 DiagnoseClassNameShadow(SemanticContext,
1335 DeclarationNameInfo(Name, NameLoc)))
1338 LookupName(Previous, S);
1341 if (Previous.isAmbiguous())
1344 NamedDecl *PrevDecl = nullptr;
1345 if (Previous.begin() != Previous.end())
1346 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1348 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1349 // Maybe we will complain about the shadowed template parameter.
1350 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1351 // Just pretend that we didn't see the previous declaration.
1355 // If there is a previous declaration with the same name, check
1356 // whether this is a valid redeclaration.
1357 ClassTemplateDecl *PrevClassTemplate =
1358 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1360 // We may have found the injected-class-name of a class template,
1361 // class template partial specialization, or class template specialization.
1362 // In these cases, grab the template that is being defined or specialized.
1363 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
1364 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1365 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1367 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1368 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1370 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1371 ->getSpecializedTemplate();
1375 if (TUK == TUK_Friend) {
1376 // C++ [namespace.memdef]p3:
1377 // [...] When looking for a prior declaration of a class or a function
1378 // declared as a friend, and when the name of the friend class or
1379 // function is neither a qualified name nor a template-id, scopes outside
1380 // the innermost enclosing namespace scope are not considered.
1382 DeclContext *OutermostContext = CurContext;
1383 while (!OutermostContext->isFileContext())
1384 OutermostContext = OutermostContext->getLookupParent();
1387 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1388 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1389 SemanticContext = PrevDecl->getDeclContext();
1391 // Declarations in outer scopes don't matter. However, the outermost
1392 // context we computed is the semantic context for our new
1394 PrevDecl = PrevClassTemplate = nullptr;
1395 SemanticContext = OutermostContext;
1397 // Check that the chosen semantic context doesn't already contain a
1398 // declaration of this name as a non-tag type.
1399 Previous.clear(LookupOrdinaryName);
1400 DeclContext *LookupContext = SemanticContext;
1401 while (LookupContext->isTransparentContext())
1402 LookupContext = LookupContext->getLookupParent();
1403 LookupQualifiedName(Previous, LookupContext);
1405 if (Previous.isAmbiguous())
1408 if (Previous.begin() != Previous.end())
1409 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1412 } else if (PrevDecl &&
1413 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1415 PrevDecl = PrevClassTemplate = nullptr;
1417 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1418 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1420 !(PrevClassTemplate &&
1421 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1422 SemanticContext->getRedeclContext()))) {
1423 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1424 Diag(Shadow->getTargetDecl()->getLocation(),
1425 diag::note_using_decl_target);
1426 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1427 // Recover by ignoring the old declaration.
1428 PrevDecl = PrevClassTemplate = nullptr;
1432 // TODO Memory management; associated constraints are not always stored.
1433 Expr *const CurAC = formAssociatedConstraints(TemplateParams, nullptr);
1435 if (PrevClassTemplate) {
1436 // Ensure that the template parameter lists are compatible. Skip this check
1437 // for a friend in a dependent context: the template parameter list itself
1438 // could be dependent.
1439 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1440 !TemplateParameterListsAreEqual(TemplateParams,
1441 PrevClassTemplate->getTemplateParameters(),
1446 // Check for matching associated constraints on redeclarations.
1447 const Expr *const PrevAC = PrevClassTemplate->getAssociatedConstraints();
1448 const bool RedeclACMismatch = [&] {
1449 if (!(CurAC || PrevAC))
1450 return false; // Nothing to check; no mismatch.
1451 if (CurAC && PrevAC) {
1452 llvm::FoldingSetNodeID CurACInfo, PrevACInfo;
1453 CurAC->Profile(CurACInfo, Context, /*Canonical=*/true);
1454 PrevAC->Profile(PrevACInfo, Context, /*Canonical=*/true);
1455 if (CurACInfo == PrevACInfo)
1456 return false; // All good; no mismatch.
1461 if (RedeclACMismatch) {
1462 Diag(CurAC ? CurAC->getLocStart() : NameLoc,
1463 diag::err_template_different_associated_constraints);
1464 Diag(PrevAC ? PrevAC->getLocStart() : PrevClassTemplate->getLocation(),
1465 diag::note_template_prev_declaration) << /*declaration*/0;
1469 // C++ [temp.class]p4:
1470 // In a redeclaration, partial specialization, explicit
1471 // specialization or explicit instantiation of a class template,
1472 // the class-key shall agree in kind with the original class
1473 // template declaration (7.1.5.3).
1474 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
1475 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
1476 TUK == TUK_Definition, KWLoc, Name)) {
1477 Diag(KWLoc, diag::err_use_with_wrong_tag)
1479 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
1480 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
1481 Kind = PrevRecordDecl->getTagKind();
1484 // Check for redefinition of this class template.
1485 if (TUK == TUK_Definition) {
1486 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
1487 // If we have a prior definition that is not visible, treat this as
1488 // simply making that previous definition visible.
1489 NamedDecl *Hidden = nullptr;
1490 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
1491 SkipBody->ShouldSkip = true;
1492 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1493 assert(Tmpl && "original definition of a class template is not a "
1495 makeMergedDefinitionVisible(Hidden);
1496 makeMergedDefinitionVisible(Tmpl);
1500 Diag(NameLoc, diag::err_redefinition) << Name;
1501 Diag(Def->getLocation(), diag::note_previous_definition);
1502 // FIXME: Would it make sense to try to "forget" the previous
1503 // definition, as part of error recovery?
1507 } else if (PrevDecl) {
1509 // A class template shall not have the same name as any other
1510 // template, class, function, object, enumeration, enumerator,
1511 // namespace, or type in the same scope (3.3), except as specified
1513 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1514 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1518 // Check the template parameter list of this declaration, possibly
1519 // merging in the template parameter list from the previous class
1520 // template declaration. Skip this check for a friend in a dependent
1521 // context, because the template parameter list might be dependent.
1522 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1523 CheckTemplateParameterList(
1525 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1527 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1528 SemanticContext->isDependentContext())
1529 ? TPC_ClassTemplateMember
1530 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1531 : TPC_ClassTemplate))
1535 // If the name of the template was qualified, we must be defining the
1536 // template out-of-line.
1537 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1538 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
1539 : diag::err_member_decl_does_not_match)
1540 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
1545 // If this is a templated friend in a dependent context we should not put it
1546 // on the redecl chain. In some cases, the templated friend can be the most
1547 // recent declaration tricking the template instantiator to make substitutions
1549 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
1550 bool ShouldAddRedecl
1551 = !(TUK == TUK_Friend && CurContext->isDependentContext());
1553 CXXRecordDecl *NewClass =
1554 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
1555 PrevClassTemplate && ShouldAddRedecl ?
1556 PrevClassTemplate->getTemplatedDecl() : nullptr,
1557 /*DelayTypeCreation=*/true);
1558 SetNestedNameSpecifier(NewClass, SS);
1559 if (NumOuterTemplateParamLists > 0)
1560 NewClass->setTemplateParameterListsInfo(
1561 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1562 NumOuterTemplateParamLists));
1564 // Add alignment attributes if necessary; these attributes are checked when
1565 // the ASTContext lays out the structure.
1566 if (TUK == TUK_Definition) {
1567 AddAlignmentAttributesForRecord(NewClass);
1568 AddMsStructLayoutForRecord(NewClass);
1571 // Attach the associated constraints when the declaration will not be part of
1573 Expr *const ACtoAttach =
1574 PrevClassTemplate && ShouldAddRedecl ? nullptr : CurAC;
1576 ClassTemplateDecl *NewTemplate
1577 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1578 DeclarationName(Name), TemplateParams,
1579 NewClass, ACtoAttach);
1581 if (ShouldAddRedecl)
1582 NewTemplate->setPreviousDecl(PrevClassTemplate);
1584 NewClass->setDescribedClassTemplate(NewTemplate);
1586 if (ModulePrivateLoc.isValid())
1587 NewTemplate->setModulePrivate();
1589 // Build the type for the class template declaration now.
1590 QualType T = NewTemplate->getInjectedClassNameSpecialization();
1591 T = Context.getInjectedClassNameType(NewClass, T);
1592 assert(T->isDependentType() && "Class template type is not dependent?");
1595 // If we are providing an explicit specialization of a member that is a
1596 // class template, make a note of that.
1597 if (PrevClassTemplate &&
1598 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1599 PrevClassTemplate->setMemberSpecialization();
1601 // Set the access specifier.
1602 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
1603 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
1605 // Set the lexical context of these templates
1606 NewClass->setLexicalDeclContext(CurContext);
1607 NewTemplate->setLexicalDeclContext(CurContext);
1609 if (TUK == TUK_Definition)
1610 NewClass->startDefinition();
1612 ProcessDeclAttributeList(S, NewClass, Attr);
1614 if (PrevClassTemplate)
1615 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1617 AddPushedVisibilityAttribute(NewClass);
1619 if (TUK != TUK_Friend) {
1620 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1622 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1623 Outer = Outer->getParent();
1624 PushOnScopeChains(NewTemplate, Outer);
1626 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
1627 NewTemplate->setAccess(PrevClassTemplate->getAccess());
1628 NewClass->setAccess(PrevClassTemplate->getAccess());
1631 NewTemplate->setObjectOfFriendDecl();
1633 // Friend templates are visible in fairly strange ways.
1634 if (!CurContext->isDependentContext()) {
1635 DeclContext *DC = SemanticContext->getRedeclContext();
1636 DC->makeDeclVisibleInContext(NewTemplate);
1637 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1638 PushOnScopeChains(NewTemplate, EnclosingScope,
1639 /* AddToContext = */ false);
1642 FriendDecl *Friend = FriendDecl::Create(
1643 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
1644 Friend->setAccess(AS_public);
1645 CurContext->addDecl(Friend);
1648 if (PrevClassTemplate)
1649 CheckRedeclarationModuleOwnership(NewTemplate, PrevClassTemplate);
1652 NewTemplate->setInvalidDecl();
1653 NewClass->setInvalidDecl();
1656 ActOnDocumentableDecl(NewTemplate);
1662 /// Tree transform to "extract" a transformed type from a class template's
1663 /// constructor to a deduction guide.
1664 class ExtractTypeForDeductionGuide
1665 : public TreeTransform<ExtractTypeForDeductionGuide> {
1667 typedef TreeTransform<ExtractTypeForDeductionGuide> Base;
1668 ExtractTypeForDeductionGuide(Sema &SemaRef) : Base(SemaRef) {}
1670 TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); }
1672 QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) {
1673 return TransformType(
1675 TL.getTypedefNameDecl()->getTypeSourceInfo()->getTypeLoc());
1679 /// Transform to convert portions of a constructor declaration into the
1680 /// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
1681 struct ConvertConstructorToDeductionGuideTransform {
1682 ConvertConstructorToDeductionGuideTransform(Sema &S,
1683 ClassTemplateDecl *Template)
1684 : SemaRef(S), Template(Template) {}
1687 ClassTemplateDecl *Template;
1689 DeclContext *DC = Template->getDeclContext();
1690 CXXRecordDecl *Primary = Template->getTemplatedDecl();
1691 DeclarationName DeductionGuideName =
1692 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template);
1694 QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
1696 // Index adjustment to apply to convert depth-1 template parameters into
1697 // depth-0 template parameters.
1698 unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
1700 /// Transform a constructor declaration into a deduction guide.
1701 NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
1702 CXXConstructorDecl *CD) {
1703 SmallVector<TemplateArgument, 16> SubstArgs;
1705 LocalInstantiationScope Scope(SemaRef);
1707 // C++ [over.match.class.deduct]p1:
1708 // -- For each constructor of the class template designated by the
1709 // template-name, a function template with the following properties:
1711 // -- The template parameters are the template parameters of the class
1712 // template followed by the template parameters (including default
1713 // template arguments) of the constructor, if any.
1714 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
1716 TemplateParameterList *InnerParams = FTD->getTemplateParameters();
1717 SmallVector<NamedDecl *, 16> AllParams;
1718 AllParams.reserve(TemplateParams->size() + InnerParams->size());
1719 AllParams.insert(AllParams.begin(),
1720 TemplateParams->begin(), TemplateParams->end());
1721 SubstArgs.reserve(InnerParams->size());
1723 // Later template parameters could refer to earlier ones, so build up
1724 // a list of substituted template arguments as we go.
1725 for (NamedDecl *Param : *InnerParams) {
1726 MultiLevelTemplateArgumentList Args;
1727 Args.addOuterTemplateArguments(SubstArgs);
1728 Args.addOuterRetainedLevel();
1729 NamedDecl *NewParam = transformTemplateParameter(Param, Args);
1732 AllParams.push_back(NewParam);
1733 SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
1734 SemaRef.Context.getInjectedTemplateArg(NewParam)));
1736 TemplateParams = TemplateParameterList::Create(
1737 SemaRef.Context, InnerParams->getTemplateLoc(),
1738 InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
1739 /*FIXME: RequiresClause*/ nullptr);
1742 // If we built a new template-parameter-list, track that we need to
1743 // substitute references to the old parameters into references to the
1745 MultiLevelTemplateArgumentList Args;
1747 Args.addOuterTemplateArguments(SubstArgs);
1748 Args.addOuterRetainedLevel();
1751 FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc()
1752 .getAsAdjusted<FunctionProtoTypeLoc>();
1753 assert(FPTL && "no prototype for constructor declaration");
1755 // Transform the type of the function, adjusting the return type and
1756 // replacing references to the old parameters with references to the
1759 SmallVector<ParmVarDecl*, 8> Params;
1760 QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args);
1761 if (NewType.isNull())
1763 TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
1765 return buildDeductionGuide(TemplateParams, CD->isExplicit(), NewTInfo,
1766 CD->getLocStart(), CD->getLocation(),
1770 /// Build a deduction guide with the specified parameter types.
1771 NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
1772 SourceLocation Loc = Template->getLocation();
1774 // Build the requested type.
1775 FunctionProtoType::ExtProtoInfo EPI;
1776 EPI.HasTrailingReturn = true;
1777 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
1778 DeductionGuideName, EPI);
1779 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
1781 FunctionProtoTypeLoc FPTL =
1782 TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
1784 // Build the parameters, needed during deduction / substitution.
1785 SmallVector<ParmVarDecl*, 4> Params;
1786 for (auto T : ParamTypes) {
1787 ParmVarDecl *NewParam = ParmVarDecl::Create(
1788 SemaRef.Context, DC, Loc, Loc, nullptr, T,
1789 SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
1790 NewParam->setScopeInfo(0, Params.size());
1791 FPTL.setParam(Params.size(), NewParam);
1792 Params.push_back(NewParam);
1795 return buildDeductionGuide(Template->getTemplateParameters(), false, TSI,
1800 /// Transform a constructor template parameter into a deduction guide template
1801 /// parameter, rebuilding any internal references to earlier parameters and
1802 /// renumbering as we go.
1803 NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
1804 MultiLevelTemplateArgumentList &Args) {
1805 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
1806 // TemplateTypeParmDecl's index cannot be changed after creation, so
1807 // substitute it directly.
1808 auto *NewTTP = TemplateTypeParmDecl::Create(
1809 SemaRef.Context, DC, TTP->getLocStart(), TTP->getLocation(),
1810 /*Depth*/0, Depth1IndexAdjustment + TTP->getIndex(),
1811 TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
1812 TTP->isParameterPack());
1813 if (TTP->hasDefaultArgument()) {
1814 TypeSourceInfo *InstantiatedDefaultArg =
1815 SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
1816 TTP->getDefaultArgumentLoc(), TTP->getDeclName());
1817 if (InstantiatedDefaultArg)
1818 NewTTP->setDefaultArgument(InstantiatedDefaultArg);
1820 SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam,
1825 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
1826 return transformTemplateParameterImpl(TTP, Args);
1828 return transformTemplateParameterImpl(
1829 cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
1831 template<typename TemplateParmDecl>
1833 transformTemplateParameterImpl(TemplateParmDecl *OldParam,
1834 MultiLevelTemplateArgumentList &Args) {
1835 // Ask the template instantiator to do the heavy lifting for us, then adjust
1836 // the index of the parameter once it's done.
1838 cast_or_null<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
1839 assert(NewParam->getDepth() == 0 && "unexpected template param depth");
1840 NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
1844 QualType transformFunctionProtoType(TypeLocBuilder &TLB,
1845 FunctionProtoTypeLoc TL,
1846 SmallVectorImpl<ParmVarDecl*> &Params,
1847 MultiLevelTemplateArgumentList &Args) {
1848 SmallVector<QualType, 4> ParamTypes;
1849 const FunctionProtoType *T = TL.getTypePtr();
1851 // -- The types of the function parameters are those of the constructor.
1852 for (auto *OldParam : TL.getParams()) {
1853 ParmVarDecl *NewParam = transformFunctionTypeParam(OldParam, Args);
1856 ParamTypes.push_back(NewParam->getType());
1857 Params.push_back(NewParam);
1860 // -- The return type is the class template specialization designated by
1861 // the template-name and template arguments corresponding to the
1862 // template parameters obtained from the class template.
1864 // We use the injected-class-name type of the primary template instead.
1865 // This has the convenient property that it is different from any type that
1866 // the user can write in a deduction-guide (because they cannot enter the
1867 // context of the template), so implicit deduction guides can never collide
1868 // with explicit ones.
1869 QualType ReturnType = DeducedType;
1870 TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
1872 // Resolving a wording defect, we also inherit the variadicness of the
1874 FunctionProtoType::ExtProtoInfo EPI;
1875 EPI.Variadic = T->isVariadic();
1876 EPI.HasTrailingReturn = true;
1878 QualType Result = SemaRef.BuildFunctionType(
1879 ReturnType, ParamTypes, TL.getLocStart(), DeductionGuideName, EPI);
1880 if (Result.isNull())
1883 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
1884 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
1885 NewTL.setLParenLoc(TL.getLParenLoc());
1886 NewTL.setRParenLoc(TL.getRParenLoc());
1887 NewTL.setExceptionSpecRange(SourceRange());
1888 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
1889 for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
1890 NewTL.setParam(I, Params[I]);
1896 transformFunctionTypeParam(ParmVarDecl *OldParam,
1897 MultiLevelTemplateArgumentList &Args) {
1898 TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
1899 TypeSourceInfo *NewDI;
1900 if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
1901 // Expand out the one and only element in each inner pack.
1902 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
1904 SemaRef.SubstType(PackTL.getPatternLoc(), Args,
1905 OldParam->getLocation(), OldParam->getDeclName());
1906 if (!NewDI) return nullptr;
1908 SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
1909 PackTL.getTypePtr()->getNumExpansions());
1911 NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
1912 OldParam->getDeclName());
1916 // Extract the type. This (for instance) replaces references to typedef
1917 // members of the current instantiations with the definitions of those
1918 // typedefs, avoiding triggering instantiation of the deduced type during
1920 NewDI = ExtractTypeForDeductionGuide(SemaRef).transform(NewDI);
1922 // Resolving a wording defect, we also inherit default arguments from the
1924 ExprResult NewDefArg;
1925 if (OldParam->hasDefaultArg()) {
1926 NewDefArg = SemaRef.SubstExpr(OldParam->getDefaultArg(), Args);
1927 if (NewDefArg.isInvalid())
1931 ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
1932 OldParam->getInnerLocStart(),
1933 OldParam->getLocation(),
1934 OldParam->getIdentifier(),
1937 OldParam->getStorageClass(),
1939 NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
1940 OldParam->getFunctionScopeIndex());
1941 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam);
1945 NamedDecl *buildDeductionGuide(TemplateParameterList *TemplateParams,
1946 bool Explicit, TypeSourceInfo *TInfo,
1947 SourceLocation LocStart, SourceLocation Loc,
1948 SourceLocation LocEnd) {
1949 DeclarationNameInfo Name(DeductionGuideName, Loc);
1950 ArrayRef<ParmVarDecl *> Params =
1951 TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
1953 // Build the implicit deduction guide template.
1955 CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, Explicit,
1956 Name, TInfo->getType(), TInfo, LocEnd);
1957 Guide->setImplicit();
1958 Guide->setParams(Params);
1960 for (auto *Param : Params)
1961 Param->setDeclContext(Guide);
1963 auto *GuideTemplate = FunctionTemplateDecl::Create(
1964 SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
1965 GuideTemplate->setImplicit();
1966 Guide->setDescribedFunctionTemplate(GuideTemplate);
1968 if (isa<CXXRecordDecl>(DC)) {
1969 Guide->setAccess(AS_public);
1970 GuideTemplate->setAccess(AS_public);
1973 DC->addDecl(GuideTemplate);
1974 return GuideTemplate;
1979 void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
1980 SourceLocation Loc) {
1981 DeclContext *DC = Template->getDeclContext();
1982 if (DC->isDependentContext())
1985 ConvertConstructorToDeductionGuideTransform Transform(
1986 *this, cast<ClassTemplateDecl>(Template));
1987 if (!isCompleteType(Loc, Transform.DeducedType))
1990 // Check whether we've already declared deduction guides for this template.
1991 // FIXME: Consider storing a flag on the template to indicate this.
1992 auto Existing = DC->lookup(Transform.DeductionGuideName);
1993 for (auto *D : Existing)
1994 if (D->isImplicit())
1997 // In case we were expanding a pack when we attempted to declare deduction
1998 // guides, turn off pack expansion for everything we're about to do.
1999 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
2000 // Create a template instantiation record to track the "instantiation" of
2001 // constructors into deduction guides.
2002 // FIXME: Add a kind for this to give more meaningful diagnostics. But can
2003 // this substitution process actually fail?
2004 InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
2005 if (BuildingDeductionGuides.isInvalid())
2008 // Convert declared constructors into deduction guide templates.
2009 // FIXME: Skip constructors for which deduction must necessarily fail (those
2010 // for which some class template parameter without a default argument never
2011 // appears in a deduced context).
2012 bool AddedAny = false;
2013 for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
2014 D = D->getUnderlyingDecl();
2015 if (D->isInvalidDecl() || D->isImplicit())
2017 D = cast<NamedDecl>(D->getCanonicalDecl());
2019 auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
2021 dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
2022 // Class-scope explicit specializations (MS extension) do not result in
2023 // deduction guides.
2024 if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
2027 Transform.transformConstructor(FTD, CD);
2031 // C++17 [over.match.class.deduct]
2032 // -- If C is not defined or does not declare any constructors, an
2033 // additional function template derived as above from a hypothetical
2036 Transform.buildSimpleDeductionGuide(None);
2038 // -- An additional function template derived as above from a hypothetical
2039 // constructor C(C), called the copy deduction candidate.
2040 cast<CXXDeductionGuideDecl>(
2041 cast<FunctionTemplateDecl>(
2042 Transform.buildSimpleDeductionGuide(Transform.DeducedType))
2043 ->getTemplatedDecl())
2044 ->setIsCopyDeductionCandidate();
2047 /// Diagnose the presence of a default template argument on a
2048 /// template parameter, which is ill-formed in certain contexts.
2050 /// \returns true if the default template argument should be dropped.
2051 static bool DiagnoseDefaultTemplateArgument(Sema &S,
2052 Sema::TemplateParamListContext TPC,
2053 SourceLocation ParamLoc,
2054 SourceRange DefArgRange) {
2056 case Sema::TPC_ClassTemplate:
2057 case Sema::TPC_VarTemplate:
2058 case Sema::TPC_TypeAliasTemplate:
2061 case Sema::TPC_FunctionTemplate:
2062 case Sema::TPC_FriendFunctionTemplateDefinition:
2063 // C++ [temp.param]p9:
2064 // A default template-argument shall not be specified in a
2065 // function template declaration or a function template
2067 // If a friend function template declaration specifies a default
2068 // template-argument, that declaration shall be a definition and shall be
2069 // the only declaration of the function template in the translation unit.
2070 // (C++98/03 doesn't have this wording; see DR226).
2071 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
2072 diag::warn_cxx98_compat_template_parameter_default_in_function_template
2073 : diag::ext_template_parameter_default_in_function_template)
2077 case Sema::TPC_ClassTemplateMember:
2078 // C++0x [temp.param]p9:
2079 // A default template-argument shall not be specified in the
2080 // template-parameter-lists of the definition of a member of a
2081 // class template that appears outside of the member's class.
2082 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2086 case Sema::TPC_FriendClassTemplate:
2087 case Sema::TPC_FriendFunctionTemplate:
2088 // C++ [temp.param]p9:
2089 // A default template-argument shall not be specified in a
2090 // friend template declaration.
2091 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2095 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2096 // for friend function templates if there is only a single
2097 // declaration (and it is a definition). Strange!
2100 llvm_unreachable("Invalid TemplateParamListContext!");
2103 /// Check for unexpanded parameter packs within the template parameters
2104 /// of a template template parameter, recursively.
2105 static bool DiagnoseUnexpandedParameterPacks(Sema &S,
2106 TemplateTemplateParmDecl *TTP) {
2107 // A template template parameter which is a parameter pack is also a pack
2109 if (TTP->isParameterPack())
2112 TemplateParameterList *Params = TTP->getTemplateParameters();
2113 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2114 NamedDecl *P = Params->getParam(I);
2115 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2116 if (!NTTP->isParameterPack() &&
2117 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2118 NTTP->getTypeSourceInfo(),
2119 Sema::UPPC_NonTypeTemplateParameterType))
2125 if (TemplateTemplateParmDecl *InnerTTP
2126 = dyn_cast<TemplateTemplateParmDecl>(P))
2127 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2134 /// Checks the validity of a template parameter list, possibly
2135 /// considering the template parameter list from a previous
2138 /// If an "old" template parameter list is provided, it must be
2139 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
2140 /// template parameter list.
2142 /// \param NewParams Template parameter list for a new template
2143 /// declaration. This template parameter list will be updated with any
2144 /// default arguments that are carried through from the previous
2145 /// template parameter list.
2147 /// \param OldParams If provided, template parameter list from a
2148 /// previous declaration of the same template. Default template
2149 /// arguments will be merged from the old template parameter list to
2150 /// the new template parameter list.
2152 /// \param TPC Describes the context in which we are checking the given
2153 /// template parameter list.
2155 /// \returns true if an error occurred, false otherwise.
2156 bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
2157 TemplateParameterList *OldParams,
2158 TemplateParamListContext TPC) {
2159 bool Invalid = false;
2161 // C++ [temp.param]p10:
2162 // The set of default template-arguments available for use with a
2163 // template declaration or definition is obtained by merging the
2164 // default arguments from the definition (if in scope) and all
2165 // declarations in scope in the same way default function
2166 // arguments are (8.3.6).
2167 bool SawDefaultArgument = false;
2168 SourceLocation PreviousDefaultArgLoc;
2170 // Dummy initialization to avoid warnings.
2171 TemplateParameterList::iterator OldParam = NewParams->end();
2173 OldParam = OldParams->begin();
2175 bool RemoveDefaultArguments = false;
2176 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2177 NewParamEnd = NewParams->end();
2178 NewParam != NewParamEnd; ++NewParam) {
2179 // Variables used to diagnose redundant default arguments
2180 bool RedundantDefaultArg = false;
2181 SourceLocation OldDefaultLoc;
2182 SourceLocation NewDefaultLoc;
2184 // Variable used to diagnose missing default arguments
2185 bool MissingDefaultArg = false;
2187 // Variable used to diagnose non-final parameter packs
2188 bool SawParameterPack = false;
2190 if (TemplateTypeParmDecl *NewTypeParm
2191 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2192 // Check the presence of a default argument here.
2193 if (NewTypeParm->hasDefaultArgument() &&
2194 DiagnoseDefaultTemplateArgument(*this, TPC,
2195 NewTypeParm->getLocation(),
2196 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
2198 NewTypeParm->removeDefaultArgument();
2200 // Merge default arguments for template type parameters.
2201 TemplateTypeParmDecl *OldTypeParm
2202 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2203 if (NewTypeParm->isParameterPack()) {
2204 assert(!NewTypeParm->hasDefaultArgument() &&
2205 "Parameter packs can't have a default argument!");
2206 SawParameterPack = true;
2207 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2208 NewTypeParm->hasDefaultArgument()) {
2209 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2210 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2211 SawDefaultArgument = true;
2212 RedundantDefaultArg = true;
2213 PreviousDefaultArgLoc = NewDefaultLoc;
2214 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2215 // Merge the default argument from the old declaration to the
2217 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2218 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2219 } else if (NewTypeParm->hasDefaultArgument()) {
2220 SawDefaultArgument = true;
2221 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2222 } else if (SawDefaultArgument)
2223 MissingDefaultArg = true;
2224 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2225 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2226 // Check for unexpanded parameter packs.
2227 if (!NewNonTypeParm->isParameterPack() &&
2228 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2229 NewNonTypeParm->getTypeSourceInfo(),
2230 UPPC_NonTypeTemplateParameterType)) {
2235 // Check the presence of a default argument here.
2236 if (NewNonTypeParm->hasDefaultArgument() &&
2237 DiagnoseDefaultTemplateArgument(*this, TPC,
2238 NewNonTypeParm->getLocation(),
2239 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
2240 NewNonTypeParm->removeDefaultArgument();
2243 // Merge default arguments for non-type template parameters
2244 NonTypeTemplateParmDecl *OldNonTypeParm
2245 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2246 if (NewNonTypeParm->isParameterPack()) {
2247 assert(!NewNonTypeParm->hasDefaultArgument() &&
2248 "Parameter packs can't have a default argument!");
2249 if (!NewNonTypeParm->isPackExpansion())
2250 SawParameterPack = true;
2251 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2252 NewNonTypeParm->hasDefaultArgument()) {
2253 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2254 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2255 SawDefaultArgument = true;
2256 RedundantDefaultArg = true;
2257 PreviousDefaultArgLoc = NewDefaultLoc;
2258 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2259 // Merge the default argument from the old declaration to the
2261 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2262 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2263 } else if (NewNonTypeParm->hasDefaultArgument()) {
2264 SawDefaultArgument = true;
2265 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2266 } else if (SawDefaultArgument)
2267 MissingDefaultArg = true;
2269 TemplateTemplateParmDecl *NewTemplateParm
2270 = cast<TemplateTemplateParmDecl>(*NewParam);
2272 // Check for unexpanded parameter packs, recursively.
2273 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2278 // Check the presence of a default argument here.
2279 if (NewTemplateParm->hasDefaultArgument() &&
2280 DiagnoseDefaultTemplateArgument(*this, TPC,
2281 NewTemplateParm->getLocation(),
2282 NewTemplateParm->getDefaultArgument().getSourceRange()))
2283 NewTemplateParm->removeDefaultArgument();
2285 // Merge default arguments for template template parameters
2286 TemplateTemplateParmDecl *OldTemplateParm
2287 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2288 if (NewTemplateParm->isParameterPack()) {
2289 assert(!NewTemplateParm->hasDefaultArgument() &&
2290 "Parameter packs can't have a default argument!");
2291 if (!NewTemplateParm->isPackExpansion())
2292 SawParameterPack = true;
2293 } else if (OldTemplateParm &&
2294 hasVisibleDefaultArgument(OldTemplateParm) &&
2295 NewTemplateParm->hasDefaultArgument()) {
2296 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2297 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2298 SawDefaultArgument = true;
2299 RedundantDefaultArg = true;
2300 PreviousDefaultArgLoc = NewDefaultLoc;
2301 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2302 // Merge the default argument from the old declaration to the
2304 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2305 PreviousDefaultArgLoc
2306 = OldTemplateParm->getDefaultArgument().getLocation();
2307 } else if (NewTemplateParm->hasDefaultArgument()) {
2308 SawDefaultArgument = true;
2309 PreviousDefaultArgLoc
2310 = NewTemplateParm->getDefaultArgument().getLocation();
2311 } else if (SawDefaultArgument)
2312 MissingDefaultArg = true;
2315 // C++11 [temp.param]p11:
2316 // If a template parameter of a primary class template or alias template
2317 // is a template parameter pack, it shall be the last template parameter.
2318 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2319 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2320 TPC == TPC_TypeAliasTemplate)) {
2321 Diag((*NewParam)->getLocation(),
2322 diag::err_template_param_pack_must_be_last_template_parameter);
2326 if (RedundantDefaultArg) {
2327 // C++ [temp.param]p12:
2328 // A template-parameter shall not be given default arguments
2329 // by two different declarations in the same scope.
2330 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2331 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2333 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
2334 // C++ [temp.param]p11:
2335 // If a template-parameter of a class template has a default
2336 // template-argument, each subsequent template-parameter shall either
2337 // have a default template-argument supplied or be a template parameter
2339 Diag((*NewParam)->getLocation(),
2340 diag::err_template_param_default_arg_missing);
2341 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2343 RemoveDefaultArguments = true;
2346 // If we have an old template parameter list that we're merging
2347 // in, move on to the next parameter.
2352 // We were missing some default arguments at the end of the list, so remove
2353 // all of the default arguments.
2354 if (RemoveDefaultArguments) {
2355 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2356 NewParamEnd = NewParams->end();
2357 NewParam != NewParamEnd; ++NewParam) {
2358 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2359 TTP->removeDefaultArgument();
2360 else if (NonTypeTemplateParmDecl *NTTP
2361 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2362 NTTP->removeDefaultArgument();
2364 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2373 /// A class which looks for a use of a certain level of template
2375 struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
2376 typedef RecursiveASTVisitor<DependencyChecker> super;
2380 // Whether we're looking for a use of a template parameter that makes the
2381 // overall construct type-dependent / a dependent type. This is strictly
2382 // best-effort for now; we may fail to match at all for a dependent type
2383 // in some cases if this is set.
2384 bool IgnoreNonTypeDependent;
2387 SourceLocation MatchLoc;
2389 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2390 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2393 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2394 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2395 NamedDecl *ND = Params->getParam(0);
2396 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2397 Depth = PD->getDepth();
2398 } else if (NonTypeTemplateParmDecl *PD =
2399 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2400 Depth = PD->getDepth();
2402 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2406 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2407 if (ParmDepth >= Depth) {
2415 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2416 // Prune out non-type-dependent expressions if requested. This can
2417 // sometimes result in us failing to find a template parameter reference
2418 // (if a value-dependent expression creates a dependent type), but this
2419 // mode is best-effort only.
2420 if (auto *E = dyn_cast_or_null<Expr>(S))
2421 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2423 return super::TraverseStmt(S, Q);
2426 bool TraverseTypeLoc(TypeLoc TL) {
2427 if (IgnoreNonTypeDependent && !TL.isNull() &&
2428 !TL.getType()->isDependentType())
2430 return super::TraverseTypeLoc(TL);
2433 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2434 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2437 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
2438 // For a best-effort search, keep looking until we find a location.
2439 return IgnoreNonTypeDependent || !Matches(T->getDepth());
2442 bool TraverseTemplateName(TemplateName N) {
2443 if (TemplateTemplateParmDecl *PD =
2444 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2445 if (Matches(PD->getDepth()))
2447 return super::TraverseTemplateName(N);
2450 bool VisitDeclRefExpr(DeclRefExpr *E) {
2451 if (NonTypeTemplateParmDecl *PD =
2452 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2453 if (Matches(PD->getDepth(), E->getExprLoc()))
2455 return super::VisitDeclRefExpr(E);
2458 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2459 return TraverseType(T->getReplacementType());
2463 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
2464 return TraverseTemplateArgument(T->getArgumentPack());
2467 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
2468 return TraverseType(T->getInjectedSpecializationType());
2471 } // end anonymous namespace
2473 /// Determines whether a given type depends on the given parameter
2476 DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
2477 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2478 Checker.TraverseType(T);
2479 return Checker.Match;
2482 // Find the source range corresponding to the named type in the given
2483 // nested-name-specifier, if any.
2484 static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2486 const CXXScopeSpec &SS) {
2487 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2488 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2489 if (const Type *CurType = NNS->getAsType()) {
2490 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2491 return NNSLoc.getTypeLoc().getSourceRange();
2495 NNSLoc = NNSLoc.getPrefix();
2498 return SourceRange();
2501 /// Match the given template parameter lists to the given scope
2502 /// specifier, returning the template parameter list that applies to the
2505 /// \param DeclStartLoc the start of the declaration that has a scope
2506 /// specifier or a template parameter list.
2508 /// \param DeclLoc The location of the declaration itself.
2510 /// \param SS the scope specifier that will be matched to the given template
2511 /// parameter lists. This scope specifier precedes a qualified name that is
2514 /// \param TemplateId The template-id following the scope specifier, if there
2515 /// is one. Used to check for a missing 'template<>'.
2517 /// \param ParamLists the template parameter lists, from the outermost to the
2518 /// innermost template parameter lists.
2520 /// \param IsFriend Whether to apply the slightly different rules for
2521 /// matching template parameters to scope specifiers in friend
2524 /// \param IsMemberSpecialization will be set true if the scope specifier
2525 /// denotes a fully-specialized type, and therefore this is a declaration of
2526 /// a member specialization.
2528 /// \returns the template parameter list, if any, that corresponds to the
2529 /// name that is preceded by the scope specifier @p SS. This template
2530 /// parameter list may have template parameters (if we're declaring a
2531 /// template) or may have no template parameters (if we're declaring a
2532 /// template specialization), or may be NULL (if what we're declaring isn't
2533 /// itself a template).
2534 TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2535 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2536 TemplateIdAnnotation *TemplateId,
2537 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2538 bool &IsMemberSpecialization, bool &Invalid) {
2539 IsMemberSpecialization = false;
2542 // The sequence of nested types to which we will match up the template
2543 // parameter lists. We first build this list by starting with the type named
2544 // by the nested-name-specifier and walking out until we run out of types.
2545 SmallVector<QualType, 4> NestedTypes;
2547 if (SS.getScopeRep()) {
2548 if (CXXRecordDecl *Record
2549 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2550 T = Context.getTypeDeclType(Record);
2552 T = QualType(SS.getScopeRep()->getAsType(), 0);
2555 // If we found an explicit specialization that prevents us from needing
2556 // 'template<>' headers, this will be set to the location of that
2557 // explicit specialization.
2558 SourceLocation ExplicitSpecLoc;
2560 while (!T.isNull()) {
2561 NestedTypes.push_back(T);
2563 // Retrieve the parent of a record type.
2564 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2565 // If this type is an explicit specialization, we're done.
2566 if (ClassTemplateSpecializationDecl *Spec
2567 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2568 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
2569 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2570 ExplicitSpecLoc = Spec->getLocation();
2573 } else if (Record->getTemplateSpecializationKind()
2574 == TSK_ExplicitSpecialization) {
2575 ExplicitSpecLoc = Record->getLocation();
2579 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2580 T = Context.getTypeDeclType(Parent);
2586 if (const TemplateSpecializationType *TST
2587 = T->getAs<TemplateSpecializationType>()) {
2588 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2589 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2590 T = Context.getTypeDeclType(Parent);
2597 // Look one step prior in a dependent template specialization type.
2598 if (const DependentTemplateSpecializationType *DependentTST
2599 = T->getAs<DependentTemplateSpecializationType>()) {
2600 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2601 T = QualType(NNS->getAsType(), 0);
2607 // Look one step prior in a dependent name type.
2608 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2609 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2610 T = QualType(NNS->getAsType(), 0);
2616 // Retrieve the parent of an enumeration type.
2617 if (const EnumType *EnumT = T->getAs<EnumType>()) {
2618 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2620 EnumDecl *Enum = EnumT->getDecl();
2622 // Get to the parent type.
2623 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2624 T = Context.getTypeDeclType(Parent);
2632 // Reverse the nested types list, since we want to traverse from the outermost
2633 // to the innermost while checking template-parameter-lists.
2634 std::reverse(NestedTypes.begin(), NestedTypes.end());
2636 // C++0x [temp.expl.spec]p17:
2637 // A member or a member template may be nested within many
2638 // enclosing class templates. In an explicit specialization for
2639 // such a member, the member declaration shall be preceded by a
2640 // template<> for each enclosing class template that is
2641 // explicitly specialized.
2642 bool SawNonEmptyTemplateParameterList = false;
2644 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2645 if (SawNonEmptyTemplateParameterList) {
2646 Diag(DeclLoc, diag::err_specialize_member_of_template)
2647 << !Recovery << Range;
2649 IsMemberSpecialization = false;
2656 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2657 // Check that we can have an explicit specialization here.
2658 if (CheckExplicitSpecialization(Range, true))
2661 // We don't have a template header, but we should.
2662 SourceLocation ExpectedTemplateLoc;
2663 if (!ParamLists.empty())
2664 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2666 ExpectedTemplateLoc = DeclStartLoc;
2668 Diag(DeclLoc, diag::err_template_spec_needs_header)
2670 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2674 unsigned ParamIdx = 0;
2675 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2677 T = NestedTypes[TypeIdx];
2679 // Whether we expect a 'template<>' header.
2680 bool NeedEmptyTemplateHeader = false;
2682 // Whether we expect a template header with parameters.
2683 bool NeedNonemptyTemplateHeader = false;
2685 // For a dependent type, the set of template parameters that we
2687 TemplateParameterList *ExpectedTemplateParams = nullptr;
2689 // C++0x [temp.expl.spec]p15:
2690 // A member or a member template may be nested within many enclosing
2691 // class templates. In an explicit specialization for such a member, the
2692 // member declaration shall be preceded by a template<> for each
2693 // enclosing class template that is explicitly specialized.
2694 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2695 if (ClassTemplatePartialSpecializationDecl *Partial
2696 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2697 ExpectedTemplateParams = Partial->getTemplateParameters();
2698 NeedNonemptyTemplateHeader = true;
2699 } else if (Record->isDependentType()) {
2700 if (Record->getDescribedClassTemplate()) {
2701 ExpectedTemplateParams = Record->getDescribedClassTemplate()
2702 ->getTemplateParameters();
2703 NeedNonemptyTemplateHeader = true;
2705 } else if (ClassTemplateSpecializationDecl *Spec
2706 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2707 // C++0x [temp.expl.spec]p4:
2708 // Members of an explicitly specialized class template are defined
2709 // in the same manner as members of normal classes, and not using
2710 // the template<> syntax.
2711 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2712 NeedEmptyTemplateHeader = true;
2715 } else if (Record->getTemplateSpecializationKind()) {
2716 if (Record->getTemplateSpecializationKind()
2717 != TSK_ExplicitSpecialization &&
2718 TypeIdx == NumTypes - 1)
2719 IsMemberSpecialization = true;
2723 } else if (const TemplateSpecializationType *TST
2724 = T->getAs<TemplateSpecializationType>()) {
2725 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2726 ExpectedTemplateParams = Template->getTemplateParameters();
2727 NeedNonemptyTemplateHeader = true;
2729 } else if (T->getAs<DependentTemplateSpecializationType>()) {
2730 // FIXME: We actually could/should check the template arguments here
2731 // against the corresponding template parameter list.
2732 NeedNonemptyTemplateHeader = false;
2735 // C++ [temp.expl.spec]p16:
2736 // In an explicit specialization declaration for a member of a class
2737 // template or a member template that ap- pears in namespace scope, the
2738 // member template and some of its enclosing class templates may remain
2739 // unspecialized, except that the declaration shall not explicitly
2740 // specialize a class member template if its en- closing class templates
2741 // are not explicitly specialized as well.
2742 if (ParamIdx < ParamLists.size()) {
2743 if (ParamLists[ParamIdx]->size() == 0) {
2744 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2748 SawNonEmptyTemplateParameterList = true;
2751 if (NeedEmptyTemplateHeader) {
2752 // If we're on the last of the types, and we need a 'template<>' header
2753 // here, then it's a member specialization.
2754 if (TypeIdx == NumTypes - 1)
2755 IsMemberSpecialization = true;
2757 if (ParamIdx < ParamLists.size()) {
2758 if (ParamLists[ParamIdx]->size() > 0) {
2759 // The header has template parameters when it shouldn't. Complain.
2760 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2761 diag::err_template_param_list_matches_nontemplate)
2763 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2764 ParamLists[ParamIdx]->getRAngleLoc())
2765 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2770 // Consume this template header.
2776 if (DiagnoseMissingExplicitSpecialization(
2777 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
2783 if (NeedNonemptyTemplateHeader) {
2784 // In friend declarations we can have template-ids which don't
2785 // depend on the corresponding template parameter lists. But
2786 // assume that empty parameter lists are supposed to match this
2788 if (IsFriend && T->isDependentType()) {
2789 if (ParamIdx < ParamLists.size() &&
2790 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
2791 ExpectedTemplateParams = nullptr;
2796 if (ParamIdx < ParamLists.size()) {
2797 // Check the template parameter list, if we can.
2798 if (ExpectedTemplateParams &&
2799 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
2800 ExpectedTemplateParams,
2801 true, TPL_TemplateMatch))
2805 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
2806 TPC_ClassTemplateMember))
2813 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2815 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2821 // If there were at least as many template-ids as there were template
2822 // parameter lists, then there are no template parameter lists remaining for
2823 // the declaration itself.
2824 if (ParamIdx >= ParamLists.size()) {
2825 if (TemplateId && !IsFriend) {
2826 // We don't have a template header for the declaration itself, but we
2828 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2829 TemplateId->RAngleLoc));
2831 // Fabricate an empty template parameter list for the invented header.
2832 return TemplateParameterList::Create(Context, SourceLocation(),
2833 SourceLocation(), None,
2834 SourceLocation(), nullptr);
2840 // If there were too many template parameter lists, complain about that now.
2841 if (ParamIdx < ParamLists.size() - 1) {
2842 bool HasAnyExplicitSpecHeader = false;
2843 bool AllExplicitSpecHeaders = true;
2844 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
2845 if (ParamLists[I]->size() == 0)
2846 HasAnyExplicitSpecHeader = true;
2848 AllExplicitSpecHeaders = false;
2851 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2852 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
2853 : diag::err_template_spec_extra_headers)
2854 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
2855 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
2857 // If there was a specialization somewhere, such that 'template<>' is
2858 // not required, and there were any 'template<>' headers, note where the
2859 // specialization occurred.
2860 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
2861 Diag(ExplicitSpecLoc,
2862 diag::note_explicit_template_spec_does_not_need_header)
2863 << NestedTypes.back();
2865 // We have a template parameter list with no corresponding scope, which
2866 // means that the resulting template declaration can't be instantiated
2867 // properly (we'll end up with dependent nodes when we shouldn't).
2868 if (!AllExplicitSpecHeaders)
2872 // C++ [temp.expl.spec]p16:
2873 // In an explicit specialization declaration for a member of a class
2874 // template or a member template that ap- pears in namespace scope, the
2875 // member template and some of its enclosing class templates may remain
2876 // unspecialized, except that the declaration shall not explicitly
2877 // specialize a class member template if its en- closing class templates
2878 // are not explicitly specialized as well.
2879 if (ParamLists.back()->size() == 0 &&
2880 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2884 // Return the last template parameter list, which corresponds to the
2885 // entity being declared.
2886 return ParamLists.back();
2889 void Sema::NoteAllFoundTemplates(TemplateName Name) {
2890 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2891 Diag(Template->getLocation(), diag::note_template_declared_here)
2892 << (isa<FunctionTemplateDecl>(Template)
2894 : isa<ClassTemplateDecl>(Template)
2896 : isa<VarTemplateDecl>(Template)
2898 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2899 << Template->getDeclName();
2903 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
2904 for (OverloadedTemplateStorage::iterator I = OST->begin(),
2907 Diag((*I)->getLocation(), diag::note_template_declared_here)
2908 << 0 << (*I)->getDeclName();
2915 checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
2916 const SmallVectorImpl<TemplateArgument> &Converted,
2917 SourceLocation TemplateLoc,
2918 TemplateArgumentListInfo &TemplateArgs) {
2919 ASTContext &Context = SemaRef.getASTContext();
2920 switch (BTD->getBuiltinTemplateKind()) {
2921 case BTK__make_integer_seq: {
2922 // Specializations of __make_integer_seq<S, T, N> are treated like
2923 // S<T, 0, ..., N-1>.
2925 // C++14 [inteseq.intseq]p1:
2926 // T shall be an integer type.
2927 if (!Converted[1].getAsType()->isIntegralType(Context)) {
2928 SemaRef.Diag(TemplateArgs[1].getLocation(),
2929 diag::err_integer_sequence_integral_element_type);
2933 // C++14 [inteseq.make]p1:
2934 // If N is negative the program is ill-formed.
2935 TemplateArgument NumArgsArg = Converted[2];
2936 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2938 SemaRef.Diag(TemplateArgs[2].getLocation(),
2939 diag::err_integer_sequence_negative_length);
2943 QualType ArgTy = NumArgsArg.getIntegralType();
2944 TemplateArgumentListInfo SyntheticTemplateArgs;
2945 // The type argument gets reused as the first template argument in the
2946 // synthetic template argument list.
2947 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2948 // Expand N into 0 ... N-1.
2949 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2951 TemplateArgument TA(Context, I, ArgTy);
2952 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
2953 TA, ArgTy, TemplateArgs[2].getLocation()));
2955 // The first template argument will be reused as the template decl that
2956 // our synthetic template arguments will be applied to.
2957 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2958 TemplateLoc, SyntheticTemplateArgs);
2961 case BTK__type_pack_element:
2962 // Specializations of
2963 // __type_pack_element<Index, T_1, ..., T_N>
2964 // are treated like T_Index.
2965 assert(Converted.size() == 2 &&
2966 "__type_pack_element should be given an index and a parameter pack");
2968 // If the Index is out of bounds, the program is ill-formed.
2969 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
2970 llvm::APSInt Index = IndexArg.getAsIntegral();
2971 assert(Index >= 0 && "the index used with __type_pack_element should be of "
2972 "type std::size_t, and hence be non-negative");
2973 if (Index >= Ts.pack_size()) {
2974 SemaRef.Diag(TemplateArgs[0].getLocation(),
2975 diag::err_type_pack_element_out_of_bounds);
2979 // We simply return the type at index `Index`.
2980 auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
2981 return Nth->getAsType();
2983 llvm_unreachable("unexpected BuiltinTemplateDecl!");
2986 /// Determine whether this alias template is "enable_if_t".
2987 static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
2988 return AliasTemplate->getName().equals("enable_if_t");
2991 /// Collect all of the separable terms in the given condition, which
2992 /// might be a conjunction.
2994 /// FIXME: The right answer is to convert the logical expression into
2995 /// disjunctive normal form, so we can find the first failed term
2996 /// within each possible clause.
2997 static void collectConjunctionTerms(Expr *Clause,
2998 SmallVectorImpl<Expr *> &Terms) {
2999 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3000 if (BinOp->getOpcode() == BO_LAnd) {
3001 collectConjunctionTerms(BinOp->getLHS(), Terms);
3002 collectConjunctionTerms(BinOp->getRHS(), Terms);
3008 Terms.push_back(Clause);
3011 // The ranges-v3 library uses an odd pattern of a top-level "||" with
3012 // a left-hand side that is value-dependent but never true. Identify
3013 // the idiom and ignore that term.
3014 static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
3016 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3017 if (!BinOp) return Cond;
3019 if (BinOp->getOpcode() != BO_LOr) return Cond;
3021 // With an inner '==' that has a literal on the right-hand side.
3022 Expr *LHS = BinOp->getLHS();
3023 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3024 if (!InnerBinOp) return Cond;
3026 if (InnerBinOp->getOpcode() != BO_EQ ||
3027 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3030 // If the inner binary operation came from a macro expansion named
3031 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3032 // of the '||', which is the real, user-provided condition.
3033 SourceLocation Loc = InnerBinOp->getExprLoc();
3034 if (!Loc.isMacroID()) return Cond;
3036 StringRef MacroName = PP.getImmediateMacroName(Loc);
3037 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3038 return BinOp->getRHS();
3043 std::pair<Expr *, std::string>
3044 Sema::findFailedBooleanCondition(Expr *Cond, bool AllowTopLevelCond) {
3045 Cond = lookThroughRangesV3Condition(PP, Cond);
3047 // Separate out all of the terms in a conjunction.
3048 SmallVector<Expr *, 4> Terms;
3049 collectConjunctionTerms(Cond, Terms);
3051 // Determine which term failed.
3052 Expr *FailedCond = nullptr;
3053 for (Expr *Term : Terms) {
3054 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3056 // Literals are uninteresting.
3057 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3058 isa<IntegerLiteral>(TermAsWritten))
3061 // The initialization of the parameter from the argument is
3062 // a constant-evaluated context.
3063 EnterExpressionEvaluationContext ConstantEvaluated(
3064 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
3067 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3069 FailedCond = TermAsWritten;
3075 if (!AllowTopLevelCond)
3076 return { nullptr, "" };
3078 FailedCond = Cond->IgnoreParenImpCasts();
3081 std::string Description;
3083 llvm::raw_string_ostream Out(Description);
3084 FailedCond->printPretty(Out, nullptr, getPrintingPolicy());
3086 return { FailedCond, Description };
3089 QualType Sema::CheckTemplateIdType(TemplateName Name,
3090 SourceLocation TemplateLoc,
3091 TemplateArgumentListInfo &TemplateArgs) {
3092 DependentTemplateName *DTN
3093 = Name.getUnderlying().getAsDependentTemplateName();
3094 if (DTN && DTN->isIdentifier())
3095 // When building a template-id where the template-name is dependent,
3096 // assume the template is a type template. Either our assumption is
3097 // correct, or the code is ill-formed and will be diagnosed when the
3098 // dependent name is substituted.
3099 return Context.getDependentTemplateSpecializationType(ETK_None,
3100 DTN->getQualifier(),
3101 DTN->getIdentifier(),
3104 TemplateDecl *Template = Name.getAsTemplateDecl();
3105 if (!Template || isa<FunctionTemplateDecl>(Template) ||
3106 isa<VarTemplateDecl>(Template)) {
3107 // We might have a substituted template template parameter pack. If so,
3108 // build a template specialization type for it.
3109 if (Name.getAsSubstTemplateTemplateParmPack())
3110 return Context.getTemplateSpecializationType(Name, TemplateArgs);
3112 Diag(TemplateLoc, diag::err_template_id_not_a_type)
3114 NoteAllFoundTemplates(Name);
3118 // Check that the template argument list is well-formed for this
3120 SmallVector<TemplateArgument, 4> Converted;
3121 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3127 bool InstantiationDependent = false;
3128 if (TypeAliasTemplateDecl *AliasTemplate =
3129 dyn_cast<TypeAliasTemplateDecl>(Template)) {
3130 // Find the canonical type for this type alias template specialization.
3131 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3132 if (Pattern->isInvalidDecl())
3135 TemplateArgumentList StackTemplateArgs(TemplateArgumentList::OnStack,
3138 // Only substitute for the innermost template argument list.
3139 MultiLevelTemplateArgumentList TemplateArgLists;
3140 TemplateArgLists.addOuterTemplateArguments(&StackTemplateArgs);
3141 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
3142 for (unsigned I = 0; I < Depth; ++I)
3143 TemplateArgLists.addOuterTemplateArguments(None);
3145 LocalInstantiationScope Scope(*this);
3146 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
3147 if (Inst.isInvalid())
3150 CanonType = SubstType(Pattern->getUnderlyingType(),
3151 TemplateArgLists, AliasTemplate->getLocation(),
3152 AliasTemplate->getDeclName());
3153 if (CanonType.isNull()) {
3154 // If this was enable_if and we failed to find the nested type
3155 // within enable_if in a SFINAE context, dig out the specific
3156 // enable_if condition that failed and present that instead.
3157 if (isEnableIfAliasTemplate(AliasTemplate)) {
3158 if (auto DeductionInfo = isSFINAEContext()) {
3159 if (*DeductionInfo &&
3160 (*DeductionInfo)->hasSFINAEDiagnostic() &&
3161 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3162 diag::err_typename_nested_not_found_enable_if &&
3163 TemplateArgs[0].getArgument().getKind()
3164 == TemplateArgument::Expression) {
3166 std::string FailedDescription;
3167 std::tie(FailedCond, FailedDescription) =
3168 findFailedBooleanCondition(
3169 TemplateArgs[0].getSourceExpression(),
3170 /*AllowTopLevelCond=*/true);
3172 // Remove the old SFINAE diagnostic.
3173 PartialDiagnosticAt OldDiag =
3174 {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3175 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3177 // Add a new SFINAE diagnostic specifying which condition
3179 (*DeductionInfo)->addSFINAEDiagnostic(
3181 PDiag(diag::err_typename_nested_not_found_requirement)
3182 << FailedDescription
3183 << FailedCond->getSourceRange());
3190 } else if (Name.isDependent() ||
3191 TemplateSpecializationType::anyDependentTemplateArguments(
3192 TemplateArgs, InstantiationDependent)) {
3193 // This class template specialization is a dependent
3194 // type. Therefore, its canonical type is another class template
3195 // specialization type that contains all of the converted
3196 // arguments in canonical form. This ensures that, e.g., A<T> and
3197 // A<T, T> have identical types when A is declared as:
3199 // template<typename T, typename U = T> struct A;
3200 CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
3202 // This might work out to be a current instantiation, in which
3203 // case the canonical type needs to be the InjectedClassNameType.
3205 // TODO: in theory this could be a simple hashtable lookup; most
3206 // changes to CurContext don't change the set of current
3208 if (isa<ClassTemplateDecl>(Template)) {
3209 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3210 // If we get out to a namespace, we're done.
3211 if (Ctx->isFileContext()) break;
3213 // If this isn't a record, keep looking.
3214 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3215 if (!Record) continue;
3217 // Look for one of the two cases with InjectedClassNameTypes
3218 // and check whether it's the same template.
3219 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3220 !Record->getDescribedClassTemplate())
3223 // Fetch the injected class name type and check whether its
3224 // injected type is equal to the type we just built.
3225 QualType ICNT = Context.getTypeDeclType(Record);
3226 QualType Injected = cast<InjectedClassNameType>(ICNT)
3227 ->getInjectedSpecializationType();
3229 if (CanonType != Injected->getCanonicalTypeInternal())
3232 // If so, the canonical type of this TST is the injected
3233 // class name type of the record we just found.
3234 assert(ICNT.isCanonical());
3239 } else if (ClassTemplateDecl *ClassTemplate
3240 = dyn_cast<ClassTemplateDecl>(Template)) {
3241 // Find the class template specialization declaration that
3242 // corresponds to these arguments.
3243 void *InsertPos = nullptr;
3244 ClassTemplateSpecializationDecl *Decl
3245 = ClassTemplate->findSpecialization(Converted, InsertPos);
3247 // This is the first time we have referenced this class template
3248 // specialization. Create the canonical declaration and add it to
3249 // the set of specializations.
3250 Decl = ClassTemplateSpecializationDecl::Create(Context,
3251 ClassTemplate->getTemplatedDecl()->getTagKind(),
3252 ClassTemplate->getDeclContext(),
3253 ClassTemplate->getTemplatedDecl()->getLocStart(),
3254 ClassTemplate->getLocation(),
3256 Converted, nullptr);
3257 ClassTemplate->AddSpecialization(Decl, InsertPos);
3258 if (ClassTemplate->isOutOfLine())
3259 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3262 if (Decl->getSpecializationKind() == TSK_Undeclared) {
3263 MultiLevelTemplateArgumentList TemplateArgLists;
3264 TemplateArgLists.addOuterTemplateArguments(Converted);
3265 InstantiateAttrsForDecl(TemplateArgLists, ClassTemplate->getTemplatedDecl(),
3269 // Diagnose uses of this specialization.
3270 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3272 CanonType = Context.getTypeDeclType(Decl);
3273 assert(isa<RecordType>(CanonType) &&
3274 "type of non-dependent specialization is not a RecordType");
3275 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3276 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
3280 // Build the fully-sugared type for this class template
3281 // specialization, which refers back to the class template
3282 // specialization we created or found.
3283 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
3287 Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3288 TemplateTy TemplateD, IdentifierInfo *TemplateII,
3289 SourceLocation TemplateIILoc,
3290 SourceLocation LAngleLoc,
3291 ASTTemplateArgsPtr TemplateArgsIn,
3292 SourceLocation RAngleLoc,
3293 bool IsCtorOrDtorName, bool IsClassName) {
3297 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3298 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3300 // C++ [temp.res]p3:
3301 // A qualified-id that refers to a type and in which the
3302 // nested-name-specifier depends on a template-parameter (14.6.2)
3303 // shall be prefixed by the keyword typename to indicate that the
3304 // qualified-id denotes a type, forming an
3305 // elaborated-type-specifier (7.1.5.3).
3306 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
3307 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
3308 << SS.getScopeRep() << TemplateII->getName();
3309 // Recover as if 'typename' were specified.
3310 // FIXME: This is not quite correct recovery as we don't transform SS
3311 // into the corresponding dependent form (and we don't diagnose missing
3312 // 'template' keywords within SS as a result).
3313 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3314 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3315 TemplateArgsIn, RAngleLoc);
3318 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3319 // it's not actually allowed to be used as a type in most cases. Because
3320 // we annotate it before we know whether it's valid, we have to check for
3322 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
3323 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3325 TemplateKWLoc.isInvalid()
3326 ? diag::err_out_of_line_qualified_id_type_names_constructor
3327 : diag::ext_out_of_line_qualified_id_type_names_constructor)
3328 << TemplateII << 0 /*injected-class-name used as template name*/
3329 << 1 /*if any keyword was present, it was 'template'*/;
3333 TemplateName Template = TemplateD.get();
3335 // Translate the parser's template argument list in our AST format.
3336 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3337 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3339 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3341 = Context.getDependentTemplateSpecializationType(ETK_None,
3342 DTN->getQualifier(),
3343 DTN->getIdentifier(),
3345 // Build type-source information.
3347 DependentTemplateSpecializationTypeLoc SpecTL
3348 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3349 SpecTL.setElaboratedKeywordLoc(SourceLocation());
3350 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3351 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3352 SpecTL.setTemplateNameLoc(TemplateIILoc);
3353 SpecTL.setLAngleLoc(LAngleLoc);
3354 SpecTL.setRAngleLoc(RAngleLoc);
3355 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3356 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3357 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3360 QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
3361 if (Result.isNull())
3364 // Build type-source information.
3366 TemplateSpecializationTypeLoc SpecTL
3367 = TLB.push<TemplateSpecializationTypeLoc>(Result);
3368 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3369 SpecTL.setTemplateNameLoc(TemplateIILoc);
3370 SpecTL.setLAngleLoc(LAngleLoc);
3371 SpecTL.setRAngleLoc(RAngleLoc);
3372 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3373 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3375 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
3376 // constructor or destructor name (in such a case, the scope specifier
3377 // will be attached to the enclosing Decl or Expr node).
3378 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
3379 // Create an elaborated-type-specifier containing the nested-name-specifier.
3380 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
3381 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
3382 ElabTL.setElaboratedKeywordLoc(SourceLocation());
3383 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3386 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
3389 TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
3390 TypeSpecifierType TagSpec,
3391 SourceLocation TagLoc,
3393 SourceLocation TemplateKWLoc,
3394 TemplateTy TemplateD,
3395 SourceLocation TemplateLoc,
3396 SourceLocation LAngleLoc,
3397 ASTTemplateArgsPtr TemplateArgsIn,
3398 SourceLocation RAngleLoc) {
3399 TemplateName Template = TemplateD.get();
3401 // Translate the parser's template argument list in our AST format.
3402 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3403 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3405 // Determine the tag kind
3406 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3407 ElaboratedTypeKeyword Keyword
3408 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
3410 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3411 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
3412 DTN->getQualifier(),
3413 DTN->getIdentifier(),
3416 // Build type-source information.
3418 DependentTemplateSpecializationTypeLoc SpecTL
3419 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3420 SpecTL.setElaboratedKeywordLoc(TagLoc);
3421 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3422 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3423 SpecTL.setTemplateNameLoc(TemplateLoc);
3424 SpecTL.setLAngleLoc(LAngleLoc);
3425 SpecTL.setRAngleLoc(RAngleLoc);
3426 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3427 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3428 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3431 if (TypeAliasTemplateDecl *TAT =
3432 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3433 // C++0x [dcl.type.elab]p2:
3434 // If the identifier resolves to a typedef-name or the simple-template-id
3435 // resolves to an alias template specialization, the
3436 // elaborated-type-specifier is ill-formed.
3437 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3438 << TAT << NTK_TypeAliasTemplate << TagKind;
3439 Diag(TAT->getLocation(), diag::note_declared_at);
3442 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3443 if (Result.isNull())
3444 return TypeResult(true);
3446 // Check the tag kind
3447 if (const RecordType *RT = Result->getAs<RecordType>()) {
3448 RecordDecl *D = RT->getDecl();
3450 IdentifierInfo *Id = D->getIdentifier();
3451 assert(Id && "templated class must have an identifier");
3453 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
3455 Diag(TagLoc, diag::err_use_with_wrong_tag)
3457 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
3458 Diag(D->getLocation(), diag::note_previous_use);
3462 // Provide source-location information for the template specialization.
3464 TemplateSpecializationTypeLoc SpecTL
3465 = TLB.push<TemplateSpecializationTypeLoc>(Result);
3466 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3467 SpecTL.setTemplateNameLoc(TemplateLoc);
3468 SpecTL.setLAngleLoc(LAngleLoc);
3469 SpecTL.setRAngleLoc(RAngleLoc);
3470 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3471 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3473 // Construct an elaborated type containing the nested-name-specifier (if any)
3475 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
3476 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
3477 ElabTL.setElaboratedKeywordLoc(TagLoc);
3478 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3479 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
3482 static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3483 NamedDecl *PrevDecl,
3485 bool IsPartialSpecialization);
3487 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
3489 static bool isTemplateArgumentTemplateParameter(
3490 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3491 switch (Arg.getKind()) {
3492 case TemplateArgument::Null:
3493 case TemplateArgument::NullPtr:
3494 case TemplateArgument::Integral:
3495 case TemplateArgument::Declaration:
3496 case TemplateArgument::Pack:
3497 case TemplateArgument::TemplateExpansion:
3500 case TemplateArgument::Type: {
3501 QualType Type = Arg.getAsType();
3502 const TemplateTypeParmType *TPT =
3503 Arg.getAsType()->getAs<TemplateTypeParmType>();
3504 return TPT && !Type.hasQualifiers() &&
3505 TPT->getDepth() == Depth && TPT->getIndex() == Index;
3508 case TemplateArgument::Expression: {
3509 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3510 if (!DRE || !DRE->getDecl())
3512 const NonTypeTemplateParmDecl *NTTP =
3513 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3514 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3517 case TemplateArgument::Template:
3518 const TemplateTemplateParmDecl *TTP =
3519 dyn_cast_or_null<TemplateTemplateParmDecl>(
3520 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
3521 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3523 llvm_unreachable("unexpected kind of template argument");
3526 static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
3527 ArrayRef<TemplateArgument> Args) {
3528 if (Params->size() != Args.size())
3531 unsigned Depth = Params->getDepth();
3533 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3534 TemplateArgument Arg = Args[I];
3536 // If the parameter is a pack expansion, the argument must be a pack
3537 // whose only element is a pack expansion.
3538 if (Params->getParam(I)->isParameterPack()) {
3539 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
3540 !Arg.pack_begin()->isPackExpansion())
3542 Arg = Arg.pack_begin()->getPackExpansionPattern();
3545 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
3552 /// Convert the parser's template argument list representation into our form.
3553 static TemplateArgumentListInfo
3554 makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
3555 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
3556 TemplateId.RAngleLoc);
3557 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
3558 TemplateId.NumArgs);
3559 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
3560 return TemplateArgs;
3563 template<typename PartialSpecDecl>
3564 static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
3565 if (Partial->getDeclContext()->isDependentContext())
3568 // FIXME: Get the TDK from deduction in order to provide better diagnostics
3569 // for non-substitution-failure issues?
3570 TemplateDeductionInfo Info(Partial->getLocation());
3571 if (S.isMoreSpecializedThanPrimary(Partial, Info))
3574 auto *Template = Partial->getSpecializedTemplate();
3575 S.Diag(Partial->getLocation(),
3576 diag::ext_partial_spec_not_more_specialized_than_primary)
3577 << isa<VarTemplateDecl>(Template);
3579 if (Info.hasSFINAEDiagnostic()) {
3580 PartialDiagnosticAt Diag = {SourceLocation(),
3581 PartialDiagnostic::NullDiagnostic()};
3582 Info.takeSFINAEDiagnostic(Diag);
3583 SmallString<128> SFINAEArgString;
3584 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
3586 diag::note_partial_spec_not_more_specialized_than_primary)
3590 S.Diag(Template->getLocation(), diag::note_template_decl_here);
3594 noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
3595 const llvm::SmallBitVector &DeducibleParams) {
3596 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3597 if (!DeducibleParams[I]) {
3598 NamedDecl *Param = TemplateParams->getParam(I);
3599 if (Param->getDeclName())
3600 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3601 << Param->getDeclName();
3603 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3610 template<typename PartialSpecDecl>
3611 static void checkTemplatePartialSpecialization(Sema &S,
3612 PartialSpecDecl *Partial) {
3613 // C++1z [temp.class.spec]p8: (DR1495)
3614 // - The specialization shall be more specialized than the primary
3615 // template (14.5.5.2).
3616 checkMoreSpecializedThanPrimary(S, Partial);
3618 // C++ [temp.class.spec]p8: (DR1315)
3619 // - Each template-parameter shall appear at least once in the
3620 // template-id outside a non-deduced context.
3621 // C++1z [temp.class.spec.match]p3 (P0127R2)
3622 // If the template arguments of a partial specialization cannot be
3623 // deduced because of the structure of its template-parameter-list
3624 // and the template-id, the program is ill-formed.
3625 auto *TemplateParams = Partial->getTemplateParameters();
3626 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3627 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3628 TemplateParams->getDepth(), DeducibleParams);
3630 if (!DeducibleParams.all()) {
3631 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3632 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
3633 << isa<VarTemplatePartialSpecializationDecl>(Partial)
3634 << (NumNonDeducible > 1)
3635 << SourceRange(Partial->getLocation(),
3636 Partial->getTemplateArgsAsWritten()->RAngleLoc);
3637 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
3641 void Sema::CheckTemplatePartialSpecialization(
3642 ClassTemplatePartialSpecializationDecl *Partial) {
3643 checkTemplatePartialSpecialization(*this, Partial);
3646 void Sema::CheckTemplatePartialSpecialization(
3647 VarTemplatePartialSpecializationDecl *Partial) {
3648 checkTemplatePartialSpecialization(*this, Partial);
3651 void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
3652 // C++1z [temp.param]p11:
3653 // A template parameter of a deduction guide template that does not have a
3654 // default-argument shall be deducible from the parameter-type-list of the
3655 // deduction guide template.
3656 auto *TemplateParams = TD->getTemplateParameters();
3657 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3658 MarkDeducedTemplateParameters(TD, DeducibleParams);
3659 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
3660 // A parameter pack is deducible (to an empty pack).
3661 auto *Param = TemplateParams->getParam(I);
3662 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
3663 DeducibleParams[I] = true;
3666 if (!DeducibleParams.all()) {
3667 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3668 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
3669 << (NumNonDeducible > 1);
3670 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
3674 DeclResult Sema::ActOnVarTemplateSpecialization(
3675 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
3676 TemplateParameterList *TemplateParams, StorageClass SC,
3677 bool IsPartialSpecialization) {
3678 // D must be variable template id.
3679 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
3680 "Variable template specialization is declared with a template it.");
3682 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
3683 TemplateArgumentListInfo TemplateArgs =
3684 makeTemplateArgumentListInfo(*this, *TemplateId);
3685 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
3686 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
3687 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
3689 TemplateName Name = TemplateId->Template.get();
3691 // The template-id must name a variable template.
3692 VarTemplateDecl *VarTemplate =
3693 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
3695 NamedDecl *FnTemplate;
3696 if (auto *OTS = Name.getAsOverloadedTemplate())
3697 FnTemplate = *OTS->begin();
3699 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
3701 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
3702 << FnTemplate->getDeclName();
3703 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
3704 << IsPartialSpecialization;
3707 // Check for unexpanded parameter packs in any of the template arguments.
3708 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3709 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
3710 UPPC_PartialSpecialization))
3713 // Check that the template argument list is well-formed for this
3715 SmallVector<TemplateArgument, 4> Converted;
3716 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
3720 // Find the variable template (partial) specialization declaration that
3721 // corresponds to these arguments.
3722 if (IsPartialSpecialization) {
3723 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
3724 TemplateArgs.size(), Converted))
3727 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
3728 // also do them during instantiation.
3729 bool InstantiationDependent;
3730 if (!Name.isDependent() &&
3731 !TemplateSpecializationType::anyDependentTemplateArguments(
3732 TemplateArgs.arguments(),
3733 InstantiationDependent)) {
3734 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3735 << VarTemplate->getDeclName();
3736 IsPartialSpecialization = false;
3739 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
3741 // C++ [temp.class.spec]p9b3:
3743 // -- The argument list of the specialization shall not be identical
3744 // to the implicit argument list of the primary template.
3745 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
3746 << /*variable template*/ 1
3747 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
3748 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
3749 // FIXME: Recover from this by treating the declaration as a redeclaration
3750 // of the primary template.
3755 void *InsertPos = nullptr;
3756 VarTemplateSpecializationDecl *PrevDecl = nullptr;
3758 if (IsPartialSpecialization)
3759 // FIXME: Template parameter list matters too
3760 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
3762 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
3764 VarTemplateSpecializationDecl *Specialization = nullptr;
3766 // Check whether we can declare a variable template specialization in
3767 // the current scope.
3768 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
3770 IsPartialSpecialization))
3773 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3774 // Since the only prior variable template specialization with these
3775 // arguments was referenced but not declared, reuse that
3776 // declaration node as our own, updating its source location and
3777 // the list of outer template parameters to reflect our new declaration.
3778 Specialization = PrevDecl;
3779 Specialization->setLocation(TemplateNameLoc);
3781 } else if (IsPartialSpecialization) {
3782 // Create a new class template partial specialization declaration node.
3783 VarTemplatePartialSpecializationDecl *PrevPartial =
3784 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
3785 VarTemplatePartialSpecializationDecl *Partial =
3786 VarTemplatePartialSpecializationDecl::Create(
3787 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
3788 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
3789 Converted, TemplateArgs);
3792 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
3793 Specialization = Partial;
3795 // If we are providing an explicit specialization of a member variable
3796 // template specialization, make a note of that.
3797 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3798 PrevPartial->setMemberSpecialization();
3800 CheckTemplatePartialSpecialization(Partial);
3802 // Create a new class template specialization declaration node for
3803 // this explicit specialization or friend declaration.
3804 Specialization = VarTemplateSpecializationDecl::Create(
3805 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
3806 VarTemplate, DI->getType(), DI, SC, Converted);
3807 Specialization->setTemplateArgsInfo(TemplateArgs);
3810 VarTemplate->AddSpecialization(Specialization, InsertPos);
3813 // C++ [temp.expl.spec]p6:
3814 // If a template, a member template or the member of a class template is
3815 // explicitly specialized then that specialization shall be declared
3816 // before the first use of that specialization that would cause an implicit
3817 // instantiation to take place, in every translation unit in which such a
3818 // use occurs; no diagnostic is required.
3819 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3821 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
3822 // Is there any previous explicit specialization declaration?
3823 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3830 SourceRange Range(TemplateNameLoc, RAngleLoc);
3831 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3834 Diag(PrevDecl->getPointOfInstantiation(),
3835 diag::note_instantiation_required_here)
3836 << (PrevDecl->getTemplateSpecializationKind() !=
3837 TSK_ImplicitInstantiation);
3842 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
3843 Specialization->setLexicalDeclContext(CurContext);
3845 // Add the specialization into its lexical context, so that it can
3846 // be seen when iterating through the list of declarations in that
3847 // context. However, specializations are not found by name lookup.
3848 CurContext->addDecl(Specialization);
3850 // Note that this is an explicit specialization.
3851 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
3854 // Check that this isn't a redefinition of this specialization,
3855 // merging with previous declarations.
3856 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
3857 forRedeclarationInCurContext());
3858 PrevSpec.addDecl(PrevDecl);
3859 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
3860 } else if (Specialization->isStaticDataMember() &&
3861 Specialization->isOutOfLine()) {
3862 Specialization->setAccess(VarTemplate->getAccess());
3865 // Link instantiations of static data members back to the template from
3866 // which they were instantiated.
3867 if (Specialization->isStaticDataMember())
3868 Specialization->setInstantiationOfStaticDataMember(
3869 VarTemplate->getTemplatedDecl(),
3870 Specialization->getSpecializationKind());
3872 return Specialization;
3876 /// A partial specialization whose template arguments have matched
3877 /// a given template-id.
3878 struct PartialSpecMatchResult {
3879 VarTemplatePartialSpecializationDecl *Partial;
3880 TemplateArgumentList *Args;
3882 } // end anonymous namespace
3885 Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
3886 SourceLocation TemplateNameLoc,
3887 const TemplateArgumentListInfo &TemplateArgs) {
3888 assert(Template && "A variable template id without template?");
3890 // Check that the template argument list is well-formed for this template.
3891 SmallVector<TemplateArgument, 4> Converted;
3892 if (CheckTemplateArgumentList(
3893 Template, TemplateNameLoc,
3894 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
3898 // Find the variable template specialization declaration that
3899 // corresponds to these arguments.
3900 void *InsertPos = nullptr;
3901 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
3902 Converted, InsertPos)) {
3903 checkSpecializationVisibility(TemplateNameLoc, Spec);
3904 // If we already have a variable template specialization, return it.
3908 // This is the first time we have referenced this variable template
3909 // specialization. Create the canonical declaration and add it to
3910 // the set of specializations, based on the closest partial specialization
3911 // that it represents. That is,
3912 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
3913 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
3915 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
3916 bool AmbiguousPartialSpec = false;
3917 typedef PartialSpecMatchResult MatchResult;
3918 SmallVector<MatchResult, 4> Matched;
3919 SourceLocation PointOfInstantiation = TemplateNameLoc;
3920 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
3921 /*ForTakingAddress=*/false);
3923 // 1. Attempt to find the closest partial specialization that this
3924 // specializes, if any.
3925 // If any of the template arguments is dependent, then this is probably
3926 // a placeholder for an incomplete declarative context; which must be
3927 // complete by instantiation time. Thus, do not search through the partial
3928 // specializations yet.
3929 // TODO: Unify with InstantiateClassTemplateSpecialization()?
3930 // Perhaps better after unification of DeduceTemplateArguments() and
3931 // getMoreSpecializedPartialSpecialization().
3932 bool InstantiationDependent = false;
3933 if (!TemplateSpecializationType::anyDependentTemplateArguments(
3934 TemplateArgs, InstantiationDependent)) {
3936 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
3937 Template->getPartialSpecializations(PartialSpecs);
3939 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3940 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
3941 TemplateDeductionInfo Info(FailedCandidates.getLocation());
3943 if (TemplateDeductionResult Result =
3944 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
3945 // Store the failed-deduction information for use in diagnostics, later.
3946 // TODO: Actually use the failed-deduction info?
3947 FailedCandidates.addCandidate().set(
3948 DeclAccessPair::make(Template, AS_public), Partial,
3949 MakeDeductionFailureInfo(Context, Result, Info));
3952 Matched.push_back(PartialSpecMatchResult());
3953 Matched.back().Partial = Partial;
3954 Matched.back().Args = Info.take();
3958 if (Matched.size() >= 1) {
3959 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
3960 if (Matched.size() == 1) {
3961 // -- If exactly one matching specialization is found, the
3962 // instantiation is generated from that specialization.
3963 // We don't need to do anything for this.
3965 // -- If more than one matching specialization is found, the
3966 // partial order rules (14.5.4.2) are used to determine
3967 // whether one of the specializations is more specialized
3968 // than the others. If none of the specializations is more
3969 // specialized than all of the other matching
3970 // specializations, then the use of the variable template is
3971 // ambiguous and the program is ill-formed.
3972 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
3973 PEnd = Matched.end();
3975 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
3976 PointOfInstantiation) ==
3981 // Determine if the best partial specialization is more specialized than
3983 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
3984 PEnd = Matched.end();
3986 if (P != Best && getMoreSpecializedPartialSpecialization(
3987 P->Partial, Best->Partial,
3988 PointOfInstantiation) != Best->Partial) {
3989 AmbiguousPartialSpec = true;
3995 // Instantiate using the best variable template partial specialization.
3996 InstantiationPattern = Best->Partial;
3997 InstantiationArgs = Best->Args;
3999 // -- If no match is found, the instantiation is generated
4000 // from the primary template.
4001 // InstantiationPattern = Template->getTemplatedDecl();
4005 // 2. Create the canonical declaration.
4006 // Note that we do not instantiate a definition until we see an odr-use
4007 // in DoMarkVarDeclReferenced().
4008 // FIXME: LateAttrs et al.?
4009 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
4010 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
4011 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
4015 if (AmbiguousPartialSpec) {
4016 // Partial ordering did not produce a clear winner. Complain.
4017 Decl->setInvalidDecl();
4018 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4021 // Print the matching partial specializations.
4022 for (MatchResult P : Matched)
4023 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4024 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4029 if (VarTemplatePartialSpecializationDecl *D =
4030 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4031 Decl->setInstantiationOf(D, InstantiationArgs);
4033 checkSpecializationVisibility(TemplateNameLoc, Decl);
4035 assert(Decl && "No variable template specialization?");
4040 Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
4041 const DeclarationNameInfo &NameInfo,
4042 VarTemplateDecl *Template, SourceLocation TemplateLoc,
4043 const TemplateArgumentListInfo *TemplateArgs) {
4045 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4047 if (Decl.isInvalid())
4050 VarDecl *Var = cast<VarDecl>(Decl.get());
4051 if (!Var->getTemplateSpecializationKind())
4052 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
4055 // Build an ordinary singleton decl ref.
4056 return BuildDeclarationNameExpr(SS, NameInfo, Var,
4057 /*FoundD=*/nullptr, TemplateArgs);
4060 void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
4061 SourceLocation Loc) {
4062 Diag(Loc, diag::err_template_missing_args)
4063 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4064 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4065 Diag(TD->getLocation(), diag::note_template_decl_here)
4066 << TD->getTemplateParameters()->getSourceRange();
4070 ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
4071 SourceLocation TemplateKWLoc,
4074 const TemplateArgumentListInfo *TemplateArgs) {
4075 // FIXME: Can we do any checking at this point? I guess we could check the
4076 // template arguments that we have against the template name, if the template
4077 // name refers to a single template. That's not a terribly common case,
4079 // foo<int> could identify a single function unambiguously
4080 // This approach does NOT work, since f<int>(1);
4081 // gets resolved prior to resorting to overload resolution
4082 // i.e., template<class T> void f(double);
4083 // vs template<class T, class U> void f(U);
4085 // These should be filtered out by our callers.
4086 assert(!R.empty() && "empty lookup results when building templateid");
4087 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4089 // Non-function templates require a template argument list.
4090 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4091 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4092 diagnoseMissingTemplateArguments(TemplateName(TD), R.getNameLoc());
4097 auto AnyDependentArguments = [&]() -> bool {
4098 bool InstantiationDependent;
4099 return TemplateArgs &&
4100 TemplateSpecializationType::anyDependentTemplateArguments(
4101 *TemplateArgs, InstantiationDependent);
4104 // In C++1y, check variable template ids.
4105 if (R.getAsSingle<VarTemplateDecl>() && !AnyDependentArguments()) {
4106 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
4107 R.getAsSingle<VarTemplateDecl>(),
4108 TemplateKWLoc, TemplateArgs);
4111 // We don't want lookup warnings at this point.
4112 R.suppressDiagnostics();
4114 UnresolvedLookupExpr *ULE
4115 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
4116 SS.getWithLocInContext(Context),
4118 R.getLookupNameInfo(),
4119 RequiresADL, TemplateArgs,
4120 R.begin(), R.end());
4125 // We actually only call this from template instantiation.
4127 Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
4128 SourceLocation TemplateKWLoc,
4129 const DeclarationNameInfo &NameInfo,
4130 const TemplateArgumentListInfo *TemplateArgs) {
4132 assert(TemplateArgs || TemplateKWLoc.isValid());
4134 if (!(DC = computeDeclContext(SS, false)) ||
4135 DC->isDependentContext() ||
4136 RequireCompleteDeclContext(SS, DC))
4137 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
4139 bool MemberOfUnknownSpecialization;
4140 LookupResult R(*this, NameInfo, LookupOrdinaryName);
4141 if (LookupTemplateName(R, (Scope *)nullptr, SS, QualType(),
4142 /*Entering*/false, MemberOfUnknownSpecialization,
4146 if (R.isAmbiguous())
4150 Diag(NameInfo.getLoc(), diag::err_no_member)
4151 << NameInfo.getName() << DC << SS.getRange();
4155 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
4156 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
4158 << NameInfo.getName().getAsString() << SS.getRange();
4159 Diag(Temp->getLocation(), diag::note_referenced_class_template);
4163 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
4166 /// Form a dependent template name.
4168 /// This action forms a dependent template name given the template
4169 /// name and its (presumably dependent) scope specifier. For
4170 /// example, given "MetaFun::template apply", the scope specifier \p
4171 /// SS will be "MetaFun::", \p TemplateKWLoc contains the location
4172 /// of the "template" keyword, and "apply" is the \p Name.
4173 TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
4175 SourceLocation TemplateKWLoc,
4176 const UnqualifiedId &Name,
4177 ParsedType ObjectType,
4178 bool EnteringContext,
4180 bool AllowInjectedClassName) {
4181 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
4183 getLangOpts().CPlusPlus11 ?
4184 diag::warn_cxx98_compat_template_outside_of_template :
4185 diag::ext_template_outside_of_template)
4186 << FixItHint::CreateRemoval(TemplateKWLoc);
4188 DeclContext *LookupCtx = nullptr;
4190 LookupCtx = computeDeclContext(SS, EnteringContext);
4191 if (!LookupCtx && ObjectType)
4192 LookupCtx = computeDeclContext(ObjectType.get());
4194 // C++0x [temp.names]p5:
4195 // If a name prefixed by the keyword template is not the name of
4196 // a template, the program is ill-formed. [Note: the keyword
4197 // template may not be applied to non-template members of class
4198 // templates. -end note ] [ Note: as is the case with the
4199 // typename prefix, the template prefix is allowed in cases
4200 // where it is not strictly necessary; i.e., when the
4201 // nested-name-specifier or the expression on the left of the ->
4202 // or . is not dependent on a template-parameter, or the use
4203 // does not appear in the scope of a template. -end note]
4205 // Note: C++03 was more strict here, because it banned the use of
4206 // the "template" keyword prior to a template-name that was not a
4207 // dependent name. C++ DR468 relaxed this requirement (the
4208 // "template" keyword is now permitted). We follow the C++0x
4209 // rules, even in C++03 mode with a warning, retroactively applying the DR.
4210 bool MemberOfUnknownSpecialization;
4211 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
4212 ObjectType, EnteringContext, Result,
4213 MemberOfUnknownSpecialization);
4214 if (TNK == TNK_Non_template && MemberOfUnknownSpecialization) {
4215 // This is a dependent template. Handle it below.
4216 } else if (TNK == TNK_Non_template) {
4217 // Do the lookup again to determine if this is a "nothing found" case or
4218 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
4220 DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
4221 LookupResult R(*this, DNI.getName(), Name.getLocStart(),
4222 LookupOrdinaryName);
4224 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext,
4225 MOUS, TemplateKWLoc))
4226 Diag(Name.getLocStart(), diag::err_no_member)
4227 << DNI.getName() << LookupCtx << SS.getRange();
4228 return TNK_Non_template;
4230 // We found something; return it.
4231 auto *LookupRD = dyn_cast<CXXRecordDecl>(LookupCtx);
4232 if (!AllowInjectedClassName && SS.isSet() && LookupRD &&
4233 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
4234 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
4235 // C++14 [class.qual]p2:
4236 // In a lookup in which function names are not ignored and the
4237 // nested-name-specifier nominates a class C, if the name specified
4238 // [...] is the injected-class-name of C, [...] the name is instead
4239 // considered to name the constructor
4241 // We don't get here if naming the constructor would be valid, so we
4242 // just reject immediately and recover by treating the
4243 // injected-class-name as naming the template.
4244 Diag(Name.getLocStart(),
4245 diag::ext_out_of_line_qualified_id_type_names_constructor)
4246 << Name.Identifier << 0 /*injected-class-name used as template name*/
4247 << 1 /*'template' keyword was used*/;
4253 NestedNameSpecifier *Qualifier = SS.getScopeRep();
4255 switch (Name.getKind()) {
4256 case UnqualifiedIdKind::IK_Identifier:
4257 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
4259 return TNK_Dependent_template_name;
4261 case UnqualifiedIdKind::IK_OperatorFunctionId:
4262 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
4263 Name.OperatorFunctionId.Operator));
4264 return TNK_Function_template;
4266 case UnqualifiedIdKind::IK_LiteralOperatorId:
4267 llvm_unreachable("literal operator id cannot have a dependent scope");
4273 Diag(Name.getLocStart(),
4274 diag::err_template_kw_refers_to_non_template)
4275 << GetNameFromUnqualifiedId(Name).getName()
4276 << Name.getSourceRange()
4278 return TNK_Non_template;
4281 bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
4282 TemplateArgumentLoc &AL,
4283 SmallVectorImpl<TemplateArgument> &Converted) {
4284 const TemplateArgument &Arg = AL.getArgument();
4286 TypeSourceInfo *TSI = nullptr;
4288 // Check template type parameter.
4289 switch(Arg.getKind()) {
4290 case TemplateArgument::Type:
4291 // C++ [temp.arg.type]p1:
4292 // A template-argument for a template-parameter which is a
4293 // type shall be a type-id.
4294 ArgType = Arg.getAsType();
4295 TSI = AL.getTypeSourceInfo();
4297 case TemplateArgument::Template:
4298 case TemplateArgument::TemplateExpansion: {
4299 // We have a template type parameter but the template argument
4300 // is a template without any arguments.
4301 SourceRange SR = AL.getSourceRange();
4302 TemplateName Name = Arg.getAsTemplateOrTemplatePattern();
4303 diagnoseMissingTemplateArguments(Name, SR.getEnd());
4306 case TemplateArgument::Expression: {
4307 // We have a template type parameter but the template argument is an
4308 // expression; see if maybe it is missing the "typename" keyword.
4310 DeclarationNameInfo NameInfo;
4312 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
4313 SS.Adopt(ArgExpr->getQualifierLoc());
4314 NameInfo = ArgExpr->getNameInfo();
4315 } else if (DependentScopeDeclRefExpr *ArgExpr =
4316 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
4317 SS.Adopt(ArgExpr->getQualifierLoc());
4318 NameInfo = ArgExpr->getNameInfo();
4319 } else if (CXXDependentScopeMemberExpr *ArgExpr =
4320 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
4321 if (ArgExpr->isImplicitAccess()) {
4322 SS.Adopt(ArgExpr->getQualifierLoc());
4323 NameInfo = ArgExpr->getMemberNameInfo();
4327 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
4328 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
4329 LookupParsedName(Result, CurScope, &SS);
4331 if (Result.getAsSingle<TypeDecl>() ||
4332 Result.getResultKind() ==
4333 LookupResult::NotFoundInCurrentInstantiation) {
4334 // Suggest that the user add 'typename' before the NNS.
4335 SourceLocation Loc = AL.getSourceRange().getBegin();
4336 Diag(Loc, getLangOpts().MSVCCompat
4337 ? diag::ext_ms_template_type_arg_missing_typename
4338 : diag::err_template_arg_must_be_type_suggest)
4339 << FixItHint::CreateInsertion(Loc, "typename ");
4340 Diag(Param->getLocation(), diag::note_template_param_here);
4342 // Recover by synthesizing a type using the location information that we
4345 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
4347 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
4348 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
4349 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4350 TL.setNameLoc(NameInfo.getLoc());
4351 TSI = TLB.getTypeSourceInfo(Context, ArgType);
4353 // Overwrite our input TemplateArgumentLoc so that we can recover
4355 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
4356 TemplateArgumentLocInfo(TSI));
4365 // We have a template type parameter but the template argument
4367 SourceRange SR = AL.getSourceRange();
4368 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
4369 Diag(Param->getLocation(), diag::note_template_param_here);
4375 if (CheckTemplateArgument(Param, TSI))
4378 // Add the converted template type argument.
4379 ArgType = Context.getCanonicalType(ArgType);
4382 // If an explicitly-specified template argument type is a lifetime type
4383 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
4384 if (getLangOpts().ObjCAutoRefCount &&
4385 ArgType->isObjCLifetimeType() &&
4386 !ArgType.getObjCLifetime()) {
4388 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
4389 ArgType = Context.getQualifiedType(ArgType, Qs);
4392 Converted.push_back(TemplateArgument(ArgType));
4396 /// Substitute template arguments into the default template argument for
4397 /// the given template type parameter.
4399 /// \param SemaRef the semantic analysis object for which we are performing
4400 /// the substitution.
4402 /// \param Template the template that we are synthesizing template arguments
4405 /// \param TemplateLoc the location of the template name that started the
4406 /// template-id we are checking.
4408 /// \param RAngleLoc the location of the right angle bracket ('>') that
4409 /// terminates the template-id.
4411 /// \param Param the template template parameter whose default we are
4412 /// substituting into.
4414 /// \param Converted the list of template arguments provided for template
4415 /// parameters that precede \p Param in the template parameter list.
4416 /// \returns the substituted template argument, or NULL if an error occurred.
4417 static TypeSourceInfo *
4418 SubstDefaultTemplateArgument(Sema &SemaRef,
4419 TemplateDecl *Template,
4420 SourceLocation TemplateLoc,
4421 SourceLocation RAngleLoc,
4422 TemplateTypeParmDecl *Param,
4423 SmallVectorImpl<TemplateArgument> &Converted) {
4424 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
4426 // If the argument type is dependent, instantiate it now based
4427 // on the previously-computed template arguments.
4428 if (ArgType->getType()->isDependentType()) {
4429 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
4430 Param, Template, Converted,
4431 SourceRange(TemplateLoc, RAngleLoc));
4432 if (Inst.isInvalid())
4435 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4437 // Only substitute for the innermost template argument list.
4438 MultiLevelTemplateArgumentList TemplateArgLists;
4439 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4440 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4441 TemplateArgLists.addOuterTemplateArguments(None);
4443 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4445 SemaRef.SubstType(ArgType, TemplateArgLists,
4446 Param->getDefaultArgumentLoc(), Param->getDeclName());
4452 /// Substitute template arguments into the default template argument for
4453 /// the given non-type template parameter.
4455 /// \param SemaRef the semantic analysis object for which we are performing
4456 /// the substitution.
4458 /// \param Template the template that we are synthesizing template arguments
4461 /// \param TemplateLoc the location of the template name that started the
4462 /// template-id we are checking.
4464 /// \param RAngleLoc the location of the right angle bracket ('>') that
4465 /// terminates the template-id.
4467 /// \param Param the non-type template parameter whose default we are
4468 /// substituting into.
4470 /// \param Converted the list of template arguments provided for template
4471 /// parameters that precede \p Param in the template parameter list.
4473 /// \returns the substituted template argument, or NULL if an error occurred.
4475 SubstDefaultTemplateArgument(Sema &SemaRef,
4476 TemplateDecl *Template,
4477 SourceLocation TemplateLoc,
4478 SourceLocation RAngleLoc,
4479 NonTypeTemplateParmDecl *Param,
4480 SmallVectorImpl<TemplateArgument> &Converted) {
4481 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
4482 Param, Template, Converted,
4483 SourceRange(TemplateLoc, RAngleLoc));
4484 if (Inst.isInvalid())
4487 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4489 // Only substitute for the innermost template argument list.
4490 MultiLevelTemplateArgumentList TemplateArgLists;
4491 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4492 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4493 TemplateArgLists.addOuterTemplateArguments(None);
4495 EnterExpressionEvaluationContext ConstantEvaluated(
4496 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4497 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
4500 /// Substitute template arguments into the default template argument for
4501 /// the given template template parameter.
4503 /// \param SemaRef the semantic analysis object for which we are performing
4504 /// the substitution.
4506 /// \param Template the template that we are synthesizing template arguments
4509 /// \param TemplateLoc the location of the template name that started the
4510 /// template-id we are checking.
4512 /// \param RAngleLoc the location of the right angle bracket ('>') that
4513 /// terminates the template-id.
4515 /// \param Param the template template parameter whose default we are
4516 /// substituting into.
4518 /// \param Converted the list of template arguments provided for template
4519 /// parameters that precede \p Param in the template parameter list.
4521 /// \param QualifierLoc Will be set to the nested-name-specifier (with
4522 /// source-location information) that precedes the template name.
4524 /// \returns the substituted template argument, or NULL if an error occurred.
4526 SubstDefaultTemplateArgument(Sema &SemaRef,
4527 TemplateDecl *Template,
4528 SourceLocation TemplateLoc,
4529 SourceLocation RAngleLoc,
4530 TemplateTemplateParmDecl *Param,
4531 SmallVectorImpl<TemplateArgument> &Converted,
4532 NestedNameSpecifierLoc &QualifierLoc) {
4533 Sema::InstantiatingTemplate Inst(
4534 SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
4535 SourceRange(TemplateLoc, RAngleLoc));
4536 if (Inst.isInvalid())
4537 return TemplateName();
4539 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4541 // Only substitute for the innermost template argument list.
4542 MultiLevelTemplateArgumentList TemplateArgLists;
4543 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4544 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4545 TemplateArgLists.addOuterTemplateArguments(None);
4547 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4548 // Substitute into the nested-name-specifier first,
4549 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
4552 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
4554 return TemplateName();
4557 return SemaRef.SubstTemplateName(
4559 Param->getDefaultArgument().getArgument().getAsTemplate(),
4560 Param->getDefaultArgument().getTemplateNameLoc(),
4564 /// If the given template parameter has a default template
4565 /// argument, substitute into that default template argument and
4566 /// return the corresponding template argument.
4568 Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
4569 SourceLocation TemplateLoc,
4570 SourceLocation RAngleLoc,
4572 SmallVectorImpl<TemplateArgument>
4574 bool &HasDefaultArg) {
4575 HasDefaultArg = false;
4577 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
4578 if (!hasVisibleDefaultArgument(TypeParm))
4579 return TemplateArgumentLoc();
4581 HasDefaultArg = true;
4582 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
4588 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4590 return TemplateArgumentLoc();
4593 if (NonTypeTemplateParmDecl *NonTypeParm
4594 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4595 if (!hasVisibleDefaultArgument(NonTypeParm))
4596 return TemplateArgumentLoc();
4598 HasDefaultArg = true;
4599 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
4604 if (Arg.isInvalid())
4605 return TemplateArgumentLoc();
4607 Expr *ArgE = Arg.getAs<Expr>();
4608 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
4611 TemplateTemplateParmDecl *TempTempParm
4612 = cast<TemplateTemplateParmDecl>(Param);
4613 if (!hasVisibleDefaultArgument(TempTempParm))
4614 return TemplateArgumentLoc();
4616 HasDefaultArg = true;
4617 NestedNameSpecifierLoc QualifierLoc;
4618 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
4625 return TemplateArgumentLoc();
4627 return TemplateArgumentLoc(TemplateArgument(TName),
4628 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
4629 TempTempParm->getDefaultArgument().getTemplateNameLoc());
4632 /// Convert a template-argument that we parsed as a type into a template, if
4633 /// possible. C++ permits injected-class-names to perform dual service as
4634 /// template template arguments and as template type arguments.
4635 static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(TypeLoc TLoc) {
4636 // Extract and step over any surrounding nested-name-specifier.
4637 NestedNameSpecifierLoc QualLoc;
4638 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
4639 if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
4640 return TemplateArgumentLoc();
4642 QualLoc = ETLoc.getQualifierLoc();
4643 TLoc = ETLoc.getNamedTypeLoc();
4646 // If this type was written as an injected-class-name, it can be used as a
4647 // template template argument.
4648 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
4649 return TemplateArgumentLoc(InjLoc.getTypePtr()->getTemplateName(),
4650 QualLoc, InjLoc.getNameLoc());
4652 // If this type was written as an injected-class-name, it may have been
4653 // converted to a RecordType during instantiation. If the RecordType is
4654 // *not* wrapped in a TemplateSpecializationType and denotes a class
4655 // template specialization, it must have come from an injected-class-name.
4656 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
4658 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
4659 return TemplateArgumentLoc(TemplateName(CTSD->getSpecializedTemplate()),
4660 QualLoc, RecLoc.getNameLoc());
4662 return TemplateArgumentLoc();
4665 /// Check that the given template argument corresponds to the given
4666 /// template parameter.
4668 /// \param Param The template parameter against which the argument will be
4671 /// \param Arg The template argument, which may be updated due to conversions.
4673 /// \param Template The template in which the template argument resides.
4675 /// \param TemplateLoc The location of the template name for the template
4676 /// whose argument list we're matching.
4678 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
4679 /// the template argument list.
4681 /// \param ArgumentPackIndex The index into the argument pack where this
4682 /// argument will be placed. Only valid if the parameter is a parameter pack.
4684 /// \param Converted The checked, converted argument will be added to the
4685 /// end of this small vector.
4687 /// \param CTAK Describes how we arrived at this particular template argument:
4688 /// explicitly written, deduced, etc.
4690 /// \returns true on error, false otherwise.
4691 bool Sema::CheckTemplateArgument(NamedDecl *Param,
4692 TemplateArgumentLoc &Arg,
4693 NamedDecl *Template,
4694 SourceLocation TemplateLoc,
4695 SourceLocation RAngleLoc,
4696 unsigned ArgumentPackIndex,
4697 SmallVectorImpl<TemplateArgument> &Converted,
4698 CheckTemplateArgumentKind CTAK) {
4699 // Check template type parameters.
4700 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4701 return CheckTemplateTypeArgument(TTP, Arg, Converted);
4703 // Check non-type template parameters.
4704 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4705 // Do substitution on the type of the non-type template parameter
4706 // with the template arguments we've seen thus far. But if the
4707 // template has a dependent context then we cannot substitute yet.
4708 QualType NTTPType = NTTP->getType();
4709 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
4710 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
4712 // FIXME: Do we need to substitute into parameters here if they're
4713 // instantiation-dependent but not dependent?
4714 if (NTTPType->isDependentType() &&
4715 !isa<TemplateTemplateParmDecl>(Template) &&
4716 !Template->getDeclContext()->isDependentContext()) {
4717 // Do substitution on the type of the non-type template parameter.
4718 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
4720 SourceRange(TemplateLoc, RAngleLoc));
4721 if (Inst.isInvalid())
4724 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
4726 NTTPType = SubstType(NTTPType,
4727 MultiLevelTemplateArgumentList(TemplateArgs),
4728 NTTP->getLocation(),
4729 NTTP->getDeclName());
4730 // If that worked, check the non-type template parameter type
4732 if (!NTTPType.isNull())
4733 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
4734 NTTP->getLocation());
4735 if (NTTPType.isNull())
4739 switch (Arg.getArgument().getKind()) {
4740 case TemplateArgument::Null:
4741 llvm_unreachable("Should never see a NULL template argument here");
4743 case TemplateArgument::Expression: {
4744 TemplateArgument Result;
4745 unsigned CurSFINAEErrors = NumSFINAEErrors;
4747 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
4749 if (Res.isInvalid())
4751 // If the current template argument causes an error, give up now.
4752 if (CurSFINAEErrors < NumSFINAEErrors)
4755 // If the resulting expression is new, then use it in place of the
4756 // old expression in the template argument.
4757 if (Res.get() != Arg.getArgument().getAsExpr()) {
4758 TemplateArgument TA(Res.get());
4759 Arg = TemplateArgumentLoc(TA, Res.get());
4762 Converted.push_back(Result);
4766 case TemplateArgument::Declaration:
4767 case TemplateArgument::Integral:
4768 case TemplateArgument::NullPtr:
4769 // We've already checked this template argument, so just copy
4770 // it to the list of converted arguments.
4771 Converted.push_back(Arg.getArgument());
4774 case TemplateArgument::Template:
4775 case TemplateArgument::TemplateExpansion:
4776 // We were given a template template argument. It may not be ill-formed;
4778 if (DependentTemplateName *DTN
4779 = Arg.getArgument().getAsTemplateOrTemplatePattern()
4780 .getAsDependentTemplateName()) {
4781 // We have a template argument such as \c T::template X, which we
4782 // parsed as a template template argument. However, since we now
4783 // know that we need a non-type template argument, convert this
4784 // template name into an expression.
4786 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
4787 Arg.getTemplateNameLoc());
4790 SS.Adopt(Arg.getTemplateQualifierLoc());
4791 // FIXME: the template-template arg was a DependentTemplateName,
4792 // so it was provided with a template keyword. However, its source
4793 // location is not stored in the template argument structure.
4794 SourceLocation TemplateKWLoc;
4795 ExprResult E = DependentScopeDeclRefExpr::Create(
4796 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
4799 // If we parsed the template argument as a pack expansion, create a
4800 // pack expansion expression.
4801 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
4802 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
4807 TemplateArgument Result;
4808 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
4812 Converted.push_back(Result);
4816 // We have a template argument that actually does refer to a class
4817 // template, alias template, or template template parameter, and
4818 // therefore cannot be a non-type template argument.
4819 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
4820 << Arg.getSourceRange();
4822 Diag(Param->getLocation(), diag::note_template_param_here);
4825 case TemplateArgument::Type: {
4826 // We have a non-type template parameter but the template
4827 // argument is a type.
4829 // C++ [temp.arg]p2:
4830 // In a template-argument, an ambiguity between a type-id and
4831 // an expression is resolved to a type-id, regardless of the
4832 // form of the corresponding template-parameter.
4834 // We warn specifically about this case, since it can be rather
4835 // confusing for users.
4836 QualType T = Arg.getArgument().getAsType();
4837 SourceRange SR = Arg.getSourceRange();
4838 if (T->isFunctionType())
4839 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
4841 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
4842 Diag(Param->getLocation(), diag::note_template_param_here);
4846 case TemplateArgument::Pack:
4847 llvm_unreachable("Caller must expand template argument packs");
4854 // Check template template parameters.
4855 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
4857 TemplateParameterList *Params = TempParm->getTemplateParameters();
4858 if (TempParm->isExpandedParameterPack())
4859 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
4861 // Substitute into the template parameter list of the template
4862 // template parameter, since previously-supplied template arguments
4863 // may appear within the template template parameter.
4865 // FIXME: Skip this if the parameters aren't instantiation-dependent.
4867 // Set up a template instantiation context.
4868 LocalInstantiationScope Scope(*this);
4869 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
4870 TempParm, Converted,
4871 SourceRange(TemplateLoc, RAngleLoc));
4872 if (Inst.isInvalid())
4875 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4876 Params = SubstTemplateParams(Params, CurContext,
4877 MultiLevelTemplateArgumentList(TemplateArgs));
4882 // C++1z [temp.local]p1: (DR1004)
4883 // When [the injected-class-name] is used [...] as a template-argument for
4884 // a template template-parameter [...] it refers to the class template
4886 if (Arg.getArgument().getKind() == TemplateArgument::Type) {
4887 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
4888 Arg.getTypeSourceInfo()->getTypeLoc());
4889 if (!ConvertedArg.getArgument().isNull())
4893 switch (Arg.getArgument().getKind()) {
4894 case TemplateArgument::Null:
4895 llvm_unreachable("Should never see a NULL template argument here");
4897 case TemplateArgument::Template:
4898 case TemplateArgument::TemplateExpansion:
4899 if (CheckTemplateTemplateArgument(Params, Arg))
4902 Converted.push_back(Arg.getArgument());
4905 case TemplateArgument::Expression:
4906 case TemplateArgument::Type:
4907 // We have a template template parameter but the template
4908 // argument does not refer to a template.
4909 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
4910 << getLangOpts().CPlusPlus11;
4913 case TemplateArgument::Declaration:
4914 llvm_unreachable("Declaration argument with template template parameter");
4915 case TemplateArgument::Integral:
4916 llvm_unreachable("Integral argument with template template parameter");
4917 case TemplateArgument::NullPtr:
4918 llvm_unreachable("Null pointer argument with template template parameter");
4920 case TemplateArgument::Pack:
4921 llvm_unreachable("Caller must expand template argument packs");
4927 /// Check whether the template parameter is a pack expansion, and if so,
4928 /// determine the number of parameters produced by that expansion. For instance:
4931 /// template<typename ...Ts> struct A {
4932 /// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
4936 /// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
4937 /// is not a pack expansion, so returns an empty Optional.
4938 static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
4939 if (NonTypeTemplateParmDecl *NTTP
4940 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4941 if (NTTP->isExpandedParameterPack())
4942 return NTTP->getNumExpansionTypes();
4945 if (TemplateTemplateParmDecl *TTP
4946 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
4947 if (TTP->isExpandedParameterPack())
4948 return TTP->getNumExpansionTemplateParameters();
4954 /// Diagnose a missing template argument.
4955 template<typename TemplateParmDecl>
4956 static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
4958 const TemplateParmDecl *D,
4959 TemplateArgumentListInfo &Args) {
4960 // Dig out the most recent declaration of the template parameter; there may be
4961 // declarations of the template that are more recent than TD.
4962 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
4963 ->getTemplateParameters()
4964 ->getParam(D->getIndex()));
4966 // If there's a default argument that's not visible, diagnose that we're
4967 // missing a module import.
4968 llvm::SmallVector<Module*, 8> Modules;
4969 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
4970 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
4971 D->getDefaultArgumentLoc(), Modules,
4972 Sema::MissingImportKind::DefaultArgument,
4977 // FIXME: If there's a more recent default argument that *is* visible,
4978 // diagnose that it was declared too late.
4980 TemplateParameterList *Params = TD->getTemplateParameters();
4982 S.Diag(Loc, diag::err_template_arg_list_different_arity)
4983 << /*not enough args*/0
4984 << (int)S.getTemplateNameKindForDiagnostics(TemplateName(TD))
4986 S.Diag(TD->getLocation(), diag::note_template_decl_here)
4987 << Params->getSourceRange();
4991 /// Check that the given template argument list is well-formed
4992 /// for specializing the given template.
4993 bool Sema::CheckTemplateArgumentList(
4994 TemplateDecl *Template, SourceLocation TemplateLoc,
4995 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
4996 SmallVectorImpl<TemplateArgument> &Converted,
4997 bool UpdateArgsWithConversions) {
4998 // Make a copy of the template arguments for processing. Only make the
4999 // changes at the end when successful in matching the arguments to the
5001 TemplateArgumentListInfo NewArgs = TemplateArgs;
5003 // Make sure we get the template parameter list from the most
5004 // recentdeclaration, since that is the only one that has is guaranteed to
5005 // have all the default template argument information.
5006 TemplateParameterList *Params =
5007 cast<TemplateDecl>(Template->getMostRecentDecl())
5008 ->getTemplateParameters();
5010 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5012 // C++ [temp.arg]p1:
5013 // [...] The type and form of each template-argument specified in
5014 // a template-id shall match the type and form specified for the
5015 // corresponding parameter declared by the template in its
5016 // template-parameter-list.
5017 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
5018 SmallVector<TemplateArgument, 2> ArgumentPack;
5019 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5020 LocalInstantiationScope InstScope(*this, true);
5021 for (TemplateParameterList::iterator Param = Params->begin(),
5022 ParamEnd = Params->end();
5023 Param != ParamEnd; /* increment in loop */) {
5024 // If we have an expanded parameter pack, make sure we don't have too
5026 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
5027 if (*Expansions == ArgumentPack.size()) {
5028 // We're done with this parameter pack. Pack up its arguments and add
5029 // them to the list.
5030 Converted.push_back(
5031 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
5032 ArgumentPack.clear();
5034 // This argument is assigned to the next parameter.
5037 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5038 // Not enough arguments for this parameter pack.
5039 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5040 << /*not enough args*/0
5041 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
5043 Diag(Template->getLocation(), diag::note_template_decl_here)
5044 << Params->getSourceRange();
5049 if (ArgIdx < NumArgs) {
5050 // Check the template argument we were given.
5051 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
5052 TemplateLoc, RAngleLoc,
5053 ArgumentPack.size(), Converted))
5056 bool PackExpansionIntoNonPack =
5057 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
5058 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
5059 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
5060 // Core issue 1430: we have a pack expansion as an argument to an
5061 // alias template, and it's not part of a parameter pack. This
5062 // can't be canonicalized, so reject it now.
5063 Diag(NewArgs[ArgIdx].getLocation(),
5064 diag::err_alias_template_expansion_into_fixed_list)
5065 << NewArgs[ArgIdx].getSourceRange();
5066 Diag((*Param)->getLocation(), diag::note_template_param_here);
5070 // We're now done with this argument.
5073 if ((*Param)->isTemplateParameterPack()) {
5074 // The template parameter was a template parameter pack, so take the
5075 // deduced argument and place it on the argument pack. Note that we
5076 // stay on the same template parameter so that we can deduce more
5078 ArgumentPack.push_back(Converted.pop_back_val());
5080 // Move to the next template parameter.
5084 // If we just saw a pack expansion into a non-pack, then directly convert
5085 // the remaining arguments, because we don't know what parameters they'll
5087 if (PackExpansionIntoNonPack) {
5088 if (!ArgumentPack.empty()) {
5089 // If we were part way through filling in an expanded parameter pack,
5090 // fall back to just producing individual arguments.
5091 Converted.insert(Converted.end(),
5092 ArgumentPack.begin(), ArgumentPack.end());
5093 ArgumentPack.clear();
5096 while (ArgIdx < NumArgs) {
5097 Converted.push_back(NewArgs[ArgIdx].getArgument());
5107 // If we're checking a partial template argument list, we're done.
5108 if (PartialTemplateArgs) {
5109 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
5110 Converted.push_back(
5111 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
5116 // If we have a template parameter pack with no more corresponding
5117 // arguments, just break out now and we'll fill in the argument pack below.
5118 if ((*Param)->isTemplateParameterPack()) {
5119 assert(!getExpandedPackSize(*Param) &&
5120 "Should have dealt with this already");
5122 // A non-expanded parameter pack before the end of the parameter list
5123 // only occurs for an ill-formed template parameter list, unless we've
5124 // got a partial argument list for a function template, so just bail out.
5125 if (Param + 1 != ParamEnd)
5128 Converted.push_back(
5129 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
5130 ArgumentPack.clear();
5136 // Check whether we have a default argument.
5137 TemplateArgumentLoc Arg;
5139 // Retrieve the default template argument from the template
5140 // parameter. For each kind of template parameter, we substitute the
5141 // template arguments provided thus far and any "outer" template arguments
5142 // (when the template parameter was part of a nested template) into
5143 // the default argument.
5144 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
5145 if (!hasVisibleDefaultArgument(TTP))
5146 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
5149 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
5158 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
5160 } else if (NonTypeTemplateParmDecl *NTTP
5161 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
5162 if (!hasVisibleDefaultArgument(NTTP))
5163 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
5166 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
5174 Expr *Ex = E.getAs<Expr>();
5175 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
5177 TemplateTemplateParmDecl *TempParm
5178 = cast<TemplateTemplateParmDecl>(*Param);
5180 if (!hasVisibleDefaultArgument(TempParm))
5181 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
5184 NestedNameSpecifierLoc QualifierLoc;
5185 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
5194 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
5195 TempParm->getDefaultArgument().getTemplateNameLoc());
5198 // Introduce an instantiation record that describes where we are using
5199 // the default template argument. We're not actually instantiating a
5200 // template here, we just create this object to put a note into the
5202 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
5203 SourceRange(TemplateLoc, RAngleLoc));
5204 if (Inst.isInvalid())
5207 // Check the default template argument.
5208 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
5209 RAngleLoc, 0, Converted))
5212 // Core issue 150 (assumed resolution): if this is a template template
5213 // parameter, keep track of the default template arguments from the
5214 // template definition.
5215 if (isTemplateTemplateParameter)
5216 NewArgs.addArgument(Arg);
5218 // Move to the next template parameter and argument.
5223 // If we're performing a partial argument substitution, allow any trailing
5224 // pack expansions; they might be empty. This can happen even if
5225 // PartialTemplateArgs is false (the list of arguments is complete but
5226 // still dependent).
5227 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
5228 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
5229 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
5230 Converted.push_back(NewArgs[ArgIdx++].getArgument());
5233 // If we have any leftover arguments, then there were too many arguments.
5234 // Complain and fail.
5235 if (ArgIdx < NumArgs) {
5236 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5237 << /*too many args*/1
5238 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
5240 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
5241 Diag(Template->getLocation(), diag::note_template_decl_here)
5242 << Params->getSourceRange();
5246 // No problems found with the new argument list, propagate changes back
5248 if (UpdateArgsWithConversions)
5249 TemplateArgs = std::move(NewArgs);
5255 class UnnamedLocalNoLinkageFinder
5256 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
5261 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
5264 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
5266 bool Visit(QualType T) {
5267 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
5270 #define TYPE(Class, Parent) \
5271 bool Visit##Class##Type(const Class##Type *);
5272 #define ABSTRACT_TYPE(Class, Parent) \
5273 bool Visit##Class##Type(const Class##Type *) { return false; }
5274 #define NON_CANONICAL_TYPE(Class, Parent) \
5275 bool Visit##Class##Type(const Class##Type *) { return false; }
5276 #include "clang/AST/TypeNodes.def"
5278 bool VisitTagDecl(const TagDecl *Tag);
5279 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
5281 } // end anonymous namespace
5283 bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
5287 bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
5288 return Visit(T->getElementType());
5291 bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
5292 return Visit(T->getPointeeType());
5295 bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
5296 const BlockPointerType* T) {
5297 return Visit(T->getPointeeType());
5300 bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
5301 const LValueReferenceType* T) {
5302 return Visit(T->getPointeeType());
5305 bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
5306 const RValueReferenceType* T) {
5307 return Visit(T->getPointeeType());
5310 bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
5311 const MemberPointerType* T) {
5312 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
5315 bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
5316 const ConstantArrayType* T) {
5317 return Visit(T->getElementType());
5320 bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
5321 const IncompleteArrayType* T) {
5322 return Visit(T->getElementType());
5325 bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
5326 const VariableArrayType* T) {
5327 return Visit(T->getElementType());
5330 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
5331 const DependentSizedArrayType* T) {
5332 return Visit(T->getElementType());
5335 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
5336 const DependentSizedExtVectorType* T) {
5337 return Visit(T->getElementType());
5340 bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
5341 const DependentAddressSpaceType *T) {
5342 return Visit(T->getPointeeType());
5345 bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
5346 return Visit(T->getElementType());
5349 bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
5350 const DependentVectorType *T) {
5351 return Visit(T->getElementType());
5354 bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
5355 return Visit(T->getElementType());
5358 bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
5359 const FunctionProtoType* T) {
5360 for (const auto &A : T->param_types()) {
5365 return Visit(T->getReturnType());
5368 bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
5369 const FunctionNoProtoType* T) {
5370 return Visit(T->getReturnType());
5373 bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
5374 const UnresolvedUsingType*) {
5378 bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
5382 bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
5383 return Visit(T->getUnderlyingType());
5386 bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
5390 bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
5391 const UnaryTransformType*) {
5395 bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
5396 return Visit(T->getDeducedType());
5399 bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
5400 const DeducedTemplateSpecializationType *T) {
5401 return Visit(T->getDeducedType());
5404 bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
5405 return VisitTagDecl(T->getDecl());
5408 bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
5409 return VisitTagDecl(T->getDecl());
5412 bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
5413 const TemplateTypeParmType*) {
5417 bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
5418 const SubstTemplateTypeParmPackType *) {
5422 bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
5423 const TemplateSpecializationType*) {
5427 bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
5428 const InjectedClassNameType* T) {
5429 return VisitTagDecl(T->getDecl());
5432 bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
5433 const DependentNameType* T) {
5434 return VisitNestedNameSpecifier(T->getQualifier());
5437 bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
5438 const DependentTemplateSpecializationType* T) {
5439 return VisitNestedNameSpecifier(T->getQualifier());
5442 bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
5443 const PackExpansionType* T) {
5444 return Visit(T->getPattern());
5447 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
5451 bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
5452 const ObjCInterfaceType *) {
5456 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
5457 const ObjCObjectPointerType *) {
5461 bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
5462 return Visit(T->getValueType());
5465 bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
5469 bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
5470 if (Tag->getDeclContext()->isFunctionOrMethod()) {
5471 S.Diag(SR.getBegin(),
5472 S.getLangOpts().CPlusPlus11 ?
5473 diag::warn_cxx98_compat_template_arg_local_type :
5474 diag::ext_template_arg_local_type)
5475 << S.Context.getTypeDeclType(Tag) << SR;
5479 if (!Tag->hasNameForLinkage()) {
5480 S.Diag(SR.getBegin(),
5481 S.getLangOpts().CPlusPlus11 ?
5482 diag::warn_cxx98_compat_template_arg_unnamed_type :
5483 diag::ext_template_arg_unnamed_type) << SR;
5484 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
5491 bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
5492 NestedNameSpecifier *NNS) {
5493 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
5496 switch (NNS->getKind()) {
5497 case NestedNameSpecifier::Identifier:
5498 case NestedNameSpecifier::Namespace:
5499 case NestedNameSpecifier::NamespaceAlias:
5500 case NestedNameSpecifier::Global:
5501 case NestedNameSpecifier::Super:
5504 case NestedNameSpecifier::TypeSpec:
5505 case NestedNameSpecifier::TypeSpecWithTemplate:
5506 return Visit(QualType(NNS->getAsType(), 0));
5508 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
5511 /// Check a template argument against its corresponding
5512 /// template type parameter.
5514 /// This routine implements the semantics of C++ [temp.arg.type]. It
5515 /// returns true if an error occurred, and false otherwise.
5516 bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
5517 TypeSourceInfo *ArgInfo) {
5518 assert(ArgInfo && "invalid TypeSourceInfo");
5519 QualType Arg = ArgInfo->getType();
5520 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
5522 if (Arg->isVariablyModifiedType()) {
5523 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
5524 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
5525 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
5528 // C++03 [temp.arg.type]p2:
5529 // A local type, a type with no linkage, an unnamed type or a type
5530 // compounded from any of these types shall not be used as a
5531 // template-argument for a template type-parameter.
5533 // C++11 allows these, and even in C++03 we allow them as an extension with
5535 if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) {
5536 UnnamedLocalNoLinkageFinder Finder(*this, SR);
5537 (void)Finder.Visit(Context.getCanonicalType(Arg));
5543 enum NullPointerValueKind {
5549 /// Determine whether the given template argument is a null pointer
5550 /// value of the appropriate type.
5551 static NullPointerValueKind
5552 isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
5553 QualType ParamType, Expr *Arg,
5554 Decl *Entity = nullptr) {
5555 if (Arg->isValueDependent() || Arg->isTypeDependent())
5556 return NPV_NotNullPointer;
5558 // dllimport'd entities aren't constant but are available inside of template
5560 if (Entity && Entity->hasAttr<DLLImportAttr>())
5561 return NPV_NotNullPointer;
5563 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
5565 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
5567 if (!S.getLangOpts().CPlusPlus11)
5568 return NPV_NotNullPointer;
5570 // Determine whether we have a constant expression.
5571 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
5572 if (ArgRV.isInvalid())
5576 Expr::EvalResult EvalResult;
5577 SmallVector<PartialDiagnosticAt, 8> Notes;
5578 EvalResult.Diag = &Notes;
5579 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
5580 EvalResult.HasSideEffects) {
5581 SourceLocation DiagLoc = Arg->getExprLoc();
5583 // If our only note is the usual "invalid subexpression" note, just point
5584 // the caret at its location rather than producing an essentially
5586 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
5587 diag::note_invalid_subexpr_in_const_expr) {
5588 DiagLoc = Notes[0].first;
5592 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
5593 << Arg->getType() << Arg->getSourceRange();
5594 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
5595 S.Diag(Notes[I].first, Notes[I].second);
5597 S.Diag(Param->getLocation(), diag::note_template_param_here);
5601 // C++11 [temp.arg.nontype]p1:
5602 // - an address constant expression of type std::nullptr_t
5603 if (Arg->getType()->isNullPtrType())
5604 return NPV_NullPointer;
5606 // - a constant expression that evaluates to a null pointer value (4.10); or
5607 // - a constant expression that evaluates to a null member pointer value
5609 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
5610 (EvalResult.Val.isMemberPointer() &&
5611 !EvalResult.Val.getMemberPointerDecl())) {
5612 // If our expression has an appropriate type, we've succeeded.
5613 bool ObjCLifetimeConversion;
5614 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
5615 S.IsQualificationConversion(Arg->getType(), ParamType, false,
5616 ObjCLifetimeConversion))
5617 return NPV_NullPointer;
5619 // The types didn't match, but we know we got a null pointer; complain,
5620 // then recover as if the types were correct.
5621 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
5622 << Arg->getType() << ParamType << Arg->getSourceRange();
5623 S.Diag(Param->getLocation(), diag::note_template_param_here);
5624 return NPV_NullPointer;
5627 // If we don't have a null pointer value, but we do have a NULL pointer
5628 // constant, suggest a cast to the appropriate type.
5629 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
5630 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
5631 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
5632 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
5633 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
5635 S.Diag(Param->getLocation(), diag::note_template_param_here);
5636 return NPV_NullPointer;
5639 // FIXME: If we ever want to support general, address-constant expressions
5640 // as non-type template arguments, we should return the ExprResult here to
5641 // be interpreted by the caller.
5642 return NPV_NotNullPointer;
5645 /// Checks whether the given template argument is compatible with its
5646 /// template parameter.
5647 static bool CheckTemplateArgumentIsCompatibleWithParameter(
5648 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
5649 Expr *Arg, QualType ArgType) {
5650 bool ObjCLifetimeConversion;
5651 if (ParamType->isPointerType() &&
5652 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
5653 S.IsQualificationConversion(ArgType, ParamType, false,
5654 ObjCLifetimeConversion)) {
5655 // For pointer-to-object types, qualification conversions are
5658 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
5659 if (!ParamRef->getPointeeType()->isFunctionType()) {
5660 // C++ [temp.arg.nontype]p5b3:
5661 // For a non-type template-parameter of type reference to
5662 // object, no conversions apply. The type referred to by the
5663 // reference may be more cv-qualified than the (otherwise
5664 // identical) type of the template- argument. The
5665 // template-parameter is bound directly to the
5666 // template-argument, which shall be an lvalue.
5668 // FIXME: Other qualifiers?
5669 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
5670 unsigned ArgQuals = ArgType.getCVRQualifiers();
5672 if ((ParamQuals | ArgQuals) != ParamQuals) {
5673 S.Diag(Arg->getLocStart(),
5674 diag::err_template_arg_ref_bind_ignores_quals)
5675 << ParamType << Arg->getType() << Arg->getSourceRange();
5676 S.Diag(Param->getLocation(), diag::note_template_param_here);
5682 // At this point, the template argument refers to an object or
5683 // function with external linkage. We now need to check whether the
5684 // argument and parameter types are compatible.
5685 if (!S.Context.hasSameUnqualifiedType(ArgType,
5686 ParamType.getNonReferenceType())) {
5687 // We can't perform this conversion or binding.
5688 if (ParamType->isReferenceType())
5689 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
5690 << ParamType << ArgIn->getType() << Arg->getSourceRange();
5692 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
5693 << ArgIn->getType() << ParamType << Arg->getSourceRange();
5694 S.Diag(Param->getLocation(), diag::note_template_param_here);
5702 /// Checks whether the given template argument is the address
5703 /// of an object or function according to C++ [temp.arg.nontype]p1.
5705 CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
5706 NonTypeTemplateParmDecl *Param,
5709 TemplateArgument &Converted) {
5710 bool Invalid = false;
5712 QualType ArgType = Arg->getType();
5714 bool AddressTaken = false;
5715 SourceLocation AddrOpLoc;
5716 if (S.getLangOpts().MicrosoftExt) {
5717 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
5718 // dereference and address-of operators.
5719 Arg = Arg->IgnoreParenCasts();
5721 bool ExtWarnMSTemplateArg = false;
5722 UnaryOperatorKind FirstOpKind;
5723 SourceLocation FirstOpLoc;
5724 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5725 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
5726 if (UnOpKind == UO_Deref)
5727 ExtWarnMSTemplateArg = true;
5728 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
5729 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
5730 if (!AddrOpLoc.isValid()) {
5731 FirstOpKind = UnOpKind;
5732 FirstOpLoc = UnOp->getOperatorLoc();
5737 if (FirstOpLoc.isValid()) {
5738 if (ExtWarnMSTemplateArg)
5739 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
5740 << ArgIn->getSourceRange();
5742 if (FirstOpKind == UO_AddrOf)
5743 AddressTaken = true;
5744 else if (Arg->getType()->isPointerType()) {
5745 // We cannot let pointers get dereferenced here, that is obviously not a
5746 // constant expression.
5747 assert(FirstOpKind == UO_Deref);
5748 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5749 << Arg->getSourceRange();
5753 // See through any implicit casts we added to fix the type.
5754 Arg = Arg->IgnoreImpCasts();
5756 // C++ [temp.arg.nontype]p1:
5758 // A template-argument for a non-type, non-template
5759 // template-parameter shall be one of: [...]
5761 // -- the address of an object or function with external
5762 // linkage, including function templates and function
5763 // template-ids but excluding non-static class members,
5764 // expressed as & id-expression where the & is optional if
5765 // the name refers to a function or array, or if the
5766 // corresponding template-parameter is a reference; or
5768 // In C++98/03 mode, give an extension warning on any extra parentheses.
5769 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5770 bool ExtraParens = false;
5771 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
5772 if (!Invalid && !ExtraParens) {
5773 S.Diag(Arg->getLocStart(),
5774 S.getLangOpts().CPlusPlus11
5775 ? diag::warn_cxx98_compat_template_arg_extra_parens
5776 : diag::ext_template_arg_extra_parens)
5777 << Arg->getSourceRange();
5781 Arg = Parens->getSubExpr();
5784 while (SubstNonTypeTemplateParmExpr *subst =
5785 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5786 Arg = subst->getReplacement()->IgnoreImpCasts();
5788 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5789 if (UnOp->getOpcode() == UO_AddrOf) {
5790 Arg = UnOp->getSubExpr();
5791 AddressTaken = true;
5792 AddrOpLoc = UnOp->getOperatorLoc();
5796 while (SubstNonTypeTemplateParmExpr *subst =
5797 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5798 Arg = subst->getReplacement()->IgnoreImpCasts();
5801 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
5802 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
5804 // If our parameter has pointer type, check for a null template value.
5805 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
5806 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
5808 case NPV_NullPointer:
5809 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
5810 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5811 /*isNullPtr=*/true);
5817 case NPV_NotNullPointer:
5822 // Stop checking the precise nature of the argument if it is value dependent,
5823 // it should be checked when instantiated.
5824 if (Arg->isValueDependent()) {
5825 Converted = TemplateArgument(ArgIn);
5829 if (isa<CXXUuidofExpr>(Arg)) {
5830 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
5831 ArgIn, Arg, ArgType))
5834 Converted = TemplateArgument(ArgIn);
5839 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5840 << Arg->getSourceRange();
5841 S.Diag(Param->getLocation(), diag::note_template_param_here);
5845 // Cannot refer to non-static data members
5846 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
5847 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
5848 << Entity << Arg->getSourceRange();
5849 S.Diag(Param->getLocation(), diag::note_template_param_here);
5853 // Cannot refer to non-static member functions
5854 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
5855 if (!Method->isStatic()) {
5856 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
5857 << Method << Arg->getSourceRange();
5858 S.Diag(Param->getLocation(), diag::note_template_param_here);
5863 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
5864 VarDecl *Var = dyn_cast<VarDecl>(Entity);
5866 // A non-type template argument must refer to an object or function.
5867 if (!Func && !Var) {
5868 // We found something, but we don't know specifically what it is.
5869 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
5870 << Arg->getSourceRange();
5871 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
5875 // Address / reference template args must have external linkage in C++98.
5876 if (Entity->getFormalLinkage() == InternalLinkage) {
5877 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
5878 diag::warn_cxx98_compat_template_arg_object_internal :
5879 diag::ext_template_arg_object_internal)
5880 << !Func << Entity << Arg->getSourceRange();
5881 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5883 } else if (!Entity->hasLinkage()) {
5884 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
5885 << !Func << Entity << Arg->getSourceRange();
5886 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5892 // If the template parameter has pointer type, the function decays.
5893 if (ParamType->isPointerType() && !AddressTaken)
5894 ArgType = S.Context.getPointerType(Func->getType());
5895 else if (AddressTaken && ParamType->isReferenceType()) {
5896 // If we originally had an address-of operator, but the
5897 // parameter has reference type, complain and (if things look
5898 // like they will work) drop the address-of operator.
5899 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
5900 ParamType.getNonReferenceType())) {
5901 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5903 S.Diag(Param->getLocation(), diag::note_template_param_here);
5907 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5909 << FixItHint::CreateRemoval(AddrOpLoc);
5910 S.Diag(Param->getLocation(), diag::note_template_param_here);
5912 ArgType = Func->getType();
5915 // A value of reference type is not an object.
5916 if (Var->getType()->isReferenceType()) {
5917 S.Diag(Arg->getLocStart(),
5918 diag::err_template_arg_reference_var)
5919 << Var->getType() << Arg->getSourceRange();
5920 S.Diag(Param->getLocation(), diag::note_template_param_here);
5924 // A template argument must have static storage duration.
5925 if (Var->getTLSKind()) {
5926 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
5927 << Arg->getSourceRange();
5928 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
5932 // If the template parameter has pointer type, we must have taken
5933 // the address of this object.
5934 if (ParamType->isReferenceType()) {
5936 // If we originally had an address-of operator, but the
5937 // parameter has reference type, complain and (if things look
5938 // like they will work) drop the address-of operator.
5939 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
5940 ParamType.getNonReferenceType())) {
5941 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5943 S.Diag(Param->getLocation(), diag::note_template_param_here);
5947 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5949 << FixItHint::CreateRemoval(AddrOpLoc);
5950 S.Diag(Param->getLocation(), diag::note_template_param_here);
5952 ArgType = Var->getType();
5954 } else if (!AddressTaken && ParamType->isPointerType()) {
5955 if (Var->getType()->isArrayType()) {
5956 // Array-to-pointer decay.
5957 ArgType = S.Context.getArrayDecayedType(Var->getType());
5959 // If the template parameter has pointer type but the address of
5960 // this object was not taken, complain and (possibly) recover by
5961 // taking the address of the entity.
5962 ArgType = S.Context.getPointerType(Var->getType());
5963 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
5964 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
5966 S.Diag(Param->getLocation(), diag::note_template_param_here);
5970 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
5972 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
5974 S.Diag(Param->getLocation(), diag::note_template_param_here);
5979 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
5983 // Create the template argument.
5985 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
5986 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
5990 /// Checks whether the given template argument is a pointer to
5991 /// member constant according to C++ [temp.arg.nontype]p1.
5992 static bool CheckTemplateArgumentPointerToMember(Sema &S,
5993 NonTypeTemplateParmDecl *Param,
5996 TemplateArgument &Converted) {
5997 bool Invalid = false;
5999 Expr *Arg = ResultArg;
6000 bool ObjCLifetimeConversion;
6002 // C++ [temp.arg.nontype]p1:
6004 // A template-argument for a non-type, non-template
6005 // template-parameter shall be one of: [...]
6007 // -- a pointer to member expressed as described in 5.3.1.
6008 DeclRefExpr *DRE = nullptr;
6010 // In C++98/03 mode, give an extension warning on any extra parentheses.
6011 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6012 bool ExtraParens = false;
6013 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6014 if (!Invalid && !ExtraParens) {
6015 S.Diag(Arg->getLocStart(),
6016 S.getLangOpts().CPlusPlus11 ?
6017 diag::warn_cxx98_compat_template_arg_extra_parens :
6018 diag::ext_template_arg_extra_parens)
6019 << Arg->getSourceRange();
6023 Arg = Parens->getSubExpr();
6026 while (SubstNonTypeTemplateParmExpr *subst =
6027 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6028 Arg = subst->getReplacement()->IgnoreImpCasts();
6030 // A pointer-to-member constant written &Class::member.
6031 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6032 if (UnOp->getOpcode() == UO_AddrOf) {
6033 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
6034 if (DRE && !DRE->getQualifier())
6038 // A constant of pointer-to-member type.
6039 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
6040 ValueDecl *VD = DRE->getDecl();
6041 if (VD->getType()->isMemberPointerType()) {
6042 if (isa<NonTypeTemplateParmDecl>(VD)) {
6043 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6044 Converted = TemplateArgument(Arg);
6046 VD = cast<ValueDecl>(VD->getCanonicalDecl());
6047 Converted = TemplateArgument(VD, ParamType);
6056 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
6058 // Check for a null pointer value.
6059 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
6063 case NPV_NullPointer:
6064 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6065 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
6068 case NPV_NotNullPointer:
6072 if (S.IsQualificationConversion(ResultArg->getType(),
6073 ParamType.getNonReferenceType(), false,
6074 ObjCLifetimeConversion)) {
6075 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
6076 ResultArg->getValueKind())
6078 } else if (!S.Context.hasSameUnqualifiedType(
6079 ResultArg->getType(), ParamType.getNonReferenceType())) {
6080 // We can't perform this conversion.
6081 S.Diag(ResultArg->getLocStart(), diag::err_template_arg_not_convertible)
6082 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
6083 S.Diag(Param->getLocation(), diag::note_template_param_here);
6088 return S.Diag(Arg->getLocStart(),
6089 diag::err_template_arg_not_pointer_to_member_form)
6090 << Arg->getSourceRange();
6092 if (isa<FieldDecl>(DRE->getDecl()) ||
6093 isa<IndirectFieldDecl>(DRE->getDecl()) ||
6094 isa<CXXMethodDecl>(DRE->getDecl())) {
6095 assert((isa<FieldDecl>(DRE->getDecl()) ||
6096 isa<IndirectFieldDecl>(DRE->getDecl()) ||
6097 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
6098 "Only non-static member pointers can make it here");
6100 // Okay: this is the address of a non-static member, and therefore
6101 // a member pointer constant.
6102 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6103 Converted = TemplateArgument(Arg);
6105 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
6106 Converted = TemplateArgument(D, ParamType);
6111 // We found something else, but we don't know specifically what it is.
6112 S.Diag(Arg->getLocStart(),
6113 diag::err_template_arg_not_pointer_to_member_form)
6114 << Arg->getSourceRange();
6115 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
6119 /// Check a template argument against its corresponding
6120 /// non-type template parameter.
6122 /// This routine implements the semantics of C++ [temp.arg.nontype].
6123 /// If an error occurred, it returns ExprError(); otherwise, it
6124 /// returns the converted template argument. \p ParamType is the
6125 /// type of the non-type template parameter after it has been instantiated.
6126 ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
6127 QualType ParamType, Expr *Arg,
6128 TemplateArgument &Converted,
6129 CheckTemplateArgumentKind CTAK) {
6130 SourceLocation StartLoc = Arg->getLocStart();
6132 // If the parameter type somehow involves auto, deduce the type now.
6133 if (getLangOpts().CPlusPlus17 && ParamType->isUndeducedType()) {
6134 // During template argument deduction, we allow 'decltype(auto)' to
6135 // match an arbitrary dependent argument.
6136 // FIXME: The language rules don't say what happens in this case.
6137 // FIXME: We get an opaque dependent type out of decltype(auto) if the
6138 // expression is merely instantiation-dependent; is this enough?
6139 if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) {
6140 auto *AT = dyn_cast<AutoType>(ParamType);
6141 if (AT && AT->isDecltypeAuto()) {
6142 Converted = TemplateArgument(Arg);
6147 // When checking a deduced template argument, deduce from its type even if
6148 // the type is dependent, in order to check the types of non-type template
6149 // arguments line up properly in partial ordering.
6150 Optional<unsigned> Depth;
6151 if (CTAK != CTAK_Specified)
6152 Depth = Param->getDepth() + 1;
6154 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()),
6155 Arg, ParamType, Depth) == DAR_Failed) {
6156 Diag(Arg->getExprLoc(),
6157 diag::err_non_type_template_parm_type_deduction_failure)
6158 << Param->getDeclName() << Param->getType() << Arg->getType()
6159 << Arg->getSourceRange();
6160 Diag(Param->getLocation(), diag::note_template_param_here);
6163 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
6164 // an error. The error message normally references the parameter
6165 // declaration, but here we'll pass the argument location because that's
6166 // where the parameter type is deduced.
6167 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
6168 if (ParamType.isNull()) {
6169 Diag(Param->getLocation(), diag::note_template_param_here);
6174 // We should have already dropped all cv-qualifiers by now.
6175 assert(!ParamType.hasQualifiers() &&
6176 "non-type template parameter type cannot be qualified");
6178 if (CTAK == CTAK_Deduced &&
6179 !Context.hasSameType(ParamType.getNonLValueExprType(Context),
6181 // FIXME: If either type is dependent, we skip the check. This isn't
6182 // correct, since during deduction we're supposed to have replaced each
6183 // template parameter with some unique (non-dependent) placeholder.
6184 // FIXME: If the argument type contains 'auto', we carry on and fail the
6185 // type check in order to force specific types to be more specialized than
6186 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
6188 if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
6189 !Arg->getType()->getContainedAutoType()) {
6190 Converted = TemplateArgument(Arg);
6193 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
6194 // we should actually be checking the type of the template argument in P,
6195 // not the type of the template argument deduced from A, against the
6196 // template parameter type.
6197 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
6199 << ParamType.getUnqualifiedType();
6200 Diag(Param->getLocation(), diag::note_template_param_here);
6204 // If either the parameter has a dependent type or the argument is
6205 // type-dependent, there's nothing we can check now.
6206 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
6207 // FIXME: Produce a cloned, canonical expression?
6208 Converted = TemplateArgument(Arg);
6212 // The initialization of the parameter from the argument is
6213 // a constant-evaluated context.
6214 EnterExpressionEvaluationContext ConstantEvaluated(
6215 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6217 if (getLangOpts().CPlusPlus17) {
6218 // C++17 [temp.arg.nontype]p1:
6219 // A template-argument for a non-type template parameter shall be
6220 // a converted constant expression of the type of the template-parameter.
6222 ExprResult ArgResult = CheckConvertedConstantExpression(
6223 Arg, ParamType, Value, CCEK_TemplateArg);
6224 if (ArgResult.isInvalid())
6227 // For a value-dependent argument, CheckConvertedConstantExpression is
6228 // permitted (and expected) to be unable to determine a value.
6229 if (ArgResult.get()->isValueDependent()) {
6230 Converted = TemplateArgument(ArgResult.get());
6234 QualType CanonParamType = Context.getCanonicalType(ParamType);
6236 // Convert the APValue to a TemplateArgument.
6237 switch (Value.getKind()) {
6238 case APValue::Uninitialized:
6239 assert(ParamType->isNullPtrType());
6240 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
6243 assert(ParamType->isIntegralOrEnumerationType());
6244 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
6246 case APValue::MemberPointer: {
6247 assert(ParamType->isMemberPointerType());
6249 // FIXME: We need TemplateArgument representation and mangling for these.
6250 if (!Value.getMemberPointerPath().empty()) {
6251 Diag(Arg->getLocStart(),
6252 diag::err_template_arg_member_ptr_base_derived_not_supported)
6253 << Value.getMemberPointerDecl() << ParamType
6254 << Arg->getSourceRange();
6258 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
6259 Converted = VD ? TemplateArgument(VD, CanonParamType)
6260 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
6263 case APValue::LValue: {
6264 // For a non-type template-parameter of pointer or reference type,
6265 // the value of the constant expression shall not refer to
6266 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
6267 ParamType->isNullPtrType());
6268 // -- a temporary object
6269 // -- a string literal
6270 // -- the result of a typeid expression, or
6271 // -- a predefined __func__ variable
6272 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
6273 if (isa<CXXUuidofExpr>(E)) {
6274 Converted = TemplateArgument(ArgResult.get());
6277 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
6278 << Arg->getSourceRange();
6281 auto *VD = const_cast<ValueDecl *>(
6282 Value.getLValueBase().dyn_cast<const ValueDecl *>());
6284 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
6285 VD && VD->getType()->isArrayType() &&
6286 Value.getLValuePath()[0].ArrayIndex == 0 &&
6287 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
6288 // Per defect report (no number yet):
6289 // ... other than a pointer to the first element of a complete array
6291 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
6292 Value.isLValueOnePastTheEnd()) {
6293 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
6294 << Value.getAsString(Context, ParamType);
6297 assert((VD || !ParamType->isReferenceType()) &&
6298 "null reference should not be a constant expression");
6299 assert((!VD || !ParamType->isNullPtrType()) &&
6300 "non-null value of type nullptr_t?");
6301 Converted = VD ? TemplateArgument(VD, CanonParamType)
6302 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
6305 case APValue::AddrLabelDiff:
6306 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
6307 case APValue::Float:
6308 case APValue::ComplexInt:
6309 case APValue::ComplexFloat:
6310 case APValue::Vector:
6311 case APValue::Array:
6312 case APValue::Struct:
6313 case APValue::Union:
6314 llvm_unreachable("invalid kind for template argument");
6317 return ArgResult.get();
6320 // C++ [temp.arg.nontype]p5:
6321 // The following conversions are performed on each expression used
6322 // as a non-type template-argument. If a non-type
6323 // template-argument cannot be converted to the type of the
6324 // corresponding template-parameter then the program is
6326 if (ParamType->isIntegralOrEnumerationType()) {
6328 // -- for a non-type template-parameter of integral or
6329 // enumeration type, conversions permitted in a converted
6330 // constant expression are applied.
6333 // -- for a non-type template-parameter of integral or
6334 // enumeration type, integral promotions (4.5) and integral
6335 // conversions (4.7) are applied.
6337 if (getLangOpts().CPlusPlus11) {
6338 // C++ [temp.arg.nontype]p1:
6339 // A template-argument for a non-type, non-template template-parameter
6342 // -- for a non-type template-parameter of integral or enumeration
6343 // type, a converted constant expression of the type of the
6344 // template-parameter; or
6346 ExprResult ArgResult =
6347 CheckConvertedConstantExpression(Arg, ParamType, Value,
6349 if (ArgResult.isInvalid())
6352 // We can't check arbitrary value-dependent arguments.
6353 if (ArgResult.get()->isValueDependent()) {
6354 Converted = TemplateArgument(ArgResult.get());
6358 // Widen the argument value to sizeof(parameter type). This is almost
6359 // always a no-op, except when the parameter type is bool. In
6360 // that case, this may extend the argument from 1 bit to 8 bits.
6361 QualType IntegerType = ParamType;
6362 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6363 IntegerType = Enum->getDecl()->getIntegerType();
6364 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
6366 Converted = TemplateArgument(Context, Value,
6367 Context.getCanonicalType(ParamType));
6371 ExprResult ArgResult = DefaultLvalueConversion(Arg);
6372 if (ArgResult.isInvalid())
6374 Arg = ArgResult.get();
6376 QualType ArgType = Arg->getType();
6378 // C++ [temp.arg.nontype]p1:
6379 // A template-argument for a non-type, non-template
6380 // template-parameter shall be one of:
6382 // -- an integral constant-expression of integral or enumeration
6384 // -- the name of a non-type template-parameter; or
6386 if (!ArgType->isIntegralOrEnumerationType()) {
6387 Diag(Arg->getLocStart(),
6388 diag::err_template_arg_not_integral_or_enumeral)
6389 << ArgType << Arg->getSourceRange();
6390 Diag(Param->getLocation(), diag::note_template_param_here);
6392 } else if (!Arg->isValueDependent()) {
6393 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
6397 TmplArgICEDiagnoser(QualType T) : T(T) { }
6399 void diagnoseNotICE(Sema &S, SourceLocation Loc,
6400 SourceRange SR) override {
6401 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
6403 } Diagnoser(ArgType);
6405 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
6411 // From here on out, all we care about is the unqualified form
6412 // of the argument type.
6413 ArgType = ArgType.getUnqualifiedType();
6415 // Try to convert the argument to the parameter's type.
6416 if (Context.hasSameType(ParamType, ArgType)) {
6417 // Okay: no conversion necessary
6418 } else if (ParamType->isBooleanType()) {
6419 // This is an integral-to-boolean conversion.
6420 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
6421 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
6422 !ParamType->isEnumeralType()) {
6423 // This is an integral promotion or conversion.
6424 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
6426 // We can't perform this conversion.
6427 Diag(Arg->getLocStart(),
6428 diag::err_template_arg_not_convertible)
6429 << Arg->getType() << ParamType << Arg->getSourceRange();
6430 Diag(Param->getLocation(), diag::note_template_param_here);
6434 // Add the value of this argument to the list of converted
6435 // arguments. We use the bitwidth and signedness of the template
6437 if (Arg->isValueDependent()) {
6438 // The argument is value-dependent. Create a new
6439 // TemplateArgument with the converted expression.
6440 Converted = TemplateArgument(Arg);
6444 QualType IntegerType = Context.getCanonicalType(ParamType);
6445 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6446 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
6448 if (ParamType->isBooleanType()) {
6449 // Value must be zero or one.
6451 unsigned AllowedBits = Context.getTypeSize(IntegerType);
6452 if (Value.getBitWidth() != AllowedBits)
6453 Value = Value.extOrTrunc(AllowedBits);
6454 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
6456 llvm::APSInt OldValue = Value;
6458 // Coerce the template argument's value to the value it will have
6459 // based on the template parameter's type.
6460 unsigned AllowedBits = Context.getTypeSize(IntegerType);
6461 if (Value.getBitWidth() != AllowedBits)
6462 Value = Value.extOrTrunc(AllowedBits);
6463 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
6465 // Complain if an unsigned parameter received a negative value.
6466 if (IntegerType->isUnsignedIntegerOrEnumerationType()
6467 && (OldValue.isSigned() && OldValue.isNegative())) {
6468 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
6469 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6470 << Arg->getSourceRange();
6471 Diag(Param->getLocation(), diag::note_template_param_here);
6474 // Complain if we overflowed the template parameter's type.
6475 unsigned RequiredBits;
6476 if (IntegerType->isUnsignedIntegerOrEnumerationType())
6477 RequiredBits = OldValue.getActiveBits();
6478 else if (OldValue.isUnsigned())
6479 RequiredBits = OldValue.getActiveBits() + 1;
6481 RequiredBits = OldValue.getMinSignedBits();
6482 if (RequiredBits > AllowedBits) {
6483 Diag(Arg->getLocStart(),
6484 diag::warn_template_arg_too_large)
6485 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6486 << Arg->getSourceRange();
6487 Diag(Param->getLocation(), diag::note_template_param_here);
6491 Converted = TemplateArgument(Context, Value,
6492 ParamType->isEnumeralType()
6493 ? Context.getCanonicalType(ParamType)
6498 QualType ArgType = Arg->getType();
6499 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
6501 // Handle pointer-to-function, reference-to-function, and
6502 // pointer-to-member-function all in (roughly) the same way.
6503 if (// -- For a non-type template-parameter of type pointer to
6504 // function, only the function-to-pointer conversion (4.3) is
6505 // applied. If the template-argument represents a set of
6506 // overloaded functions (or a pointer to such), the matching
6507 // function is selected from the set (13.4).
6508 (ParamType->isPointerType() &&
6509 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
6510 // -- For a non-type template-parameter of type reference to
6511 // function, no conversions apply. If the template-argument
6512 // represents a set of overloaded functions, the matching
6513 // function is selected from the set (13.4).
6514 (ParamType->isReferenceType() &&
6515 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
6516 // -- For a non-type template-parameter of type pointer to
6517 // member function, no conversions apply. If the
6518 // template-argument represents a set of overloaded member
6519 // functions, the matching member function is selected from
6521 (ParamType->isMemberPointerType() &&
6522 ParamType->getAs<MemberPointerType>()->getPointeeType()
6523 ->isFunctionType())) {
6525 if (Arg->getType() == Context.OverloadTy) {
6526 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
6529 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
6532 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6533 ArgType = Arg->getType();
6538 if (!ParamType->isMemberPointerType()) {
6539 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6546 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6552 if (ParamType->isPointerType()) {
6553 // -- for a non-type template-parameter of type pointer to
6554 // object, qualification conversions (4.4) and the
6555 // array-to-pointer conversion (4.2) are applied.
6556 // C++0x also allows a value of std::nullptr_t.
6557 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
6558 "Only object pointers allowed here");
6560 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6567 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
6568 // -- For a non-type template-parameter of type reference to
6569 // object, no conversions apply. The type referred to by the
6570 // reference may be more cv-qualified than the (otherwise
6571 // identical) type of the template-argument. The
6572 // template-parameter is bound directly to the
6573 // template-argument, which must be an lvalue.
6574 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
6575 "Only object references allowed here");
6577 if (Arg->getType() == Context.OverloadTy) {
6578 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
6579 ParamRefType->getPointeeType(),
6582 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
6585 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6586 ArgType = Arg->getType();
6591 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6598 // Deal with parameters of type std::nullptr_t.
6599 if (ParamType->isNullPtrType()) {
6600 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6601 Converted = TemplateArgument(Arg);
6605 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
6606 case NPV_NotNullPointer:
6607 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
6608 << Arg->getType() << ParamType;
6609 Diag(Param->getLocation(), diag::note_template_param_here);
6615 case NPV_NullPointer:
6616 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6617 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
6623 // -- For a non-type template-parameter of type pointer to data
6624 // member, qualification conversions (4.4) are applied.
6625 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
6627 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6633 static void DiagnoseTemplateParameterListArityMismatch(
6634 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
6635 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
6637 /// Check a template argument against its corresponding
6638 /// template template parameter.
6640 /// This routine implements the semantics of C++ [temp.arg.template].
6641 /// It returns true if an error occurred, and false otherwise.
6642 bool Sema::CheckTemplateTemplateArgument(TemplateParameterList *Params,
6643 TemplateArgumentLoc &Arg) {
6644 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
6645 TemplateDecl *Template = Name.getAsTemplateDecl();
6647 // Any dependent template name is fine.
6648 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
6652 if (Template->isInvalidDecl())
6655 // C++0x [temp.arg.template]p1:
6656 // A template-argument for a template template-parameter shall be
6657 // the name of a class template or an alias template, expressed as an
6658 // id-expression. When the template-argument names a class template, only
6659 // primary class templates are considered when matching the
6660 // template template argument with the corresponding parameter;
6661 // partial specializations are not considered even if their
6662 // parameter lists match that of the template template parameter.
6664 // Note that we also allow template template parameters here, which
6665 // will happen when we are dealing with, e.g., class template
6666 // partial specializations.
6667 if (!isa<ClassTemplateDecl>(Template) &&
6668 !isa<TemplateTemplateParmDecl>(Template) &&
6669 !isa<TypeAliasTemplateDecl>(Template) &&
6670 !isa<BuiltinTemplateDecl>(Template)) {
6671 assert(isa<FunctionTemplateDecl>(Template) &&
6672 "Only function templates are possible here");
6673 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
6674 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
6678 // C++1z [temp.arg.template]p3: (DR 150)
6679 // A template-argument matches a template template-parameter P when P
6680 // is at least as specialized as the template-argument A.
6681 if (getLangOpts().RelaxedTemplateTemplateArgs) {
6682 // Quick check for the common case:
6683 // If P contains a parameter pack, then A [...] matches P if each of A's
6684 // template parameters matches the corresponding template parameter in
6685 // the template-parameter-list of P.
6686 if (TemplateParameterListsAreEqual(
6687 Template->getTemplateParameters(), Params, false,
6688 TPL_TemplateTemplateArgumentMatch, Arg.getLocation()))
6691 if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
6694 // FIXME: Produce better diagnostics for deduction failures.
6697 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
6700 TPL_TemplateTemplateArgumentMatch,
6704 /// Given a non-type template argument that refers to a
6705 /// declaration and the type of its corresponding non-type template
6706 /// parameter, produce an expression that properly refers to that
6709 Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6711 SourceLocation Loc) {
6712 // C++ [temp.param]p8:
6714 // A non-type template-parameter of type "array of T" or
6715 // "function returning T" is adjusted to be of type "pointer to
6716 // T" or "pointer to function returning T", respectively.
6717 if (ParamType->isArrayType())
6718 ParamType = Context.getArrayDecayedType(ParamType);
6719 else if (ParamType->isFunctionType())
6720 ParamType = Context.getPointerType(ParamType);
6722 // For a NULL non-type template argument, return nullptr casted to the
6723 // parameter's type.
6724 if (Arg.getKind() == TemplateArgument::NullPtr) {
6725 return ImpCastExprToType(
6726 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
6728 ParamType->getAs<MemberPointerType>()
6729 ? CK_NullToMemberPointer
6730 : CK_NullToPointer);
6732 assert(Arg.getKind() == TemplateArgument::Declaration &&
6733 "Only declaration template arguments permitted here");
6735 ValueDecl *VD = Arg.getAsDecl();
6737 if (VD->getDeclContext()->isRecord() &&
6738 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
6739 isa<IndirectFieldDecl>(VD))) {
6740 // If the value is a class member, we might have a pointer-to-member.
6741 // Determine whether the non-type template template parameter is of
6742 // pointer-to-member type. If so, we need to build an appropriate
6743 // expression for a pointer-to-member, since a "normal" DeclRefExpr
6744 // would refer to the member itself.
6745 if (ParamType->isMemberPointerType()) {
6747 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
6748 NestedNameSpecifier *Qualifier
6749 = NestedNameSpecifier::Create(Context, nullptr, false,
6750 ClassType.getTypePtr());
6752 SS.MakeTrivial(Context, Qualifier, Loc);
6754 // The actual value-ness of this is unimportant, but for
6755 // internal consistency's sake, references to instance methods
6757 ExprValueKind VK = VK_LValue;
6758 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
6761 ExprResult RefExpr = BuildDeclRefExpr(VD,
6762 VD->getType().getNonReferenceType(),
6766 if (RefExpr.isInvalid())
6769 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
6771 // We might need to perform a trailing qualification conversion, since
6772 // the element type on the parameter could be more qualified than the
6773 // element type in the expression we constructed.
6774 bool ObjCLifetimeConversion;
6775 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
6776 ParamType.getUnqualifiedType(), false,
6777 ObjCLifetimeConversion))
6778 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
6780 assert(!RefExpr.isInvalid() &&
6781 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
6782 ParamType.getUnqualifiedType()));
6787 QualType T = VD->getType().getNonReferenceType();
6789 if (ParamType->isPointerType()) {
6790 // When the non-type template parameter is a pointer, take the
6791 // address of the declaration.
6792 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
6793 if (RefExpr.isInvalid())
6796 if (!Context.hasSameUnqualifiedType(ParamType->getPointeeType(), T) &&
6797 (T->isFunctionType() || T->isArrayType())) {
6798 // Decay functions and arrays unless we're forming a pointer to array.
6799 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
6800 if (RefExpr.isInvalid())
6806 // Take the address of everything else
6807 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
6810 ExprValueKind VK = VK_RValue;
6812 // If the non-type template parameter has reference type, qualify the
6813 // resulting declaration reference with the extra qualifiers on the
6814 // type that the reference refers to.
6815 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
6817 T = Context.getQualifiedType(T,
6818 TargetRef->getPointeeType().getQualifiers());
6819 } else if (isa<FunctionDecl>(VD)) {
6820 // References to functions are always lvalues.
6824 return BuildDeclRefExpr(VD, T, VK, Loc);
6827 /// Construct a new expression that refers to the given
6828 /// integral template argument with the given source-location
6831 /// This routine takes care of the mapping from an integral template
6832 /// argument (which may have any integral type) to the appropriate
6835 Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6836 SourceLocation Loc) {
6837 assert(Arg.getKind() == TemplateArgument::Integral &&
6838 "Operation is only valid for integral template arguments");
6839 QualType OrigT = Arg.getIntegralType();
6841 // If this is an enum type that we're instantiating, we need to use an integer
6842 // type the same size as the enumerator. We don't want to build an
6843 // IntegerLiteral with enum type. The integer type of an enum type can be of
6844 // any integral type with C++11 enum classes, make sure we create the right
6845 // type of literal for it.
6847 if (const EnumType *ET = OrigT->getAs<EnumType>())
6848 T = ET->getDecl()->getIntegerType();
6851 if (T->isAnyCharacterType()) {
6852 CharacterLiteral::CharacterKind Kind;
6853 if (T->isWideCharType())
6854 Kind = CharacterLiteral::Wide;
6855 else if (T->isChar8Type() && getLangOpts().Char8)
6856 Kind = CharacterLiteral::UTF8;
6857 else if (T->isChar16Type())
6858 Kind = CharacterLiteral::UTF16;
6859 else if (T->isChar32Type())
6860 Kind = CharacterLiteral::UTF32;
6862 Kind = CharacterLiteral::Ascii;
6864 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
6866 } else if (T->isBooleanType()) {
6867 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
6869 } else if (T->isNullPtrType()) {
6870 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
6872 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
6875 if (OrigT->isEnumeralType()) {
6876 // FIXME: This is a hack. We need a better way to handle substituted
6877 // non-type template parameters.
6878 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
6880 Context.getTrivialTypeSourceInfo(OrigT, Loc),
6887 /// Match two template parameters within template parameter lists.
6888 static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
6890 Sema::TemplateParameterListEqualKind Kind,
6891 SourceLocation TemplateArgLoc) {
6892 // Check the actual kind (type, non-type, template).
6893 if (Old->getKind() != New->getKind()) {
6895 unsigned NextDiag = diag::err_template_param_different_kind;
6896 if (TemplateArgLoc.isValid()) {
6897 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6898 NextDiag = diag::note_template_param_different_kind;
6900 S.Diag(New->getLocation(), NextDiag)
6901 << (Kind != Sema::TPL_TemplateMatch);
6902 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
6903 << (Kind != Sema::TPL_TemplateMatch);
6909 // Check that both are parameter packs or neither are parameter packs.
6910 // However, if we are matching a template template argument to a
6911 // template template parameter, the template template parameter can have
6912 // a parameter pack where the template template argument does not.
6913 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
6914 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
6915 Old->isTemplateParameterPack())) {
6917 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
6918 if (TemplateArgLoc.isValid()) {
6919 S.Diag(TemplateArgLoc,
6920 diag::err_template_arg_template_params_mismatch);
6921 NextDiag = diag::note_template_parameter_pack_non_pack;
6924 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
6925 : isa<NonTypeTemplateParmDecl>(New)? 1
6927 S.Diag(New->getLocation(), NextDiag)
6928 << ParamKind << New->isParameterPack();
6929 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
6930 << ParamKind << Old->isParameterPack();
6936 // For non-type template parameters, check the type of the parameter.
6937 if (NonTypeTemplateParmDecl *OldNTTP
6938 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
6939 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
6941 // If we are matching a template template argument to a template
6942 // template parameter and one of the non-type template parameter types
6943 // is dependent, then we must wait until template instantiation time
6944 // to actually compare the arguments.
6945 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
6946 (OldNTTP->getType()->isDependentType() ||
6947 NewNTTP->getType()->isDependentType()))
6950 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
6952 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
6953 if (TemplateArgLoc.isValid()) {
6954 S.Diag(TemplateArgLoc,
6955 diag::err_template_arg_template_params_mismatch);
6956 NextDiag = diag::note_template_nontype_parm_different_type;
6958 S.Diag(NewNTTP->getLocation(), NextDiag)
6959 << NewNTTP->getType()
6960 << (Kind != Sema::TPL_TemplateMatch);
6961 S.Diag(OldNTTP->getLocation(),
6962 diag::note_template_nontype_parm_prev_declaration)
6963 << OldNTTP->getType();
6972 // For template template parameters, check the template parameter types.
6973 // The template parameter lists of template template
6974 // parameters must agree.
6975 if (TemplateTemplateParmDecl *OldTTP
6976 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
6977 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
6978 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
6979 OldTTP->getTemplateParameters(),
6981 (Kind == Sema::TPL_TemplateMatch
6982 ? Sema::TPL_TemplateTemplateParmMatch
6990 /// Diagnose a known arity mismatch when comparing template argument
6993 void DiagnoseTemplateParameterListArityMismatch(Sema &S,
6994 TemplateParameterList *New,
6995 TemplateParameterList *Old,
6996 Sema::TemplateParameterListEqualKind Kind,
6997 SourceLocation TemplateArgLoc) {
6998 unsigned NextDiag = diag::err_template_param_list_different_arity;
6999 if (TemplateArgLoc.isValid()) {
7000 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7001 NextDiag = diag::note_template_param_list_different_arity;
7003 S.Diag(New->getTemplateLoc(), NextDiag)
7004 << (New->size() > Old->size())
7005 << (Kind != Sema::TPL_TemplateMatch)
7006 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
7007 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
7008 << (Kind != Sema::TPL_TemplateMatch)
7009 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
7012 /// Determine whether the given template parameter lists are
7015 /// \param New The new template parameter list, typically written in the
7016 /// source code as part of a new template declaration.
7018 /// \param Old The old template parameter list, typically found via
7019 /// name lookup of the template declared with this template parameter
7022 /// \param Complain If true, this routine will produce a diagnostic if
7023 /// the template parameter lists are not equivalent.
7025 /// \param Kind describes how we are to match the template parameter lists.
7027 /// \param TemplateArgLoc If this source location is valid, then we
7028 /// are actually checking the template parameter list of a template
7029 /// argument (New) against the template parameter list of its
7030 /// corresponding template template parameter (Old). We produce
7031 /// slightly different diagnostics in this scenario.
7033 /// \returns True if the template parameter lists are equal, false
7036 Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
7037 TemplateParameterList *Old,
7039 TemplateParameterListEqualKind Kind,
7040 SourceLocation TemplateArgLoc) {
7041 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
7043 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7049 // C++0x [temp.arg.template]p3:
7050 // A template-argument matches a template template-parameter (call it P)
7051 // when each of the template parameters in the template-parameter-list of
7052 // the template-argument's corresponding class template or alias template
7053 // (call it A) matches the corresponding template parameter in the
7054 // template-parameter-list of P. [...]
7055 TemplateParameterList::iterator NewParm = New->begin();
7056 TemplateParameterList::iterator NewParmEnd = New->end();
7057 for (TemplateParameterList::iterator OldParm = Old->begin(),
7058 OldParmEnd = Old->end();
7059 OldParm != OldParmEnd; ++OldParm) {
7060 if (Kind != TPL_TemplateTemplateArgumentMatch ||
7061 !(*OldParm)->isTemplateParameterPack()) {
7062 if (NewParm == NewParmEnd) {
7064 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7070 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
7071 Kind, TemplateArgLoc))
7078 // C++0x [temp.arg.template]p3:
7079 // [...] When P's template- parameter-list contains a template parameter
7080 // pack (14.5.3), the template parameter pack will match zero or more
7081 // template parameters or template parameter packs in the
7082 // template-parameter-list of A with the same type and form as the
7083 // template parameter pack in P (ignoring whether those template
7084 // parameters are template parameter packs).
7085 for (; NewParm != NewParmEnd; ++NewParm) {
7086 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
7087 Kind, TemplateArgLoc))
7092 // Make sure we exhausted all of the arguments.
7093 if (NewParm != NewParmEnd) {
7095 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7104 /// Check whether a template can be declared within this scope.
7106 /// If the template declaration is valid in this scope, returns
7107 /// false. Otherwise, issues a diagnostic and returns true.
7109 Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
7113 // Find the nearest enclosing declaration scope.
7114 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7115 (S->getFlags() & Scope::TemplateParamScope) != 0)
7119 // A template [...] shall not have C linkage.
7120 DeclContext *Ctx = S->getEntity();
7121 if (Ctx && Ctx->isExternCContext()) {
7122 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
7123 << TemplateParams->getSourceRange();
7124 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
7125 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
7128 Ctx = Ctx->getRedeclContext();
7131 // A template-declaration can appear only as a namespace scope or
7132 // class scope declaration.
7134 if (Ctx->isFileContext())
7136 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
7137 // C++ [temp.mem]p2:
7138 // A local class shall not have member templates.
7139 if (RD->isLocalClass())
7140 return Diag(TemplateParams->getTemplateLoc(),
7141 diag::err_template_inside_local_class)
7142 << TemplateParams->getSourceRange();
7148 return Diag(TemplateParams->getTemplateLoc(),
7149 diag::err_template_outside_namespace_or_class_scope)
7150 << TemplateParams->getSourceRange();
7153 /// Determine what kind of template specialization the given declaration
7155 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
7157 return TSK_Undeclared;
7159 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
7160 return Record->getTemplateSpecializationKind();
7161 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
7162 return Function->getTemplateSpecializationKind();
7163 if (VarDecl *Var = dyn_cast<VarDecl>(D))
7164 return Var->getTemplateSpecializationKind();
7166 return TSK_Undeclared;
7169 /// Check whether a specialization is well-formed in the current
7172 /// This routine determines whether a template specialization can be declared
7173 /// in the current context (C++ [temp.expl.spec]p2).
7175 /// \param S the semantic analysis object for which this check is being
7178 /// \param Specialized the entity being specialized or instantiated, which
7179 /// may be a kind of template (class template, function template, etc.) or
7180 /// a member of a class template (member function, static data member,
7183 /// \param PrevDecl the previous declaration of this entity, if any.
7185 /// \param Loc the location of the explicit specialization or instantiation of
7188 /// \param IsPartialSpecialization whether this is a partial specialization of
7189 /// a class template.
7191 /// \returns true if there was an error that we cannot recover from, false
7193 static bool CheckTemplateSpecializationScope(Sema &S,
7194 NamedDecl *Specialized,
7195 NamedDecl *PrevDecl,
7197 bool IsPartialSpecialization) {
7198 // Keep these "kind" numbers in sync with the %select statements in the
7199 // various diagnostics emitted by this routine.
7201 if (isa<ClassTemplateDecl>(Specialized))
7202 EntityKind = IsPartialSpecialization? 1 : 0;
7203 else if (isa<VarTemplateDecl>(Specialized))
7204 EntityKind = IsPartialSpecialization ? 3 : 2;
7205 else if (isa<FunctionTemplateDecl>(Specialized))
7207 else if (isa<CXXMethodDecl>(Specialized))
7209 else if (isa<VarDecl>(Specialized))
7211 else if (isa<RecordDecl>(Specialized))
7213 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
7216 S.Diag(Loc, diag::err_template_spec_unknown_kind)
7217 << S.getLangOpts().CPlusPlus11;
7218 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
7222 // C++ [temp.expl.spec]p2:
7223 // An explicit specialization may be declared in any scope in which
7224 // the corresponding primary template may be defined.
7225 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7226 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
7231 // C++ [temp.class.spec]p6:
7232 // A class template partial specialization may be declared in any
7233 // scope in which the primary template may be defined.
7234 DeclContext *SpecializedContext =
7235 Specialized->getDeclContext()->getRedeclContext();
7236 DeclContext *DC = S.CurContext->getRedeclContext();
7238 // Make sure that this redeclaration (or definition) occurs in the same
7239 // scope or an enclosing namespace.
7240 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
7241 : DC->Equals(SpecializedContext))) {
7242 if (isa<TranslationUnitDecl>(SpecializedContext))
7243 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
7244 << EntityKind << Specialized;
7246 auto *ND = cast<NamedDecl>(SpecializedContext);
7247 int Diag = diag::err_template_spec_redecl_out_of_scope;
7248 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
7249 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
7250 S.Diag(Loc, Diag) << EntityKind << Specialized
7251 << ND << isa<CXXRecordDecl>(ND);
7254 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
7256 // Don't allow specializing in the wrong class during error recovery.
7257 // Otherwise, things can go horribly wrong.
7265 static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
7266 if (!E->isTypeDependent())
7267 return SourceLocation();
7268 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
7269 Checker.TraverseStmt(E);
7270 if (Checker.MatchLoc.isInvalid())
7271 return E->getSourceRange();
7272 return Checker.MatchLoc;
7275 static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
7276 if (!TL.getType()->isDependentType())
7277 return SourceLocation();
7278 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
7279 Checker.TraverseTypeLoc(TL);
7280 if (Checker.MatchLoc.isInvalid())
7281 return TL.getSourceRange();
7282 return Checker.MatchLoc;
7285 /// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
7286 /// that checks non-type template partial specialization arguments.
7287 static bool CheckNonTypeTemplatePartialSpecializationArgs(
7288 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
7289 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
7290 for (unsigned I = 0; I != NumArgs; ++I) {
7291 if (Args[I].getKind() == TemplateArgument::Pack) {
7292 if (CheckNonTypeTemplatePartialSpecializationArgs(
7293 S, TemplateNameLoc, Param, Args[I].pack_begin(),
7294 Args[I].pack_size(), IsDefaultArgument))
7300 if (Args[I].getKind() != TemplateArgument::Expression)
7303 Expr *ArgExpr = Args[I].getAsExpr();
7305 // We can have a pack expansion of any of the bullets below.
7306 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
7307 ArgExpr = Expansion->getPattern();
7309 // Strip off any implicit casts we added as part of type checking.
7310 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
7311 ArgExpr = ICE->getSubExpr();
7313 // C++ [temp.class.spec]p8:
7314 // A non-type argument is non-specialized if it is the name of a
7315 // non-type parameter. All other non-type arguments are
7318 // Below, we check the two conditions that only apply to
7319 // specialized non-type arguments, so skip any non-specialized
7321 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
7322 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
7325 // C++ [temp.class.spec]p9:
7326 // Within the argument list of a class template partial
7327 // specialization, the following restrictions apply:
7328 // -- A partially specialized non-type argument expression
7329 // shall not involve a template parameter of the partial
7330 // specialization except when the argument expression is a
7331 // simple identifier.
7332 // -- The type of a template parameter corresponding to a
7333 // specialized non-type argument shall not be dependent on a
7334 // parameter of the specialization.
7335 // DR1315 removes the first bullet, leaving an incoherent set of rules.
7336 // We implement a compromise between the original rules and DR1315:
7337 // -- A specialized non-type template argument shall not be
7338 // type-dependent and the corresponding template parameter
7339 // shall have a non-dependent type.
7340 SourceRange ParamUseRange =
7341 findTemplateParameterInType(Param->getDepth(), ArgExpr);
7342 if (ParamUseRange.isValid()) {
7343 if (IsDefaultArgument) {
7344 S.Diag(TemplateNameLoc,
7345 diag::err_dependent_non_type_arg_in_partial_spec);
7346 S.Diag(ParamUseRange.getBegin(),
7347 diag::note_dependent_non_type_default_arg_in_partial_spec)
7350 S.Diag(ParamUseRange.getBegin(),
7351 diag::err_dependent_non_type_arg_in_partial_spec)
7357 ParamUseRange = findTemplateParameter(
7358 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
7359 if (ParamUseRange.isValid()) {
7360 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
7361 diag::err_dependent_typed_non_type_arg_in_partial_spec)
7362 << Param->getType();
7363 S.Diag(Param->getLocation(), diag::note_template_param_here)
7364 << (IsDefaultArgument ? ParamUseRange : SourceRange())
7373 /// Check the non-type template arguments of a class template
7374 /// partial specialization according to C++ [temp.class.spec]p9.
7376 /// \param TemplateNameLoc the location of the template name.
7377 /// \param PrimaryTemplate the template parameters of the primary class
7379 /// \param NumExplicit the number of explicitly-specified template arguments.
7380 /// \param TemplateArgs the template arguments of the class template
7381 /// partial specialization.
7383 /// \returns \c true if there was an error, \c false otherwise.
7384 bool Sema::CheckTemplatePartialSpecializationArgs(
7385 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
7386 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
7387 // We have to be conservative when checking a template in a dependent
7389 if (PrimaryTemplate->getDeclContext()->isDependentContext())
7392 TemplateParameterList *TemplateParams =
7393 PrimaryTemplate->getTemplateParameters();
7394 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7395 NonTypeTemplateParmDecl *Param
7396 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
7400 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
7401 Param, &TemplateArgs[I],
7402 1, I >= NumExplicit))
7409 DeclResult Sema::ActOnClassTemplateSpecialization(
7410 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
7411 SourceLocation ModulePrivateLoc, TemplateIdAnnotation &TemplateId,
7412 const ParsedAttributesView &Attr,
7413 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
7414 assert(TUK != TUK_Reference && "References are not specializations");
7416 CXXScopeSpec &SS = TemplateId.SS;
7418 // NOTE: KWLoc is the location of the tag keyword. This will instead
7419 // store the location of the outermost template keyword in the declaration.
7420 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
7421 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
7422 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
7423 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
7424 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
7426 // Find the class template we're specializing
7427 TemplateName Name = TemplateId.Template.get();
7428 ClassTemplateDecl *ClassTemplate
7429 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
7431 if (!ClassTemplate) {
7432 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
7433 << (Name.getAsTemplateDecl() &&
7434 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
7438 bool isMemberSpecialization = false;
7439 bool isPartialSpecialization = false;
7441 // Check the validity of the template headers that introduce this
7443 // FIXME: We probably shouldn't complain about these headers for
7444 // friend declarations.
7445 bool Invalid = false;
7446 TemplateParameterList *TemplateParams =
7447 MatchTemplateParametersToScopeSpecifier(
7448 KWLoc, TemplateNameLoc, SS, &TemplateId,
7449 TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
7454 if (TemplateParams && TemplateParams->size() > 0) {
7455 isPartialSpecialization = true;
7457 if (TUK == TUK_Friend) {
7458 Diag(KWLoc, diag::err_partial_specialization_friend)
7459 << SourceRange(LAngleLoc, RAngleLoc);
7463 // C++ [temp.class.spec]p10:
7464 // The template parameter list of a specialization shall not
7465 // contain default template argument values.
7466 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7467 Decl *Param = TemplateParams->getParam(I);
7468 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
7469 if (TTP->hasDefaultArgument()) {
7470 Diag(TTP->getDefaultArgumentLoc(),
7471 diag::err_default_arg_in_partial_spec);
7472 TTP->removeDefaultArgument();
7474 } else if (NonTypeTemplateParmDecl *NTTP
7475 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
7476 if (Expr *DefArg = NTTP->getDefaultArgument()) {
7477 Diag(NTTP->getDefaultArgumentLoc(),
7478 diag::err_default_arg_in_partial_spec)
7479 << DefArg->getSourceRange();
7480 NTTP->removeDefaultArgument();
7483 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
7484 if (TTP->hasDefaultArgument()) {
7485 Diag(TTP->getDefaultArgument().getLocation(),
7486 diag::err_default_arg_in_partial_spec)
7487 << TTP->getDefaultArgument().getSourceRange();
7488 TTP->removeDefaultArgument();
7492 } else if (TemplateParams) {
7493 if (TUK == TUK_Friend)
7494 Diag(KWLoc, diag::err_template_spec_friend)
7495 << FixItHint::CreateRemoval(
7496 SourceRange(TemplateParams->getTemplateLoc(),
7497 TemplateParams->getRAngleLoc()))
7498 << SourceRange(LAngleLoc, RAngleLoc);
7500 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
7503 // Check that the specialization uses the same tag kind as the
7504 // original template.
7505 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7506 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
7507 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
7508 Kind, TUK == TUK_Definition, KWLoc,
7509 ClassTemplate->getIdentifier())) {
7510 Diag(KWLoc, diag::err_use_with_wrong_tag)
7512 << FixItHint::CreateReplacement(KWLoc,
7513 ClassTemplate->getTemplatedDecl()->getKindName());
7514 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
7515 diag::note_previous_use);
7516 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7519 // Translate the parser's template argument list in our AST format.
7520 TemplateArgumentListInfo TemplateArgs =
7521 makeTemplateArgumentListInfo(*this, TemplateId);
7523 // Check for unexpanded parameter packs in any of the template arguments.
7524 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7525 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
7526 UPPC_PartialSpecialization))
7529 // Check that the template argument list is well-formed for this
7531 SmallVector<TemplateArgument, 4> Converted;
7532 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7533 TemplateArgs, false, Converted))
7536 // Find the class template (partial) specialization declaration that
7537 // corresponds to these arguments.
7538 if (isPartialSpecialization) {
7539 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
7540 TemplateArgs.size(), Converted))
7543 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
7544 // also do it during instantiation.
7545 bool InstantiationDependent;
7546 if (!Name.isDependent() &&
7547 !TemplateSpecializationType::anyDependentTemplateArguments(
7548 TemplateArgs.arguments(), InstantiationDependent)) {
7549 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
7550 << ClassTemplate->getDeclName();
7551 isPartialSpecialization = false;
7555 void *InsertPos = nullptr;
7556 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
7558 if (isPartialSpecialization)
7559 // FIXME: Template parameter list matters, too
7560 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
7562 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
7564 ClassTemplateSpecializationDecl *Specialization = nullptr;
7566 // Check whether we can declare a class template specialization in
7567 // the current scope.
7568 if (TUK != TUK_Friend &&
7569 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
7571 isPartialSpecialization))
7574 // The canonical type
7576 if (isPartialSpecialization) {
7577 // Build the canonical type that describes the converted template
7578 // arguments of the class template partial specialization.
7579 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7580 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
7583 if (Context.hasSameType(CanonType,
7584 ClassTemplate->getInjectedClassNameSpecialization())) {
7585 // C++ [temp.class.spec]p9b3:
7587 // -- The argument list of the specialization shall not be identical
7588 // to the implicit argument list of the primary template.
7590 // This rule has since been removed, because it's redundant given DR1495,
7591 // but we keep it because it produces better diagnostics and recovery.
7592 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
7593 << /*class template*/0 << (TUK == TUK_Definition)
7594 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
7595 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
7596 ClassTemplate->getIdentifier(),
7600 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
7601 /*FriendLoc*/SourceLocation(),
7602 TemplateParameterLists.size() - 1,
7603 TemplateParameterLists.data());
7606 // Create a new class template partial specialization declaration node.
7607 ClassTemplatePartialSpecializationDecl *PrevPartial
7608 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
7609 ClassTemplatePartialSpecializationDecl *Partial
7610 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
7611 ClassTemplate->getDeclContext(),
7612 KWLoc, TemplateNameLoc,
7619 SetNestedNameSpecifier(Partial, SS);
7620 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
7621 Partial->setTemplateParameterListsInfo(
7622 Context, TemplateParameterLists.drop_back(1));
7626 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
7627 Specialization = Partial;
7629 // If we are providing an explicit specialization of a member class
7630 // template specialization, make a note of that.
7631 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
7632 PrevPartial->setMemberSpecialization();
7634 CheckTemplatePartialSpecialization(Partial);
7636 // Create a new class template specialization declaration node for
7637 // this explicit specialization or friend declaration.
7639 = ClassTemplateSpecializationDecl::Create(Context, Kind,
7640 ClassTemplate->getDeclContext(),
7641 KWLoc, TemplateNameLoc,
7645 SetNestedNameSpecifier(Specialization, SS);
7646 if (TemplateParameterLists.size() > 0) {
7647 Specialization->setTemplateParameterListsInfo(Context,
7648 TemplateParameterLists);
7652 ClassTemplate->AddSpecialization(Specialization, InsertPos);
7654 if (CurContext->isDependentContext()) {
7655 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7656 CanonType = Context.getTemplateSpecializationType(
7657 CanonTemplate, Converted);
7659 CanonType = Context.getTypeDeclType(Specialization);
7663 // C++ [temp.expl.spec]p6:
7664 // If a template, a member template or the member of a class template is
7665 // explicitly specialized then that specialization shall be declared
7666 // before the first use of that specialization that would cause an implicit
7667 // instantiation to take place, in every translation unit in which such a
7668 // use occurs; no diagnostic is required.
7669 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
7671 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
7672 // Is there any previous explicit specialization declaration?
7673 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7680 SourceRange Range(TemplateNameLoc, RAngleLoc);
7681 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
7682 << Context.getTypeDeclType(Specialization) << Range;
7684 Diag(PrevDecl->getPointOfInstantiation(),
7685 diag::note_instantiation_required_here)
7686 << (PrevDecl->getTemplateSpecializationKind()
7687 != TSK_ImplicitInstantiation);
7692 // If this is not a friend, note that this is an explicit specialization.
7693 if (TUK != TUK_Friend)
7694 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
7696 // Check that this isn't a redefinition of this specialization.
7697 if (TUK == TUK_Definition) {
7698 RecordDecl *Def = Specialization->getDefinition();
7699 NamedDecl *Hidden = nullptr;
7700 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
7701 SkipBody->ShouldSkip = true;
7702 makeMergedDefinitionVisible(Hidden);
7703 // From here on out, treat this as just a redeclaration.
7704 TUK = TUK_Declaration;
7706 SourceRange Range(TemplateNameLoc, RAngleLoc);
7707 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
7708 Diag(Def->getLocation(), diag::note_previous_definition);
7709 Specialization->setInvalidDecl();
7714 ProcessDeclAttributeList(S, Specialization, Attr);
7716 // Add alignment attributes if necessary; these attributes are checked when
7717 // the ASTContext lays out the structure.
7718 if (TUK == TUK_Definition) {
7719 AddAlignmentAttributesForRecord(Specialization);
7720 AddMsStructLayoutForRecord(Specialization);
7723 if (ModulePrivateLoc.isValid())
7724 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
7725 << (isPartialSpecialization? 1 : 0)
7726 << FixItHint::CreateRemoval(ModulePrivateLoc);
7728 // Build the fully-sugared type for this class template
7729 // specialization as the user wrote in the specialization
7730 // itself. This means that we'll pretty-print the type retrieved
7731 // from the specialization's declaration the way that the user
7732 // actually wrote the specialization, rather than formatting the
7733 // name based on the "canonical" representation used to store the
7734 // template arguments in the specialization.
7735 TypeSourceInfo *WrittenTy
7736 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7737 TemplateArgs, CanonType);
7738 if (TUK != TUK_Friend) {
7739 Specialization->setTypeAsWritten(WrittenTy);
7740 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
7743 // C++ [temp.expl.spec]p9:
7744 // A template explicit specialization is in the scope of the
7745 // namespace in which the template was defined.
7747 // We actually implement this paragraph where we set the semantic
7748 // context (in the creation of the ClassTemplateSpecializationDecl),
7749 // but we also maintain the lexical context where the actual
7750 // definition occurs.
7751 Specialization->setLexicalDeclContext(CurContext);
7753 // We may be starting the definition of this specialization.
7754 if (TUK == TUK_Definition)
7755 Specialization->startDefinition();
7757 if (TUK == TUK_Friend) {
7758 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
7762 Friend->setAccess(AS_public);
7763 CurContext->addDecl(Friend);
7765 // Add the specialization into its lexical context, so that it can
7766 // be seen when iterating through the list of declarations in that
7767 // context. However, specializations are not found by name lookup.
7768 CurContext->addDecl(Specialization);
7770 return Specialization;
7773 Decl *Sema::ActOnTemplateDeclarator(Scope *S,
7774 MultiTemplateParamsArg TemplateParameterLists,
7776 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
7777 ActOnDocumentableDecl(NewDecl);
7781 /// Strips various properties off an implicit instantiation
7782 /// that has just been explicitly specialized.
7783 static void StripImplicitInstantiation(NamedDecl *D) {
7784 D->dropAttr<DLLImportAttr>();
7785 D->dropAttr<DLLExportAttr>();
7787 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
7788 FD->setInlineSpecified(false);
7791 /// Compute the diagnostic location for an explicit instantiation
7792 // declaration or definition.
7793 static SourceLocation DiagLocForExplicitInstantiation(
7794 NamedDecl* D, SourceLocation PointOfInstantiation) {
7795 // Explicit instantiations following a specialization have no effect and
7796 // hence no PointOfInstantiation. In that case, walk decl backwards
7797 // until a valid name loc is found.
7798 SourceLocation PrevDiagLoc = PointOfInstantiation;
7799 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
7800 Prev = Prev->getPreviousDecl()) {
7801 PrevDiagLoc = Prev->getLocation();
7803 assert(PrevDiagLoc.isValid() &&
7804 "Explicit instantiation without point of instantiation?");
7808 /// Diagnose cases where we have an explicit template specialization
7809 /// before/after an explicit template instantiation, producing diagnostics
7810 /// for those cases where they are required and determining whether the
7811 /// new specialization/instantiation will have any effect.
7813 /// \param NewLoc the location of the new explicit specialization or
7816 /// \param NewTSK the kind of the new explicit specialization or instantiation.
7818 /// \param PrevDecl the previous declaration of the entity.
7820 /// \param PrevTSK the kind of the old explicit specialization or instantiatin.
7822 /// \param PrevPointOfInstantiation if valid, indicates where the previus
7823 /// declaration was instantiated (either implicitly or explicitly).
7825 /// \param HasNoEffect will be set to true to indicate that the new
7826 /// specialization or instantiation has no effect and should be ignored.
7828 /// \returns true if there was an error that should prevent the introduction of
7829 /// the new declaration into the AST, false otherwise.
7831 Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
7832 TemplateSpecializationKind NewTSK,
7833 NamedDecl *PrevDecl,
7834 TemplateSpecializationKind PrevTSK,
7835 SourceLocation PrevPointOfInstantiation,
7836 bool &HasNoEffect) {
7837 HasNoEffect = false;
7840 case TSK_Undeclared:
7841 case TSK_ImplicitInstantiation:
7843 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
7844 "previous declaration must be implicit!");
7847 case TSK_ExplicitSpecialization:
7849 case TSK_Undeclared:
7850 case TSK_ExplicitSpecialization:
7851 // Okay, we're just specializing something that is either already
7852 // explicitly specialized or has merely been mentioned without any
7856 case TSK_ImplicitInstantiation:
7857 if (PrevPointOfInstantiation.isInvalid()) {
7858 // The declaration itself has not actually been instantiated, so it is
7859 // still okay to specialize it.
7860 StripImplicitInstantiation(PrevDecl);
7866 case TSK_ExplicitInstantiationDeclaration:
7867 case TSK_ExplicitInstantiationDefinition:
7868 assert((PrevTSK == TSK_ImplicitInstantiation ||
7869 PrevPointOfInstantiation.isValid()) &&
7870 "Explicit instantiation without point of instantiation?");
7872 // C++ [temp.expl.spec]p6:
7873 // If a template, a member template or the member of a class template
7874 // is explicitly specialized then that specialization shall be declared
7875 // before the first use of that specialization that would cause an
7876 // implicit instantiation to take place, in every translation unit in
7877 // which such a use occurs; no diagnostic is required.
7878 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
7879 // Is there any previous explicit specialization declaration?
7880 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
7884 Diag(NewLoc, diag::err_specialization_after_instantiation)
7886 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
7887 << (PrevTSK != TSK_ImplicitInstantiation);
7891 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
7893 case TSK_ExplicitInstantiationDeclaration:
7895 case TSK_ExplicitInstantiationDeclaration:
7896 // This explicit instantiation declaration is redundant (that's okay).
7900 case TSK_Undeclared:
7901 case TSK_ImplicitInstantiation:
7902 // We're explicitly instantiating something that may have already been
7903 // implicitly instantiated; that's fine.
7906 case TSK_ExplicitSpecialization:
7907 // C++0x [temp.explicit]p4:
7908 // For a given set of template parameters, if an explicit instantiation
7909 // of a template appears after a declaration of an explicit
7910 // specialization for that template, the explicit instantiation has no
7915 case TSK_ExplicitInstantiationDefinition:
7916 // C++0x [temp.explicit]p10:
7917 // If an entity is the subject of both an explicit instantiation
7918 // declaration and an explicit instantiation definition in the same
7919 // translation unit, the definition shall follow the declaration.
7921 diag::err_explicit_instantiation_declaration_after_definition);
7923 // Explicit instantiations following a specialization have no effect and
7924 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
7925 // until a valid name loc is found.
7926 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
7927 diag::note_explicit_instantiation_definition_here);
7932 case TSK_ExplicitInstantiationDefinition:
7934 case TSK_Undeclared:
7935 case TSK_ImplicitInstantiation:
7936 // We're explicitly instantiating something that may have already been
7937 // implicitly instantiated; that's fine.
7940 case TSK_ExplicitSpecialization:
7941 // C++ DR 259, C++0x [temp.explicit]p4:
7942 // For a given set of template parameters, if an explicit
7943 // instantiation of a template appears after a declaration of
7944 // an explicit specialization for that template, the explicit
7945 // instantiation has no effect.
7946 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
7948 Diag(PrevDecl->getLocation(),
7949 diag::note_previous_template_specialization);
7953 case TSK_ExplicitInstantiationDeclaration:
7954 // We're explicitly instantiating a definition for something for which we
7955 // were previously asked to suppress instantiations. That's fine.
7957 // C++0x [temp.explicit]p4:
7958 // For a given set of template parameters, if an explicit instantiation
7959 // of a template appears after a declaration of an explicit
7960 // specialization for that template, the explicit instantiation has no
7962 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
7963 // Is there any previous explicit specialization declaration?
7964 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7972 case TSK_ExplicitInstantiationDefinition:
7973 // C++0x [temp.spec]p5:
7974 // For a given template and a given set of template-arguments,
7975 // - an explicit instantiation definition shall appear at most once
7978 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
7979 Diag(NewLoc, (getLangOpts().MSVCCompat)
7980 ? diag::ext_explicit_instantiation_duplicate
7981 : diag::err_explicit_instantiation_duplicate)
7983 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
7984 diag::note_previous_explicit_instantiation);
7990 llvm_unreachable("Missing specialization/instantiation case?");
7993 /// Perform semantic analysis for the given dependent function
7994 /// template specialization.
7996 /// The only possible way to get a dependent function template specialization
7997 /// is with a friend declaration, like so:
8000 /// template \<class T> void foo(T);
8001 /// template \<class T> class A {
8002 /// friend void foo<>(T);
8006 /// There really isn't any useful analysis we can do here, so we
8007 /// just store the information.
8009 Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
8010 const TemplateArgumentListInfo &ExplicitTemplateArgs,
8011 LookupResult &Previous) {
8012 // Remove anything from Previous that isn't a function template in
8013 // the correct context.
8014 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
8015 LookupResult::Filter F = Previous.makeFilter();
8016 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
8017 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
8018 while (F.hasNext()) {
8019 NamedDecl *D = F.next()->getUnderlyingDecl();
8020 if (!isa<FunctionTemplateDecl>(D)) {
8022 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
8026 if (!FDLookupContext->InEnclosingNamespaceSetOf(
8027 D->getDeclContext()->getRedeclContext())) {
8029 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
8035 if (Previous.empty()) {
8036 Diag(FD->getLocation(),
8037 diag::err_dependent_function_template_spec_no_match);
8038 for (auto &P : DiscardedCandidates)
8039 Diag(P.second->getLocation(),
8040 diag::note_dependent_function_template_spec_discard_reason)
8045 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
8046 ExplicitTemplateArgs);
8050 /// Perform semantic analysis for the given function template
8053 /// This routine performs all of the semantic analysis required for an
8054 /// explicit function template specialization. On successful completion,
8055 /// the function declaration \p FD will become a function template
8058 /// \param FD the function declaration, which will be updated to become a
8059 /// function template specialization.
8061 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
8062 /// if any. Note that this may be valid info even when 0 arguments are
8063 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
8064 /// as it anyway contains info on the angle brackets locations.
8066 /// \param Previous the set of declarations that may be specialized by
8067 /// this function specialization.
8068 bool Sema::CheckFunctionTemplateSpecialization(
8069 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
8070 LookupResult &Previous) {
8071 // The set of function template specializations that could match this
8072 // explicit function template specialization.
8073 UnresolvedSet<8> Candidates;
8074 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
8075 /*ForTakingAddress=*/false);
8077 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
8078 ConvertedTemplateArgs;
8080 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
8081 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8083 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
8084 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
8085 // Only consider templates found within the same semantic lookup scope as
8087 if (!FDLookupContext->InEnclosingNamespaceSetOf(
8088 Ovl->getDeclContext()->getRedeclContext()))
8091 // When matching a constexpr member function template specialization
8092 // against the primary template, we don't yet know whether the
8093 // specialization has an implicit 'const' (because we don't know whether
8094 // it will be a static member function until we know which template it
8095 // specializes), so adjust it now assuming it specializes this template.
8096 QualType FT = FD->getType();
8097 if (FD->isConstexpr()) {
8098 CXXMethodDecl *OldMD =
8099 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
8100 if (OldMD && OldMD->isConst()) {
8101 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
8102 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8103 EPI.TypeQuals |= Qualifiers::Const;
8104 FT = Context.getFunctionType(FPT->getReturnType(),
8105 FPT->getParamTypes(), EPI);
8109 TemplateArgumentListInfo Args;
8110 if (ExplicitTemplateArgs)
8111 Args = *ExplicitTemplateArgs;
8113 // C++ [temp.expl.spec]p11:
8114 // A trailing template-argument can be left unspecified in the
8115 // template-id naming an explicit function template specialization
8116 // provided it can be deduced from the function argument type.
8117 // Perform template argument deduction to determine whether we may be
8118 // specializing this template.
8119 // FIXME: It is somewhat wasteful to build
8120 TemplateDeductionInfo Info(FailedCandidates.getLocation());
8121 FunctionDecl *Specialization = nullptr;
8122 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
8123 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
8124 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
8126 // Template argument deduction failed; record why it failed, so
8127 // that we can provide nifty diagnostics.
8128 FailedCandidates.addCandidate().set(
8129 I.getPair(), FunTmpl->getTemplatedDecl(),
8130 MakeDeductionFailureInfo(Context, TDK, Info));
8135 // Target attributes are part of the cuda function signature, so
8136 // the deduced template's cuda target must match that of the
8137 // specialization. Given that C++ template deduction does not
8138 // take target attributes into account, we reject candidates
8139 // here that have a different target.
8140 if (LangOpts.CUDA &&
8141 IdentifyCUDATarget(Specialization,
8142 /* IgnoreImplicitHDAttributes = */ true) !=
8143 IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttributes = */ true)) {
8144 FailedCandidates.addCandidate().set(
8145 I.getPair(), FunTmpl->getTemplatedDecl(),
8146 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
8150 // Record this candidate.
8151 if (ExplicitTemplateArgs)
8152 ConvertedTemplateArgs[Specialization] = std::move(Args);
8153 Candidates.addDecl(Specialization, I.getAccess());
8157 // Find the most specialized function template.
8158 UnresolvedSetIterator Result = getMostSpecialized(
8159 Candidates.begin(), Candidates.end(), FailedCandidates,
8161 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
8162 PDiag(diag::err_function_template_spec_ambiguous)
8163 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
8164 PDiag(diag::note_function_template_spec_matched));
8166 if (Result == Candidates.end())
8169 // Ignore access information; it doesn't figure into redeclaration checking.
8170 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
8172 FunctionTemplateSpecializationInfo *SpecInfo
8173 = Specialization->getTemplateSpecializationInfo();
8174 assert(SpecInfo && "Function template specialization info missing?");
8176 // Note: do not overwrite location info if previous template
8177 // specialization kind was explicit.
8178 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
8179 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
8180 Specialization->setLocation(FD->getLocation());
8181 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
8182 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
8183 // function can differ from the template declaration with respect to
8184 // the constexpr specifier.
8185 // FIXME: We need an update record for this AST mutation.
8186 // FIXME: What if there are multiple such prior declarations (for instance,
8187 // from different modules)?
8188 Specialization->setConstexpr(FD->isConstexpr());
8191 // FIXME: Check if the prior specialization has a point of instantiation.
8192 // If so, we have run afoul of .
8194 // If this is a friend declaration, then we're not really declaring
8195 // an explicit specialization.
8196 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
8198 // Check the scope of this explicit specialization.
8200 CheckTemplateSpecializationScope(*this,
8201 Specialization->getPrimaryTemplate(),
8202 Specialization, FD->getLocation(),
8206 // C++ [temp.expl.spec]p6:
8207 // If a template, a member template or the member of a class template is
8208 // explicitly specialized then that specialization shall be declared
8209 // before the first use of that specialization that would cause an implicit
8210 // instantiation to take place, in every translation unit in which such a
8211 // use occurs; no diagnostic is required.
8212 bool HasNoEffect = false;
8214 CheckSpecializationInstantiationRedecl(FD->getLocation(),
8215 TSK_ExplicitSpecialization,
8217 SpecInfo->getTemplateSpecializationKind(),
8218 SpecInfo->getPointOfInstantiation(),
8222 // Mark the prior declaration as an explicit specialization, so that later
8223 // clients know that this is an explicit specialization.
8225 // Since explicit specializations do not inherit '=delete' from their
8226 // primary function template - check if the 'specialization' that was
8227 // implicitly generated (during template argument deduction for partial
8228 // ordering) from the most specialized of all the function templates that
8229 // 'FD' could have been specializing, has a 'deleted' definition. If so,
8230 // first check that it was implicitly generated during template argument
8231 // deduction by making sure it wasn't referenced, and then reset the deleted
8232 // flag to not-deleted, so that we can inherit that information from 'FD'.
8233 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
8234 !Specialization->getCanonicalDecl()->isReferenced()) {
8235 // FIXME: This assert will not hold in the presence of modules.
8237 Specialization->getCanonicalDecl() == Specialization &&
8238 "This must be the only existing declaration of this specialization");
8239 // FIXME: We need an update record for this AST mutation.
8240 Specialization->setDeletedAsWritten(false);
8242 // FIXME: We need an update record for this AST mutation.
8243 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
8244 MarkUnusedFileScopedDecl(Specialization);
8247 // Turn the given function declaration into a function template
8248 // specialization, with the template arguments from the previous
8250 // Take copies of (semantic and syntactic) template argument lists.
8251 const TemplateArgumentList* TemplArgs = new (Context)
8252 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
8253 FD->setFunctionTemplateSpecialization(
8254 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
8255 SpecInfo->getTemplateSpecializationKind(),
8256 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
8258 // A function template specialization inherits the target attributes
8259 // of its template. (We require the attributes explicitly in the
8260 // code to match, but a template may have implicit attributes by
8261 // virtue e.g. of being constexpr, and it passes these implicit
8262 // attributes on to its specializations.)
8264 inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
8266 // The "previous declaration" for this function template specialization is
8267 // the prior function template specialization.
8269 Previous.addDecl(Specialization);
8273 /// Perform semantic analysis for the given non-template member
8276 /// This routine performs all of the semantic analysis required for an
8277 /// explicit member function specialization. On successful completion,
8278 /// the function declaration \p FD will become a member function
8281 /// \param Member the member declaration, which will be updated to become a
8284 /// \param Previous the set of declarations, one of which may be specialized
8285 /// by this function specialization; the set will be modified to contain the
8286 /// redeclared member.
8288 Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
8289 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
8291 // Try to find the member we are instantiating.
8292 NamedDecl *FoundInstantiation = nullptr;
8293 NamedDecl *Instantiation = nullptr;
8294 NamedDecl *InstantiatedFrom = nullptr;
8295 MemberSpecializationInfo *MSInfo = nullptr;
8297 if (Previous.empty()) {
8298 // Nowhere to look anyway.
8299 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
8300 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8302 NamedDecl *D = (*I)->getUnderlyingDecl();
8303 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
8304 QualType Adjusted = Function->getType();
8305 if (!hasExplicitCallingConv(Adjusted))
8306 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
8307 // This doesn't handle deduced return types, but both function
8308 // declarations should be undeduced at this point.
8309 if (Context.hasSameType(Adjusted, Method->getType())) {
8310 FoundInstantiation = *I;
8311 Instantiation = Method;
8312 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
8313 MSInfo = Method->getMemberSpecializationInfo();
8318 } else if (isa<VarDecl>(Member)) {
8320 if (Previous.isSingleResult() &&
8321 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
8322 if (PrevVar->isStaticDataMember()) {
8323 FoundInstantiation = Previous.getRepresentativeDecl();
8324 Instantiation = PrevVar;
8325 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
8326 MSInfo = PrevVar->getMemberSpecializationInfo();
8328 } else if (isa<RecordDecl>(Member)) {
8329 CXXRecordDecl *PrevRecord;
8330 if (Previous.isSingleResult() &&
8331 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
8332 FoundInstantiation = Previous.getRepresentativeDecl();
8333 Instantiation = PrevRecord;
8334 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
8335 MSInfo = PrevRecord->getMemberSpecializationInfo();
8337 } else if (isa<EnumDecl>(Member)) {
8339 if (Previous.isSingleResult() &&
8340 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
8341 FoundInstantiation = Previous.getRepresentativeDecl();
8342 Instantiation = PrevEnum;
8343 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
8344 MSInfo = PrevEnum->getMemberSpecializationInfo();
8348 if (!Instantiation) {
8349 // There is no previous declaration that matches. Since member
8350 // specializations are always out-of-line, the caller will complain about
8351 // this mismatch later.
8355 // A member specialization in a friend declaration isn't really declaring
8356 // an explicit specialization, just identifying a specific (possibly implicit)
8357 // specialization. Don't change the template specialization kind.
8359 // FIXME: Is this really valid? Other compilers reject.
8360 if (Member->getFriendObjectKind() != Decl::FOK_None) {
8361 // Preserve instantiation information.
8362 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
8363 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
8364 cast<CXXMethodDecl>(InstantiatedFrom),
8365 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
8366 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
8367 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
8368 cast<CXXRecordDecl>(InstantiatedFrom),
8369 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
8373 Previous.addDecl(FoundInstantiation);
8377 // Make sure that this is a specialization of a member.
8378 if (!InstantiatedFrom) {
8379 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
8381 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
8385 // C++ [temp.expl.spec]p6:
8386 // If a template, a member template or the member of a class template is
8387 // explicitly specialized then that specialization shall be declared
8388 // before the first use of that specialization that would cause an implicit
8389 // instantiation to take place, in every translation unit in which such a
8390 // use occurs; no diagnostic is required.
8391 assert(MSInfo && "Member specialization info missing?");
8393 bool HasNoEffect = false;
8394 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
8395 TSK_ExplicitSpecialization,
8397 MSInfo->getTemplateSpecializationKind(),
8398 MSInfo->getPointOfInstantiation(),
8402 // Check the scope of this explicit specialization.
8403 if (CheckTemplateSpecializationScope(*this,
8405 Instantiation, Member->getLocation(),
8409 // Note that this member specialization is an "instantiation of" the
8410 // corresponding member of the original template.
8411 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
8412 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
8413 if (InstantiationFunction->getTemplateSpecializationKind() ==
8414 TSK_ImplicitInstantiation) {
8415 // Explicit specializations of member functions of class templates do not
8416 // inherit '=delete' from the member function they are specializing.
8417 if (InstantiationFunction->isDeleted()) {
8418 // FIXME: This assert will not hold in the presence of modules.
8419 assert(InstantiationFunction->getCanonicalDecl() ==
8420 InstantiationFunction);
8421 // FIXME: We need an update record for this AST mutation.
8422 InstantiationFunction->setDeletedAsWritten(false);
8426 MemberFunction->setInstantiationOfMemberFunction(
8427 cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8428 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
8429 MemberVar->setInstantiationOfStaticDataMember(
8430 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8431 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
8432 MemberClass->setInstantiationOfMemberClass(
8433 cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8434 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
8435 MemberEnum->setInstantiationOfMemberEnum(
8436 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8438 llvm_unreachable("unknown member specialization kind");
8441 // Save the caller the trouble of having to figure out which declaration
8442 // this specialization matches.
8444 Previous.addDecl(FoundInstantiation);
8448 /// Complete the explicit specialization of a member of a class template by
8449 /// updating the instantiated member to be marked as an explicit specialization.
8451 /// \param OrigD The member declaration instantiated from the template.
8452 /// \param Loc The location of the explicit specialization of the member.
8453 template<typename DeclT>
8454 static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
8455 SourceLocation Loc) {
8456 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
8459 // FIXME: Inform AST mutation listeners of this AST mutation.
8460 // FIXME: If there are multiple in-class declarations of the member (from
8461 // multiple modules, or a declaration and later definition of a member type),
8462 // should we update all of them?
8463 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
8464 OrigD->setLocation(Loc);
8467 void Sema::CompleteMemberSpecialization(NamedDecl *Member,
8468 LookupResult &Previous) {
8469 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
8470 if (Instantiation == Member)
8473 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
8474 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
8475 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
8476 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
8477 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
8478 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
8479 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
8480 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
8482 llvm_unreachable("unknown member specialization kind");
8485 /// Check the scope of an explicit instantiation.
8487 /// \returns true if a serious error occurs, false otherwise.
8488 static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
8489 SourceLocation InstLoc,
8490 bool WasQualifiedName) {
8491 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
8492 DeclContext *CurContext = S.CurContext->getRedeclContext();
8494 if (CurContext->isRecord()) {
8495 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
8500 // C++11 [temp.explicit]p3:
8501 // An explicit instantiation shall appear in an enclosing namespace of its
8502 // template. If the name declared in the explicit instantiation is an
8503 // unqualified name, the explicit instantiation shall appear in the
8504 // namespace where its template is declared or, if that namespace is inline
8505 // (7.3.1), any namespace from its enclosing namespace set.
8507 // This is DR275, which we do not retroactively apply to C++98/03.
8508 if (WasQualifiedName) {
8509 if (CurContext->Encloses(OrigContext))
8512 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
8516 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
8517 if (WasQualifiedName)
8519 S.getLangOpts().CPlusPlus11?
8520 diag::err_explicit_instantiation_out_of_scope :
8521 diag::warn_explicit_instantiation_out_of_scope_0x)
8525 S.getLangOpts().CPlusPlus11?
8526 diag::err_explicit_instantiation_unqualified_wrong_namespace :
8527 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
8531 S.getLangOpts().CPlusPlus11?
8532 diag::err_explicit_instantiation_must_be_global :
8533 diag::warn_explicit_instantiation_must_be_global_0x)
8535 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
8539 /// Determine whether the given scope specifier has a template-id in it.
8540 static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
8544 // C++11 [temp.explicit]p3:
8545 // If the explicit instantiation is for a member function, a member class
8546 // or a static data member of a class template specialization, the name of
8547 // the class template specialization in the qualified-id for the member
8548 // name shall be a simple-template-id.
8550 // C++98 has the same restriction, just worded differently.
8551 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
8552 NNS = NNS->getPrefix())
8553 if (const Type *T = NNS->getAsType())
8554 if (isa<TemplateSpecializationType>(T))
8560 /// Make a dllexport or dllimport attr on a class template specialization take
8562 static void dllExportImportClassTemplateSpecialization(
8563 Sema &S, ClassTemplateSpecializationDecl *Def) {
8564 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
8565 assert(A && "dllExportImportClassTemplateSpecialization called "
8566 "on Def without dllexport or dllimport");
8568 // We reject explicit instantiations in class scope, so there should
8569 // never be any delayed exported classes to worry about.
8570 assert(S.DelayedDllExportClasses.empty() &&
8571 "delayed exports present at explicit instantiation");
8572 S.checkClassLevelDLLAttribute(Def);
8574 // Propagate attribute to base class templates.
8575 for (auto &B : Def->bases()) {
8576 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
8577 B.getType()->getAsCXXRecordDecl()))
8578 S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getLocStart());
8581 S.referenceDLLExportedClassMethods();
8584 // Explicit instantiation of a class template specialization
8585 DeclResult Sema::ActOnExplicitInstantiation(
8586 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
8587 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
8588 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
8589 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
8590 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
8591 // Find the class template we're specializing
8592 TemplateName Name = TemplateD.get();
8593 TemplateDecl *TD = Name.getAsTemplateDecl();
8594 // Check that the specialization uses the same tag kind as the
8595 // original template.
8596 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8597 assert(Kind != TTK_Enum &&
8598 "Invalid enum tag in class template explicit instantiation!");
8600 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
8602 if (!ClassTemplate) {
8603 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
8604 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
8605 Diag(TD->getLocation(), diag::note_previous_use);
8609 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
8610 Kind, /*isDefinition*/false, KWLoc,
8611 ClassTemplate->getIdentifier())) {
8612 Diag(KWLoc, diag::err_use_with_wrong_tag)
8614 << FixItHint::CreateReplacement(KWLoc,
8615 ClassTemplate->getTemplatedDecl()->getKindName());
8616 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8617 diag::note_previous_use);
8618 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8621 // C++0x [temp.explicit]p2:
8622 // There are two forms of explicit instantiation: an explicit instantiation
8623 // definition and an explicit instantiation declaration. An explicit
8624 // instantiation declaration begins with the extern keyword. [...]
8625 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
8626 ? TSK_ExplicitInstantiationDefinition
8627 : TSK_ExplicitInstantiationDeclaration;
8629 if (TSK == TSK_ExplicitInstantiationDeclaration) {
8630 // Check for dllexport class template instantiation declarations.
8631 for (const ParsedAttr &AL : Attr) {
8632 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
8634 diag::warn_attribute_dllexport_explicit_instantiation_decl);
8635 Diag(AL.getLoc(), diag::note_attribute);
8640 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
8642 diag::warn_attribute_dllexport_explicit_instantiation_decl);
8643 Diag(A->getLocation(), diag::note_attribute);
8647 // In MSVC mode, dllimported explicit instantiation definitions are treated as
8648 // instantiation declarations for most purposes.
8649 bool DLLImportExplicitInstantiationDef = false;
8650 if (TSK == TSK_ExplicitInstantiationDefinition &&
8651 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
8652 // Check for dllimport class template instantiation definitions.
8654 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
8655 for (const ParsedAttr &AL : Attr) {
8656 if (AL.getKind() == ParsedAttr::AT_DLLImport)
8658 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
8659 // dllexport trumps dllimport here.
8665 TSK = TSK_ExplicitInstantiationDeclaration;
8666 DLLImportExplicitInstantiationDef = true;
8670 // Translate the parser's template argument list in our AST format.
8671 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
8672 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
8674 // Check that the template argument list is well-formed for this
8676 SmallVector<TemplateArgument, 4> Converted;
8677 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
8678 TemplateArgs, false, Converted))
8681 // Find the class template specialization declaration that
8682 // corresponds to these arguments.
8683 void *InsertPos = nullptr;
8684 ClassTemplateSpecializationDecl *PrevDecl
8685 = ClassTemplate->findSpecialization(Converted, InsertPos);
8687 TemplateSpecializationKind PrevDecl_TSK
8688 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
8690 // C++0x [temp.explicit]p2:
8691 // [...] An explicit instantiation shall appear in an enclosing
8692 // namespace of its template. [...]
8694 // This is C++ DR 275.
8695 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
8699 ClassTemplateSpecializationDecl *Specialization = nullptr;
8701 bool HasNoEffect = false;
8703 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
8704 PrevDecl, PrevDecl_TSK,
8705 PrevDecl->getPointOfInstantiation(),
8709 // Even though HasNoEffect == true means that this explicit instantiation
8710 // has no effect on semantics, we go on to put its syntax in the AST.
8712 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
8713 PrevDecl_TSK == TSK_Undeclared) {
8714 // Since the only prior class template specialization with these
8715 // arguments was referenced but not declared, reuse that
8716 // declaration node as our own, updating the source location
8717 // for the template name to reflect our new declaration.
8718 // (Other source locations will be updated later.)
8719 Specialization = PrevDecl;
8720 Specialization->setLocation(TemplateNameLoc);
8724 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
8725 DLLImportExplicitInstantiationDef) {
8726 // The new specialization might add a dllimport attribute.
8727 HasNoEffect = false;
8731 if (!Specialization) {
8732 // Create a new class template specialization declaration node for
8733 // this explicit specialization.
8735 = ClassTemplateSpecializationDecl::Create(Context, Kind,
8736 ClassTemplate->getDeclContext(),
8737 KWLoc, TemplateNameLoc,
8741 SetNestedNameSpecifier(Specialization, SS);
8743 if (!HasNoEffect && !PrevDecl) {
8744 // Insert the new specialization.
8745 ClassTemplate->AddSpecialization(Specialization, InsertPos);
8749 // Build the fully-sugared type for this explicit instantiation as
8750 // the user wrote in the explicit instantiation itself. This means
8751 // that we'll pretty-print the type retrieved from the
8752 // specialization's declaration the way that the user actually wrote
8753 // the explicit instantiation, rather than formatting the name based
8754 // on the "canonical" representation used to store the template
8755 // arguments in the specialization.
8756 TypeSourceInfo *WrittenTy
8757 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
8759 Context.getTypeDeclType(Specialization));
8760 Specialization->setTypeAsWritten(WrittenTy);
8762 // Set source locations for keywords.
8763 Specialization->setExternLoc(ExternLoc);
8764 Specialization->setTemplateKeywordLoc(TemplateLoc);
8765 Specialization->setBraceRange(SourceRange());
8767 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
8768 ProcessDeclAttributeList(S, Specialization, Attr);
8770 // Add the explicit instantiation into its lexical context. However,
8771 // since explicit instantiations are never found by name lookup, we
8772 // just put it into the declaration context directly.
8773 Specialization->setLexicalDeclContext(CurContext);
8774 CurContext->addDecl(Specialization);
8776 // Syntax is now OK, so return if it has no other effect on semantics.
8778 // Set the template specialization kind.
8779 Specialization->setTemplateSpecializationKind(TSK);
8780 return Specialization;
8783 // C++ [temp.explicit]p3:
8784 // A definition of a class template or class member template
8785 // shall be in scope at the point of the explicit instantiation of
8786 // the class template or class member template.
8788 // This check comes when we actually try to perform the
8790 ClassTemplateSpecializationDecl *Def
8791 = cast_or_null<ClassTemplateSpecializationDecl>(
8792 Specialization->getDefinition());
8794 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
8795 else if (TSK == TSK_ExplicitInstantiationDefinition) {
8796 MarkVTableUsed(TemplateNameLoc, Specialization, true);
8797 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
8800 // Instantiate the members of this class template specialization.
8801 Def = cast_or_null<ClassTemplateSpecializationDecl>(
8802 Specialization->getDefinition());
8804 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
8805 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
8806 // TSK_ExplicitInstantiationDefinition
8807 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
8808 (TSK == TSK_ExplicitInstantiationDefinition ||
8809 DLLImportExplicitInstantiationDef)) {
8810 // FIXME: Need to notify the ASTMutationListener that we did this.
8811 Def->setTemplateSpecializationKind(TSK);
8813 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
8814 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8815 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
8816 // In the MS ABI, an explicit instantiation definition can add a dll
8817 // attribute to a template with a previous instantiation declaration.
8818 // MinGW doesn't allow this.
8819 auto *A = cast<InheritableAttr>(
8820 getDLLAttr(Specialization)->clone(getASTContext()));
8821 A->setInherited(true);
8823 dllExportImportClassTemplateSpecialization(*this, Def);
8827 // Fix a TSK_ImplicitInstantiation followed by a
8828 // TSK_ExplicitInstantiationDefinition
8829 bool NewlyDLLExported =
8830 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
8831 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
8832 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8833 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
8834 // In the MS ABI, an explicit instantiation definition can add a dll
8835 // attribute to a template with a previous implicit instantiation.
8836 // MinGW doesn't allow this. We limit clang to only adding dllexport, to
8837 // avoid potentially strange codegen behavior. For example, if we extend
8838 // this conditional to dllimport, and we have a source file calling a
8839 // method on an implicitly instantiated template class instance and then
8840 // declaring a dllimport explicit instantiation definition for the same
8841 // template class, the codegen for the method call will not respect the
8842 // dllimport, while it will with cl. The Def will already have the DLL
8843 // attribute, since the Def and Specialization will be the same in the
8844 // case of Old_TSK == TSK_ImplicitInstantiation, and we already added the
8845 // attribute to the Specialization; we just need to make it take effect.
8846 assert(Def == Specialization &&
8847 "Def and Specialization should match for implicit instantiation");
8848 dllExportImportClassTemplateSpecialization(*this, Def);
8851 // Set the template specialization kind. Make sure it is set before
8852 // instantiating the members which will trigger ASTConsumer callbacks.
8853 Specialization->setTemplateSpecializationKind(TSK);
8854 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
8857 // Set the template specialization kind.
8858 Specialization->setTemplateSpecializationKind(TSK);
8861 return Specialization;
8864 // Explicit instantiation of a member class of a class template.
8866 Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
8867 SourceLocation TemplateLoc, unsigned TagSpec,
8868 SourceLocation KWLoc, CXXScopeSpec &SS,
8869 IdentifierInfo *Name, SourceLocation NameLoc,
8870 const ParsedAttributesView &Attr) {
8873 bool IsDependent = false;
8874 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
8875 KWLoc, SS, Name, NameLoc, Attr, AS_none,
8876 /*ModulePrivateLoc=*/SourceLocation(),
8877 MultiTemplateParamsArg(), Owned, IsDependent,
8878 SourceLocation(), false, TypeResult(),
8879 /*IsTypeSpecifier*/false,
8880 /*IsTemplateParamOrArg*/false);
8881 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
8886 TagDecl *Tag = cast<TagDecl>(TagD);
8887 assert(!Tag->isEnum() && "shouldn't see enumerations here");
8889 if (Tag->isInvalidDecl())
8892 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
8893 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
8895 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
8896 << Context.getTypeDeclType(Record);
8897 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
8901 // C++0x [temp.explicit]p2:
8902 // If the explicit instantiation is for a class or member class, the
8903 // elaborated-type-specifier in the declaration shall include a
8904 // simple-template-id.
8906 // C++98 has the same restriction, just worded differently.
8907 if (!ScopeSpecifierHasTemplateId(SS))
8908 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
8909 << Record << SS.getRange();
8911 // C++0x [temp.explicit]p2:
8912 // There are two forms of explicit instantiation: an explicit instantiation
8913 // definition and an explicit instantiation declaration. An explicit
8914 // instantiation declaration begins with the extern keyword. [...]
8915 TemplateSpecializationKind TSK
8916 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
8917 : TSK_ExplicitInstantiationDeclaration;
8919 // C++0x [temp.explicit]p2:
8920 // [...] An explicit instantiation shall appear in an enclosing
8921 // namespace of its template. [...]
8923 // This is C++ DR 275.
8924 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
8926 // Verify that it is okay to explicitly instantiate here.
8927 CXXRecordDecl *PrevDecl
8928 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
8929 if (!PrevDecl && Record->getDefinition())
8932 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
8933 bool HasNoEffect = false;
8934 assert(MSInfo && "No member specialization information?");
8935 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
8937 MSInfo->getTemplateSpecializationKind(),
8938 MSInfo->getPointOfInstantiation(),
8945 CXXRecordDecl *RecordDef
8946 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
8948 // C++ [temp.explicit]p3:
8949 // A definition of a member class of a class template shall be in scope
8950 // at the point of an explicit instantiation of the member class.
8952 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
8954 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
8955 << 0 << Record->getDeclName() << Record->getDeclContext();
8956 Diag(Pattern->getLocation(), diag::note_forward_declaration)
8960 if (InstantiateClass(NameLoc, Record, Def,
8961 getTemplateInstantiationArgs(Record),
8965 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
8971 // Instantiate all of the members of the class.
8972 InstantiateClassMembers(NameLoc, RecordDef,
8973 getTemplateInstantiationArgs(Record), TSK);
8975 if (TSK == TSK_ExplicitInstantiationDefinition)
8976 MarkVTableUsed(NameLoc, RecordDef, true);
8978 // FIXME: We don't have any representation for explicit instantiations of
8979 // member classes. Such a representation is not needed for compilation, but it
8980 // should be available for clients that want to see all of the declarations in
8985 DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
8986 SourceLocation ExternLoc,
8987 SourceLocation TemplateLoc,
8989 // Explicit instantiations always require a name.
8990 // TODO: check if/when DNInfo should replace Name.
8991 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8992 DeclarationName Name = NameInfo.getName();
8994 if (!D.isInvalidType())
8995 Diag(D.getDeclSpec().getLocStart(),
8996 diag::err_explicit_instantiation_requires_name)
8997 << D.getDeclSpec().getSourceRange()
8998 << D.getSourceRange();
9003 // The scope passed in may not be a decl scope. Zip up the scope tree until
9004 // we find one that is.
9005 while ((S->getFlags() & Scope::DeclScope) == 0 ||
9006 (S->getFlags() & Scope::TemplateParamScope) != 0)
9009 // Determine the type of the declaration.
9010 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
9011 QualType R = T->getType();
9016 // A storage-class-specifier shall not be specified in [...] an explicit
9017 // instantiation (14.7.2) directive.
9018 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
9019 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
9022 } else if (D.getDeclSpec().getStorageClassSpec()
9023 != DeclSpec::SCS_unspecified) {
9024 // Complain about then remove the storage class specifier.
9025 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
9026 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9028 D.getMutableDeclSpec().ClearStorageClassSpecs();
9031 // C++0x [temp.explicit]p1:
9032 // [...] An explicit instantiation of a function template shall not use the
9033 // inline or constexpr specifiers.
9034 // Presumably, this also applies to member functions of class templates as
9036 if (D.getDeclSpec().isInlineSpecified())
9037 Diag(D.getDeclSpec().getInlineSpecLoc(),
9038 getLangOpts().CPlusPlus11 ?
9039 diag::err_explicit_instantiation_inline :
9040 diag::warn_explicit_instantiation_inline_0x)
9041 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9042 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
9043 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
9044 // not already specified.
9045 Diag(D.getDeclSpec().getConstexprSpecLoc(),
9046 diag::err_explicit_instantiation_constexpr);
9048 // A deduction guide is not on the list of entities that can be explicitly
9050 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
9051 Diag(D.getDeclSpec().getLocStart(), diag::err_deduction_guide_specialized)
9052 << /*explicit instantiation*/ 0;
9056 // C++0x [temp.explicit]p2:
9057 // There are two forms of explicit instantiation: an explicit instantiation
9058 // definition and an explicit instantiation declaration. An explicit
9059 // instantiation declaration begins with the extern keyword. [...]
9060 TemplateSpecializationKind TSK
9061 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
9062 : TSK_ExplicitInstantiationDeclaration;
9064 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
9065 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
9067 if (!R->isFunctionType()) {
9068 // C++ [temp.explicit]p1:
9069 // A [...] static data member of a class template can be explicitly
9070 // instantiated from the member definition associated with its class
9072 // C++1y [temp.explicit]p1:
9073 // A [...] variable [...] template specialization can be explicitly
9074 // instantiated from its template.
9075 if (Previous.isAmbiguous())
9078 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
9079 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
9081 if (!PrevTemplate) {
9082 if (!Prev || !Prev->isStaticDataMember()) {
9083 // We expect to see a data data member here.
9084 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
9086 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9088 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
9092 if (!Prev->getInstantiatedFromStaticDataMember()) {
9093 // FIXME: Check for explicit specialization?
9094 Diag(D.getIdentifierLoc(),
9095 diag::err_explicit_instantiation_data_member_not_instantiated)
9097 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
9098 // FIXME: Can we provide a note showing where this was declared?
9102 // Explicitly instantiate a variable template.
9104 // C++1y [dcl.spec.auto]p6:
9105 // ... A program that uses auto or decltype(auto) in a context not
9106 // explicitly allowed in this section is ill-formed.
9108 // This includes auto-typed variable template instantiations.
9109 if (R->isUndeducedType()) {
9110 Diag(T->getTypeLoc().getLocStart(),
9111 diag::err_auto_not_allowed_var_inst);
9115 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9116 // C++1y [temp.explicit]p3:
9117 // If the explicit instantiation is for a variable, the unqualified-id
9118 // in the declaration shall be a template-id.
9119 Diag(D.getIdentifierLoc(),
9120 diag::err_explicit_instantiation_without_template_id)
9122 Diag(PrevTemplate->getLocation(),
9123 diag::note_explicit_instantiation_here);
9127 // Translate the parser's template argument list into our AST format.
9128 TemplateArgumentListInfo TemplateArgs =
9129 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
9131 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
9132 D.getIdentifierLoc(), TemplateArgs);
9133 if (Res.isInvalid())
9136 // Ignore access control bits, we don't need them for redeclaration
9138 Prev = cast<VarDecl>(Res.get());
9141 // C++0x [temp.explicit]p2:
9142 // If the explicit instantiation is for a member function, a member class
9143 // or a static data member of a class template specialization, the name of
9144 // the class template specialization in the qualified-id for the member
9145 // name shall be a simple-template-id.
9147 // C++98 has the same restriction, just worded differently.
9149 // This does not apply to variable template specializations, where the
9150 // template-id is in the unqualified-id instead.
9151 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
9152 Diag(D.getIdentifierLoc(),
9153 diag::ext_explicit_instantiation_without_qualified_id)
9154 << Prev << D.getCXXScopeSpec().getRange();
9156 // Check the scope of this explicit instantiation.
9157 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
9159 // Verify that it is okay to explicitly instantiate here.
9160 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
9161 SourceLocation POI = Prev->getPointOfInstantiation();
9162 bool HasNoEffect = false;
9163 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
9164 PrevTSK, POI, HasNoEffect))
9168 // Instantiate static data member or variable template.
9169 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
9171 // Merge attributes.
9172 ProcessDeclAttributeList(S, Prev, D.getDeclSpec().getAttributes());
9174 if (TSK == TSK_ExplicitInstantiationDefinition)
9175 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
9178 // Check the new variable specialization against the parsed input.
9179 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
9180 Diag(T->getTypeLoc().getLocStart(),
9181 diag::err_invalid_var_template_spec_type)
9182 << 0 << PrevTemplate << R << Prev->getType();
9183 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
9184 << 2 << PrevTemplate->getDeclName();
9188 // FIXME: Create an ExplicitInstantiation node?
9189 return (Decl*) nullptr;
9192 // If the declarator is a template-id, translate the parser's template
9193 // argument list into our AST format.
9194 bool HasExplicitTemplateArgs = false;
9195 TemplateArgumentListInfo TemplateArgs;
9196 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9197 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
9198 HasExplicitTemplateArgs = true;
9201 // C++ [temp.explicit]p1:
9202 // A [...] function [...] can be explicitly instantiated from its template.
9203 // A member function [...] of a class template can be explicitly
9204 // instantiated from the member definition associated with its class
9206 UnresolvedSet<8> TemplateMatches;
9207 FunctionDecl *NonTemplateMatch = nullptr;
9208 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
9209 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9211 NamedDecl *Prev = *P;
9212 if (!HasExplicitTemplateArgs) {
9213 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
9214 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
9215 /*AdjustExceptionSpec*/true);
9216 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
9217 if (Method->getPrimaryTemplate()) {
9218 TemplateMatches.addDecl(Method, P.getAccess());
9220 // FIXME: Can this assert ever happen? Needs a test.
9221 assert(!NonTemplateMatch && "Multiple NonTemplateMatches");
9222 NonTemplateMatch = Method;
9228 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
9232 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9233 FunctionDecl *Specialization = nullptr;
9234 if (TemplateDeductionResult TDK
9235 = DeduceTemplateArguments(FunTmpl,
9236 (HasExplicitTemplateArgs ? &TemplateArgs
9238 R, Specialization, Info)) {
9239 // Keep track of almost-matches.
9240 FailedCandidates.addCandidate()
9241 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
9242 MakeDeductionFailureInfo(Context, TDK, Info));
9247 // Target attributes are part of the cuda function signature, so
9248 // the cuda target of the instantiated function must match that of its
9249 // template. Given that C++ template deduction does not take
9250 // target attributes into account, we reject candidates here that
9251 // have a different target.
9252 if (LangOpts.CUDA &&
9253 IdentifyCUDATarget(Specialization,
9254 /* IgnoreImplicitHDAttributes = */ true) !=
9255 IdentifyCUDATarget(D.getDeclSpec().getAttributes())) {
9256 FailedCandidates.addCandidate().set(
9257 P.getPair(), FunTmpl->getTemplatedDecl(),
9258 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
9262 TemplateMatches.addDecl(Specialization, P.getAccess());
9265 FunctionDecl *Specialization = NonTemplateMatch;
9266 if (!Specialization) {
9267 // Find the most specialized function template specialization.
9268 UnresolvedSetIterator Result = getMostSpecialized(
9269 TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates,
9270 D.getIdentifierLoc(),
9271 PDiag(diag::err_explicit_instantiation_not_known) << Name,
9272 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
9273 PDiag(diag::note_explicit_instantiation_candidate));
9275 if (Result == TemplateMatches.end())
9278 // Ignore access control bits, we don't need them for redeclaration checking.
9279 Specialization = cast<FunctionDecl>(*Result);
9282 // C++11 [except.spec]p4
9283 // In an explicit instantiation an exception-specification may be specified,
9284 // but is not required.
9285 // If an exception-specification is specified in an explicit instantiation
9286 // directive, it shall be compatible with the exception-specifications of
9287 // other declarations of that function.
9288 if (auto *FPT = R->getAs<FunctionProtoType>())
9289 if (FPT->hasExceptionSpec()) {
9291 diag::err_mismatched_exception_spec_explicit_instantiation;
9292 if (getLangOpts().MicrosoftExt)
9293 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
9294 bool Result = CheckEquivalentExceptionSpec(
9295 PDiag(DiagID) << Specialization->getType(),
9296 PDiag(diag::note_explicit_instantiation_here),
9297 Specialization->getType()->getAs<FunctionProtoType>(),
9298 Specialization->getLocation(), FPT, D.getLocStart());
9299 // In Microsoft mode, mismatching exception specifications just cause a
9301 if (!getLangOpts().MicrosoftExt && Result)
9305 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
9306 Diag(D.getIdentifierLoc(),
9307 diag::err_explicit_instantiation_member_function_not_instantiated)
9309 << (Specialization->getTemplateSpecializationKind() ==
9310 TSK_ExplicitSpecialization);
9311 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
9315 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
9316 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
9317 PrevDecl = Specialization;
9320 bool HasNoEffect = false;
9321 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
9323 PrevDecl->getTemplateSpecializationKind(),
9324 PrevDecl->getPointOfInstantiation(),
9328 // FIXME: We may still want to build some representation of this
9329 // explicit specialization.
9331 return (Decl*) nullptr;
9334 ProcessDeclAttributeList(S, Specialization, D.getDeclSpec().getAttributes());
9336 // In MSVC mode, dllimported explicit instantiation definitions are treated as
9337 // instantiation declarations.
9338 if (TSK == TSK_ExplicitInstantiationDefinition &&
9339 Specialization->hasAttr<DLLImportAttr>() &&
9340 Context.getTargetInfo().getCXXABI().isMicrosoft())
9341 TSK = TSK_ExplicitInstantiationDeclaration;
9343 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
9345 if (Specialization->isDefined()) {
9346 // Let the ASTConsumer know that this function has been explicitly
9347 // instantiated now, and its linkage might have changed.
9348 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
9349 } else if (TSK == TSK_ExplicitInstantiationDefinition)
9350 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
9352 // C++0x [temp.explicit]p2:
9353 // If the explicit instantiation is for a member function, a member class
9354 // or a static data member of a class template specialization, the name of
9355 // the class template specialization in the qualified-id for the member
9356 // name shall be a simple-template-id.
9358 // C++98 has the same restriction, just worded differently.
9359 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
9360 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
9361 D.getCXXScopeSpec().isSet() &&
9362 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
9363 Diag(D.getIdentifierLoc(),
9364 diag::ext_explicit_instantiation_without_qualified_id)
9365 << Specialization << D.getCXXScopeSpec().getRange();
9367 CheckExplicitInstantiationScope(*this,
9368 FunTmpl? (NamedDecl *)FunTmpl
9369 : Specialization->getInstantiatedFromMemberFunction(),
9370 D.getIdentifierLoc(),
9371 D.getCXXScopeSpec().isSet());
9373 // FIXME: Create some kind of ExplicitInstantiationDecl here.
9374 return (Decl*) nullptr;
9378 Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
9379 const CXXScopeSpec &SS, IdentifierInfo *Name,
9380 SourceLocation TagLoc, SourceLocation NameLoc) {
9381 // This has to hold, because SS is expected to be defined.
9382 assert(Name && "Expected a name in a dependent tag");
9384 NestedNameSpecifier *NNS = SS.getScopeRep();
9388 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9390 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
9391 Diag(NameLoc, diag::err_dependent_tag_decl)
9392 << (TUK == TUK_Definition) << Kind << SS.getRange();
9396 // Create the resulting type.
9397 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9398 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
9400 // Create type-source location information for this type.
9402 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
9403 TL.setElaboratedKeywordLoc(TagLoc);
9404 TL.setQualifierLoc(SS.getWithLocInContext(Context));
9405 TL.setNameLoc(NameLoc);
9406 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
9410 Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
9411 const CXXScopeSpec &SS, const IdentifierInfo &II,
9412 SourceLocation IdLoc) {
9416 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9418 getLangOpts().CPlusPlus11 ?
9419 diag::warn_cxx98_compat_typename_outside_of_template :
9420 diag::ext_typename_outside_of_template)
9421 << FixItHint::CreateRemoval(TypenameLoc);
9423 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9424 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
9425 TypenameLoc, QualifierLoc, II, IdLoc);
9429 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9430 if (isa<DependentNameType>(T)) {
9431 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
9432 TL.setElaboratedKeywordLoc(TypenameLoc);
9433 TL.setQualifierLoc(QualifierLoc);
9434 TL.setNameLoc(IdLoc);
9436 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
9437 TL.setElaboratedKeywordLoc(TypenameLoc);
9438 TL.setQualifierLoc(QualifierLoc);
9439 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
9442 return CreateParsedType(T, TSI);
9446 Sema::ActOnTypenameType(Scope *S,
9447 SourceLocation TypenameLoc,
9448 const CXXScopeSpec &SS,
9449 SourceLocation TemplateKWLoc,
9450 TemplateTy TemplateIn,
9451 IdentifierInfo *TemplateII,
9452 SourceLocation TemplateIILoc,
9453 SourceLocation LAngleLoc,
9454 ASTTemplateArgsPtr TemplateArgsIn,
9455 SourceLocation RAngleLoc) {
9456 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9458 getLangOpts().CPlusPlus11 ?
9459 diag::warn_cxx98_compat_typename_outside_of_template :
9460 diag::ext_typename_outside_of_template)
9461 << FixItHint::CreateRemoval(TypenameLoc);
9463 // Strangely, non-type results are not ignored by this lookup, so the
9464 // program is ill-formed if it finds an injected-class-name.
9465 if (TypenameLoc.isValid()) {
9467 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
9468 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
9470 diag::ext_out_of_line_qualified_id_type_names_constructor)
9471 << TemplateII << 0 /*injected-class-name used as template name*/
9472 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
9476 // Translate the parser's template argument list in our AST format.
9477 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9478 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
9480 TemplateName Template = TemplateIn.get();
9481 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
9482 // Construct a dependent template specialization type.
9483 assert(DTN && "dependent template has non-dependent name?");
9484 assert(DTN->getQualifier() == SS.getScopeRep());
9485 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
9486 DTN->getQualifier(),
9487 DTN->getIdentifier(),
9490 // Create source-location information for this type.
9491 TypeLocBuilder Builder;
9492 DependentTemplateSpecializationTypeLoc SpecTL
9493 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
9494 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
9495 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
9496 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
9497 SpecTL.setTemplateNameLoc(TemplateIILoc);
9498 SpecTL.setLAngleLoc(LAngleLoc);
9499 SpecTL.setRAngleLoc(RAngleLoc);
9500 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9501 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
9502 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
9505 QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
9509 // Provide source-location information for the template specialization type.
9510 TypeLocBuilder Builder;
9511 TemplateSpecializationTypeLoc SpecTL
9512 = Builder.push<TemplateSpecializationTypeLoc>(T);
9513 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
9514 SpecTL.setTemplateNameLoc(TemplateIILoc);
9515 SpecTL.setLAngleLoc(LAngleLoc);
9516 SpecTL.setRAngleLoc(RAngleLoc);
9517 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9518 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
9520 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
9521 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
9522 TL.setElaboratedKeywordLoc(TypenameLoc);
9523 TL.setQualifierLoc(SS.getWithLocInContext(Context));
9525 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
9526 return CreateParsedType(T, TSI);
9530 /// Determine whether this failed name lookup should be treated as being
9531 /// disabled by a usage of std::enable_if.
9532 static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
9533 SourceRange &CondRange, Expr *&Cond) {
9534 // We must be looking for a ::type...
9535 if (!II.isStr("type"))
9538 // ... within an explicitly-written template specialization...
9539 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
9541 TypeLoc EnableIfTy = NNS.getTypeLoc();
9542 TemplateSpecializationTypeLoc EnableIfTSTLoc =
9543 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
9544 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
9546 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
9548 // ... which names a complete class template declaration...
9549 const TemplateDecl *EnableIfDecl =
9550 EnableIfTST->getTemplateName().getAsTemplateDecl();
9551 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
9554 // ... called "enable_if".
9555 const IdentifierInfo *EnableIfII =
9556 EnableIfDecl->getDeclName().getAsIdentifierInfo();
9557 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
9560 // Assume the first template argument is the condition.
9561 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
9563 // Dig out the condition.
9565 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
9566 != TemplateArgument::Expression)
9569 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
9571 // Ignore Boolean literals; they add no value.
9572 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
9578 /// Build the type that describes a C++ typename specifier,
9579 /// e.g., "typename T::type".
9581 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
9582 SourceLocation KeywordLoc,
9583 NestedNameSpecifierLoc QualifierLoc,
9584 const IdentifierInfo &II,
9585 SourceLocation IILoc) {
9587 SS.Adopt(QualifierLoc);
9589 DeclContext *Ctx = computeDeclContext(SS);
9591 // If the nested-name-specifier is dependent and couldn't be
9592 // resolved to a type, build a typename type.
9593 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
9594 return Context.getDependentNameType(Keyword,
9595 QualifierLoc.getNestedNameSpecifier(),
9599 // If the nested-name-specifier refers to the current instantiation,
9600 // the "typename" keyword itself is superfluous. In C++03, the
9601 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
9602 // allows such extraneous "typename" keywords, and we retroactively
9603 // apply this DR to C++03 code with only a warning. In any case we continue.
9605 if (RequireCompleteDeclContext(SS, Ctx))
9608 DeclarationName Name(&II);
9609 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
9610 LookupQualifiedName(Result, Ctx, SS);
9611 unsigned DiagID = 0;
9612 Decl *Referenced = nullptr;
9613 switch (Result.getResultKind()) {
9614 case LookupResult::NotFound: {
9615 // If we're looking up 'type' within a template named 'enable_if', produce
9616 // a more specific diagnostic.
9617 SourceRange CondRange;
9618 Expr *Cond = nullptr;
9619 if (isEnableIf(QualifierLoc, II, CondRange, Cond)) {
9620 // If we have a condition, narrow it down to the specific failed
9624 std::string FailedDescription;
9625 std::tie(FailedCond, FailedDescription) =
9626 findFailedBooleanCondition(Cond, /*AllowTopLevelCond=*/true);
9628 Diag(FailedCond->getExprLoc(),
9629 diag::err_typename_nested_not_found_requirement)
9630 << FailedDescription
9631 << FailedCond->getSourceRange();
9635 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
9636 << Ctx << CondRange;
9640 DiagID = diag::err_typename_nested_not_found;
9644 case LookupResult::FoundUnresolvedValue: {
9645 // We found a using declaration that is a value. Most likely, the using
9646 // declaration itself is meant to have the 'typename' keyword.
9647 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
9649 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
9650 << Name << Ctx << FullRange;
9651 if (UnresolvedUsingValueDecl *Using
9652 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
9653 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
9654 Diag(Loc, diag::note_using_value_decl_missing_typename)
9655 << FixItHint::CreateInsertion(Loc, "typename ");
9658 // Fall through to create a dependent typename type, from which we can recover
9662 case LookupResult::NotFoundInCurrentInstantiation:
9663 // Okay, it's a member of an unknown instantiation.
9664 return Context.getDependentNameType(Keyword,
9665 QualifierLoc.getNestedNameSpecifier(),
9668 case LookupResult::Found:
9669 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
9670 // C++ [class.qual]p2:
9671 // In a lookup in which function names are not ignored and the
9672 // nested-name-specifier nominates a class C, if the name specified
9673 // after the nested-name-specifier, when looked up in C, is the
9674 // injected-class-name of C [...] then the name is instead considered
9675 // to name the constructor of class C.
9677 // Unlike in an elaborated-type-specifier, function names are not ignored
9678 // in typename-specifier lookup. However, they are ignored in all the
9679 // contexts where we form a typename type with no keyword (that is, in
9680 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
9682 // FIXME: That's not strictly true: mem-initializer-id lookup does not
9683 // ignore functions, but that appears to be an oversight.
9684 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
9685 auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
9686 if (Keyword == ETK_Typename && LookupRD && FoundRD &&
9687 FoundRD->isInjectedClassName() &&
9688 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
9689 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
9690 << &II << 1 << 0 /*'typename' keyword used*/;
9692 // We found a type. Build an ElaboratedType, since the
9693 // typename-specifier was just sugar.
9694 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
9695 return Context.getElaboratedType(Keyword,
9696 QualifierLoc.getNestedNameSpecifier(),
9697 Context.getTypeDeclType(Type));
9700 // C++ [dcl.type.simple]p2:
9701 // A type-specifier of the form
9702 // typename[opt] nested-name-specifier[opt] template-name
9703 // is a placeholder for a deduced class type [...].
9704 if (getLangOpts().CPlusPlus17) {
9705 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
9706 return Context.getElaboratedType(
9707 Keyword, QualifierLoc.getNestedNameSpecifier(),
9708 Context.getDeducedTemplateSpecializationType(TemplateName(TD),
9709 QualType(), false));
9713 DiagID = diag::err_typename_nested_not_type;
9714 Referenced = Result.getFoundDecl();
9717 case LookupResult::FoundOverloaded:
9718 DiagID = diag::err_typename_nested_not_type;
9719 Referenced = *Result.begin();
9722 case LookupResult::Ambiguous:
9726 // If we get here, it's because name lookup did not find a
9727 // type. Emit an appropriate diagnostic and return an error.
9728 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
9730 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
9732 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
9738 // See Sema::RebuildTypeInCurrentInstantiation
9739 class CurrentInstantiationRebuilder
9740 : public TreeTransform<CurrentInstantiationRebuilder> {
9742 DeclarationName Entity;
9745 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
9747 CurrentInstantiationRebuilder(Sema &SemaRef,
9749 DeclarationName Entity)
9750 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
9751 Loc(Loc), Entity(Entity) { }
9753 /// Determine whether the given type \p T has already been
9756 /// For the purposes of type reconstruction, a type has already been
9757 /// transformed if it is NULL or if it is not dependent.
9758 bool AlreadyTransformed(QualType T) {
9759 return T.isNull() || !T->isDependentType();
9762 /// Returns the location of the entity whose type is being
9764 SourceLocation getBaseLocation() { return Loc; }
9766 /// Returns the name of the entity whose type is being rebuilt.
9767 DeclarationName getBaseEntity() { return Entity; }
9769 /// Sets the "base" location and entity when that
9770 /// information is known based on another transformation.
9771 void setBase(SourceLocation Loc, DeclarationName Entity) {
9773 this->Entity = Entity;
9776 ExprResult TransformLambdaExpr(LambdaExpr *E) {
9777 // Lambdas never need to be transformed.
9781 } // end anonymous namespace
9783 /// Rebuilds a type within the context of the current instantiation.
9785 /// The type \p T is part of the type of an out-of-line member definition of
9786 /// a class template (or class template partial specialization) that was parsed
9787 /// and constructed before we entered the scope of the class template (or
9788 /// partial specialization thereof). This routine will rebuild that type now
9789 /// that we have entered the declarator's scope, which may produce different
9790 /// canonical types, e.g.,
9793 /// template<typename T>
9795 /// typedef T* pointer;
9799 /// template<typename T>
9800 /// typename X<T>::pointer X<T>::data() { ... }
9803 /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
9804 /// since we do not know that we can look into X<T> when we parsed the type.
9805 /// This function will rebuild the type, performing the lookup of "pointer"
9806 /// in X<T> and returning an ElaboratedType whose canonical type is the same
9807 /// as the canonical type of T*, allowing the return types of the out-of-line
9808 /// definition and the declaration to match.
9809 TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
9811 DeclarationName Name) {
9812 if (!T || !T->getType()->isDependentType())
9815 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
9816 return Rebuilder.TransformType(T);
9819 ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
9820 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
9822 return Rebuilder.TransformExpr(E);
9825 bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
9829 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9830 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
9832 NestedNameSpecifierLoc Rebuilt
9833 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
9841 /// Rebuild the template parameters now that we know we're in a current
9843 bool Sema::RebuildTemplateParamsInCurrentInstantiation(
9844 TemplateParameterList *Params) {
9845 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
9846 Decl *Param = Params->getParam(I);
9848 // There is nothing to rebuild in a type parameter.
9849 if (isa<TemplateTypeParmDecl>(Param))
9852 // Rebuild the template parameter list of a template template parameter.
9853 if (TemplateTemplateParmDecl *TTP
9854 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
9855 if (RebuildTemplateParamsInCurrentInstantiation(
9856 TTP->getTemplateParameters()))
9862 // Rebuild the type of a non-type template parameter.
9863 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
9864 TypeSourceInfo *NewTSI
9865 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
9866 NTTP->getLocation(),
9867 NTTP->getDeclName());
9871 if (NewTSI != NTTP->getTypeSourceInfo()) {
9872 NTTP->setTypeSourceInfo(NewTSI);
9873 NTTP->setType(NewTSI->getType());
9880 /// Produces a formatted string that describes the binding of
9881 /// template parameters to template arguments.
9883 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
9884 const TemplateArgumentList &Args) {
9885 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
9889 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
9890 const TemplateArgument *Args,
9892 SmallString<128> Str;
9893 llvm::raw_svector_ostream Out(Str);
9895 if (!Params || Params->size() == 0 || NumArgs == 0)
9896 return std::string();
9898 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
9907 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
9908 Out << Id->getName();
9914 Args[I].print(getPrintingPolicy(), Out);
9921 void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
9922 CachedTokens &Toks) {
9926 auto LPT = llvm::make_unique<LateParsedTemplate>();
9928 // Take tokens to avoid allocations
9929 LPT->Toks.swap(Toks);
9931 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
9933 FD->setLateTemplateParsed(true);
9936 void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
9939 FD->setLateTemplateParsed(false);
9942 bool Sema::IsInsideALocalClassWithinATemplateFunction() {
9943 DeclContext *DC = CurContext;
9946 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
9947 const FunctionDecl *FD = RD->isLocalClass();
9948 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
9949 } else if (DC->isTranslationUnit() || DC->isNamespace())
9952 DC = DC->getParent();
9958 /// Walk the path from which a declaration was instantiated, and check
9959 /// that every explicit specialization along that path is visible. This enforces
9960 /// C++ [temp.expl.spec]/6:
9962 /// If a template, a member template or a member of a class template is
9963 /// explicitly specialized then that specialization shall be declared before
9964 /// the first use of that specialization that would cause an implicit
9965 /// instantiation to take place, in every translation unit in which such a
9966 /// use occurs; no diagnostic is required.
9968 /// and also C++ [temp.class.spec]/1:
9970 /// A partial specialization shall be declared before the first use of a
9971 /// class template specialization that would make use of the partial
9972 /// specialization as the result of an implicit or explicit instantiation
9973 /// in every translation unit in which such a use occurs; no diagnostic is
9975 class ExplicitSpecializationVisibilityChecker {
9978 llvm::SmallVector<Module *, 8> Modules;
9981 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
9984 void check(NamedDecl *ND) {
9985 if (auto *FD = dyn_cast<FunctionDecl>(ND))
9986 return checkImpl(FD);
9987 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
9988 return checkImpl(RD);
9989 if (auto *VD = dyn_cast<VarDecl>(ND))
9990 return checkImpl(VD);
9991 if (auto *ED = dyn_cast<EnumDecl>(ND))
9992 return checkImpl(ED);
9996 void diagnose(NamedDecl *D, bool IsPartialSpec) {
9997 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
9998 : Sema::MissingImportKind::ExplicitSpecialization;
9999 const bool Recover = true;
10001 // If we got a custom set of modules (because only a subset of the
10002 // declarations are interesting), use them, otherwise let
10003 // diagnoseMissingImport intelligently pick some.
10004 if (Modules.empty())
10005 S.diagnoseMissingImport(Loc, D, Kind, Recover);
10007 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
10010 // Check a specific declaration. There are three problematic cases:
10012 // 1) The declaration is an explicit specialization of a template
10014 // 2) The declaration is an explicit specialization of a member of an
10015 // templated class.
10016 // 3) The declaration is an instantiation of a template, and that template
10017 // is an explicit specialization of a member of a templated class.
10019 // We don't need to go any deeper than that, as the instantiation of the
10020 // surrounding class / etc is not triggered by whatever triggered this
10021 // instantiation, and thus should be checked elsewhere.
10022 template<typename SpecDecl>
10023 void checkImpl(SpecDecl *Spec) {
10024 bool IsHiddenExplicitSpecialization = false;
10025 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
10026 IsHiddenExplicitSpecialization =
10027 Spec->getMemberSpecializationInfo()
10028 ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
10029 : !S.hasVisibleExplicitSpecialization(Spec, &Modules);
10031 checkInstantiated(Spec);
10034 if (IsHiddenExplicitSpecialization)
10035 diagnose(Spec->getMostRecentDecl(), false);
10038 void checkInstantiated(FunctionDecl *FD) {
10039 if (auto *TD = FD->getPrimaryTemplate())
10043 void checkInstantiated(CXXRecordDecl *RD) {
10044 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
10048 auto From = SD->getSpecializedTemplateOrPartial();
10049 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
10051 else if (auto *TD =
10052 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
10053 if (!S.hasVisibleDeclaration(TD))
10054 diagnose(TD, true);
10059 void checkInstantiated(VarDecl *RD) {
10060 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
10064 auto From = SD->getSpecializedTemplateOrPartial();
10065 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
10067 else if (auto *TD =
10068 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
10069 if (!S.hasVisibleDeclaration(TD))
10070 diagnose(TD, true);
10075 void checkInstantiated(EnumDecl *FD) {}
10077 template<typename TemplDecl>
10078 void checkTemplate(TemplDecl *TD) {
10079 if (TD->isMemberSpecialization()) {
10080 if (!S.hasVisibleMemberSpecialization(TD, &Modules))
10081 diagnose(TD->getMostRecentDecl(), false);
10085 } // end anonymous namespace
10087 void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
10088 if (!getLangOpts().Modules)
10091 ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
10094 /// Check whether a template partial specialization that we've discovered
10095 /// is hidden, and produce suitable diagnostics if so.
10096 void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
10098 llvm::SmallVector<Module *, 8> Modules;
10099 if (!hasVisibleDeclaration(Spec, &Modules))
10100 diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
10101 MissingImportKind::PartialSpecialization,