[DFAJumpThreading] Remove incoming StartBlock from all phis when unfolding select...
[llvm-project.git] / clang / lib / Sema / SemaTemplate.cpp
blobee354862212803f31cf716c682241aedb39c2364
1 //===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //===----------------------------------------------------------------------===//
7 //
8 // This file implements semantic analysis for C++ templates.
9 //===----------------------------------------------------------------------===//
11 #include "TreeTransform.h"
12 #include "clang/AST/ASTConsumer.h"
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/Decl.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/TemplateName.h"
21 #include "clang/AST/TypeVisitor.h"
22 #include "clang/Basic/Builtins.h"
23 #include "clang/Basic/DiagnosticSema.h"
24 #include "clang/Basic/LangOptions.h"
25 #include "clang/Basic/PartialDiagnostic.h"
26 #include "clang/Basic/SourceLocation.h"
27 #include "clang/Basic/Stack.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Sema/DeclSpec.h"
30 #include "clang/Sema/EnterExpressionEvaluationContext.h"
31 #include "clang/Sema/Initialization.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/Overload.h"
34 #include "clang/Sema/ParsedTemplate.h"
35 #include "clang/Sema/Scope.h"
36 #include "clang/Sema/SemaInternal.h"
37 #include "clang/Sema/Template.h"
38 #include "clang/Sema/TemplateDeduction.h"
39 #include "llvm/ADT/SmallBitVector.h"
40 #include "llvm/ADT/SmallString.h"
41 #include "llvm/ADT/StringExtras.h"
43 #include <iterator>
44 #include <optional>
45 using namespace clang;
46 using namespace sema;
48 // Exported for use by Parser.
49 SourceRange
50 clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
51 unsigned N) {
52 if (!N) return SourceRange();
53 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
56 unsigned Sema::getTemplateDepth(Scope *S) const {
57 unsigned Depth = 0;
59 // Each template parameter scope represents one level of template parameter
60 // depth.
61 for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
62 TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
63 ++Depth;
66 // Note that there are template parameters with the given depth.
67 auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(Depth, D + 1); };
69 // Look for parameters of an enclosing generic lambda. We don't create a
70 // template parameter scope for these.
71 for (FunctionScopeInfo *FSI : getFunctionScopes()) {
72 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FSI)) {
73 if (!LSI->TemplateParams.empty()) {
74 ParamsAtDepth(LSI->AutoTemplateParameterDepth);
75 break;
77 if (LSI->GLTemplateParameterList) {
78 ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
79 break;
84 // Look for parameters of an enclosing terse function template. We don't
85 // create a template parameter scope for these either.
86 for (const InventedTemplateParameterInfo &Info :
87 getInventedParameterInfos()) {
88 if (!Info.TemplateParams.empty()) {
89 ParamsAtDepth(Info.AutoTemplateParameterDepth);
90 break;
94 return Depth;
97 /// \brief Determine whether the declaration found is acceptable as the name
98 /// of a template and, if so, return that template declaration. Otherwise,
99 /// returns null.
101 /// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
102 /// is true. In all other cases it will return a TemplateDecl (or null).
103 NamedDecl *Sema::getAsTemplateNameDecl(NamedDecl *D,
104 bool AllowFunctionTemplates,
105 bool AllowDependent) {
106 D = D->getUnderlyingDecl();
108 if (isa<TemplateDecl>(D)) {
109 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
110 return nullptr;
112 return D;
115 if (const auto *Record = dyn_cast<CXXRecordDecl>(D)) {
116 // C++ [temp.local]p1:
117 // Like normal (non-template) classes, class templates have an
118 // injected-class-name (Clause 9). The injected-class-name
119 // can be used with or without a template-argument-list. When
120 // it is used without a template-argument-list, it is
121 // equivalent to the injected-class-name followed by the
122 // template-parameters of the class template enclosed in
123 // <>. When it is used with a template-argument-list, it
124 // refers to the specified class template specialization,
125 // which could be the current specialization or another
126 // specialization.
127 if (Record->isInjectedClassName()) {
128 Record = cast<CXXRecordDecl>(Record->getDeclContext());
129 if (Record->getDescribedClassTemplate())
130 return Record->getDescribedClassTemplate();
132 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Record))
133 return Spec->getSpecializedTemplate();
136 return nullptr;
139 // 'using Dependent::foo;' can resolve to a template name.
140 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
141 // injected-class-name).
142 if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
143 return D;
145 return nullptr;
148 void Sema::FilterAcceptableTemplateNames(LookupResult &R,
149 bool AllowFunctionTemplates,
150 bool AllowDependent) {
151 LookupResult::Filter filter = R.makeFilter();
152 while (filter.hasNext()) {
153 NamedDecl *Orig = filter.next();
154 if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
155 filter.erase();
157 filter.done();
160 bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
161 bool AllowFunctionTemplates,
162 bool AllowDependent,
163 bool AllowNonTemplateFunctions) {
164 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
165 if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
166 return true;
167 if (AllowNonTemplateFunctions &&
168 isa<FunctionDecl>((*I)->getUnderlyingDecl()))
169 return true;
172 return false;
175 TemplateNameKind Sema::isTemplateName(Scope *S,
176 CXXScopeSpec &SS,
177 bool hasTemplateKeyword,
178 const UnqualifiedId &Name,
179 ParsedType ObjectTypePtr,
180 bool EnteringContext,
181 TemplateTy &TemplateResult,
182 bool &MemberOfUnknownSpecialization,
183 bool Disambiguation) {
184 assert(getLangOpts().CPlusPlus && "No template names in C!");
186 DeclarationName TName;
187 MemberOfUnknownSpecialization = false;
189 switch (Name.getKind()) {
190 case UnqualifiedIdKind::IK_Identifier:
191 TName = DeclarationName(Name.Identifier);
192 break;
194 case UnqualifiedIdKind::IK_OperatorFunctionId:
195 TName = Context.DeclarationNames.getCXXOperatorName(
196 Name.OperatorFunctionId.Operator);
197 break;
199 case UnqualifiedIdKind::IK_LiteralOperatorId:
200 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
201 break;
203 default:
204 return TNK_Non_template;
207 QualType ObjectType = ObjectTypePtr.get();
209 AssumedTemplateKind AssumedTemplate;
210 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
211 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
212 MemberOfUnknownSpecialization, SourceLocation(),
213 &AssumedTemplate,
214 /*AllowTypoCorrection=*/!Disambiguation))
215 return TNK_Non_template;
217 if (AssumedTemplate != AssumedTemplateKind::None) {
218 TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
219 // Let the parser know whether we found nothing or found functions; if we
220 // found nothing, we want to more carefully check whether this is actually
221 // a function template name versus some other kind of undeclared identifier.
222 return AssumedTemplate == AssumedTemplateKind::FoundNothing
223 ? TNK_Undeclared_template
224 : TNK_Function_template;
227 if (R.empty())
228 return TNK_Non_template;
230 NamedDecl *D = nullptr;
231 UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(*R.begin());
232 if (R.isAmbiguous()) {
233 // If we got an ambiguity involving a non-function template, treat this
234 // as a template name, and pick an arbitrary template for error recovery.
235 bool AnyFunctionTemplates = false;
236 for (NamedDecl *FoundD : R) {
237 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
238 if (isa<FunctionTemplateDecl>(FoundTemplate))
239 AnyFunctionTemplates = true;
240 else {
241 D = FoundTemplate;
242 FoundUsingShadow = dyn_cast<UsingShadowDecl>(FoundD);
243 break;
248 // If we didn't find any templates at all, this isn't a template name.
249 // Leave the ambiguity for a later lookup to diagnose.
250 if (!D && !AnyFunctionTemplates) {
251 R.suppressDiagnostics();
252 return TNK_Non_template;
255 // If the only templates were function templates, filter out the rest.
256 // We'll diagnose the ambiguity later.
257 if (!D)
258 FilterAcceptableTemplateNames(R);
261 // At this point, we have either picked a single template name declaration D
262 // or we have a non-empty set of results R containing either one template name
263 // declaration or a set of function templates.
265 TemplateName Template;
266 TemplateNameKind TemplateKind;
268 unsigned ResultCount = R.end() - R.begin();
269 if (!D && ResultCount > 1) {
270 // We assume that we'll preserve the qualifier from a function
271 // template name in other ways.
272 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
273 TemplateKind = TNK_Function_template;
275 // We'll do this lookup again later.
276 R.suppressDiagnostics();
277 } else {
278 if (!D) {
279 D = getAsTemplateNameDecl(*R.begin());
280 assert(D && "unambiguous result is not a template name");
283 if (isa<UnresolvedUsingValueDecl>(D)) {
284 // We don't yet know whether this is a template-name or not.
285 MemberOfUnknownSpecialization = true;
286 return TNK_Non_template;
289 TemplateDecl *TD = cast<TemplateDecl>(D);
290 Template =
291 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
292 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
293 if (SS.isSet() && !SS.isInvalid()) {
294 NestedNameSpecifier *Qualifier = SS.getScopeRep();
295 Template = Context.getQualifiedTemplateName(Qualifier, hasTemplateKeyword,
296 Template);
299 if (isa<FunctionTemplateDecl>(TD)) {
300 TemplateKind = TNK_Function_template;
302 // We'll do this lookup again later.
303 R.suppressDiagnostics();
304 } else {
305 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
306 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
307 isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD));
308 TemplateKind =
309 isa<VarTemplateDecl>(TD) ? TNK_Var_template :
310 isa<ConceptDecl>(TD) ? TNK_Concept_template :
311 TNK_Type_template;
315 TemplateResult = TemplateTy::make(Template);
316 return TemplateKind;
319 bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
320 SourceLocation NameLoc, CXXScopeSpec &SS,
321 ParsedTemplateTy *Template /*=nullptr*/) {
322 bool MemberOfUnknownSpecialization = false;
324 // We could use redeclaration lookup here, but we don't need to: the
325 // syntactic form of a deduction guide is enough to identify it even
326 // if we can't look up the template name at all.
327 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
328 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
329 /*EnteringContext*/ false,
330 MemberOfUnknownSpecialization))
331 return false;
333 if (R.empty()) return false;
334 if (R.isAmbiguous()) {
335 // FIXME: Diagnose an ambiguity if we find at least one template.
336 R.suppressDiagnostics();
337 return false;
340 // We only treat template-names that name type templates as valid deduction
341 // guide names.
342 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
343 if (!TD || !getAsTypeTemplateDecl(TD))
344 return false;
346 if (Template)
347 *Template = TemplateTy::make(TemplateName(TD));
348 return true;
351 bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
352 SourceLocation IILoc,
353 Scope *S,
354 const CXXScopeSpec *SS,
355 TemplateTy &SuggestedTemplate,
356 TemplateNameKind &SuggestedKind) {
357 // We can't recover unless there's a dependent scope specifier preceding the
358 // template name.
359 // FIXME: Typo correction?
360 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
361 computeDeclContext(*SS))
362 return false;
364 // The code is missing a 'template' keyword prior to the dependent template
365 // name.
366 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
367 Diag(IILoc, diag::err_template_kw_missing)
368 << Qualifier << II.getName()
369 << FixItHint::CreateInsertion(IILoc, "template ");
370 SuggestedTemplate
371 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
372 SuggestedKind = TNK_Dependent_template_name;
373 return true;
376 bool Sema::LookupTemplateName(LookupResult &Found,
377 Scope *S, CXXScopeSpec &SS,
378 QualType ObjectType,
379 bool EnteringContext,
380 bool &MemberOfUnknownSpecialization,
381 RequiredTemplateKind RequiredTemplate,
382 AssumedTemplateKind *ATK,
383 bool AllowTypoCorrection) {
384 if (ATK)
385 *ATK = AssumedTemplateKind::None;
387 if (SS.isInvalid())
388 return true;
390 Found.setTemplateNameLookup(true);
392 // Determine where to perform name lookup
393 MemberOfUnknownSpecialization = false;
394 DeclContext *LookupCtx = nullptr;
395 bool IsDependent = false;
396 if (!ObjectType.isNull()) {
397 // This nested-name-specifier occurs in a member access expression, e.g.,
398 // x->B::f, and we are looking into the type of the object.
399 assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");
400 LookupCtx = computeDeclContext(ObjectType);
401 IsDependent = !LookupCtx && ObjectType->isDependentType();
402 assert((IsDependent || !ObjectType->isIncompleteType() ||
403 !ObjectType->getAs<TagType>() ||
404 ObjectType->castAs<TagType>()->isBeingDefined()) &&
405 "Caller should have completed object type");
407 // Template names cannot appear inside an Objective-C class or object type
408 // or a vector type.
410 // FIXME: This is wrong. For example:
412 // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
413 // Vec<int> vi;
414 // vi.Vec<int>::~Vec<int>();
416 // ... should be accepted but we will not treat 'Vec' as a template name
417 // here. The right thing to do would be to check if the name is a valid
418 // vector component name, and look up a template name if not. And similarly
419 // for lookups into Objective-C class and object types, where the same
420 // problem can arise.
421 if (ObjectType->isObjCObjectOrInterfaceType() ||
422 ObjectType->isVectorType()) {
423 Found.clear();
424 return false;
426 } else if (SS.isNotEmpty()) {
427 // This nested-name-specifier occurs after another nested-name-specifier,
428 // so long into the context associated with the prior nested-name-specifier.
429 LookupCtx = computeDeclContext(SS, EnteringContext);
430 IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
432 // The declaration context must be complete.
433 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
434 return true;
437 bool ObjectTypeSearchedInScope = false;
438 bool AllowFunctionTemplatesInLookup = true;
439 if (LookupCtx) {
440 // Perform "qualified" name lookup into the declaration context we
441 // computed, which is either the type of the base of a member access
442 // expression or the declaration context associated with a prior
443 // nested-name-specifier.
444 LookupQualifiedName(Found, LookupCtx);
446 // FIXME: The C++ standard does not clearly specify what happens in the
447 // case where the object type is dependent, and implementations vary. In
448 // Clang, we treat a name after a . or -> as a template-name if lookup
449 // finds a non-dependent member or member of the current instantiation that
450 // is a type template, or finds no such members and lookup in the context
451 // of the postfix-expression finds a type template. In the latter case, the
452 // name is nonetheless dependent, and we may resolve it to a member of an
453 // unknown specialization when we come to instantiate the template.
454 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
457 if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
458 // C++ [basic.lookup.classref]p1:
459 // In a class member access expression (5.2.5), if the . or -> token is
460 // immediately followed by an identifier followed by a <, the
461 // identifier must be looked up to determine whether the < is the
462 // beginning of a template argument list (14.2) or a less-than operator.
463 // The identifier is first looked up in the class of the object
464 // expression. If the identifier is not found, it is then looked up in
465 // the context of the entire postfix-expression and shall name a class
466 // template.
467 if (S)
468 LookupName(Found, S);
470 if (!ObjectType.isNull()) {
471 // FIXME: We should filter out all non-type templates here, particularly
472 // variable templates and concepts. But the exclusion of alias templates
473 // and template template parameters is a wording defect.
474 AllowFunctionTemplatesInLookup = false;
475 ObjectTypeSearchedInScope = true;
478 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
481 if (Found.isAmbiguous())
482 return false;
484 if (ATK && SS.isEmpty() && ObjectType.isNull() &&
485 !RequiredTemplate.hasTemplateKeyword()) {
486 // C++2a [temp.names]p2:
487 // A name is also considered to refer to a template if it is an
488 // unqualified-id followed by a < and name lookup finds either one or more
489 // functions or finds nothing.
491 // To keep our behavior consistent, we apply the "finds nothing" part in
492 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
493 // successfully form a call to an undeclared template-id.
494 bool AllFunctions =
495 getLangOpts().CPlusPlus20 && llvm::all_of(Found, [](NamedDecl *ND) {
496 return isa<FunctionDecl>(ND->getUnderlyingDecl());
498 if (AllFunctions || (Found.empty() && !IsDependent)) {
499 // If lookup found any functions, or if this is a name that can only be
500 // used for a function, then strongly assume this is a function
501 // template-id.
502 *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
503 ? AssumedTemplateKind::FoundNothing
504 : AssumedTemplateKind::FoundFunctions;
505 Found.clear();
506 return false;
510 if (Found.empty() && !IsDependent && AllowTypoCorrection) {
511 // If we did not find any names, and this is not a disambiguation, attempt
512 // to correct any typos.
513 DeclarationName Name = Found.getLookupName();
514 Found.clear();
515 // Simple filter callback that, for keywords, only accepts the C++ *_cast
516 DefaultFilterCCC FilterCCC{};
517 FilterCCC.WantTypeSpecifiers = false;
518 FilterCCC.WantExpressionKeywords = false;
519 FilterCCC.WantRemainingKeywords = false;
520 FilterCCC.WantCXXNamedCasts = true;
521 if (TypoCorrection Corrected =
522 CorrectTypo(Found.getLookupNameInfo(), Found.getLookupKind(), S,
523 &SS, FilterCCC, CTK_ErrorRecovery, LookupCtx)) {
524 if (auto *ND = Corrected.getFoundDecl())
525 Found.addDecl(ND);
526 FilterAcceptableTemplateNames(Found);
527 if (Found.isAmbiguous()) {
528 Found.clear();
529 } else if (!Found.empty()) {
530 Found.setLookupName(Corrected.getCorrection());
531 if (LookupCtx) {
532 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
533 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
534 Name.getAsString() == CorrectedStr;
535 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
536 << Name << LookupCtx << DroppedSpecifier
537 << SS.getRange());
538 } else {
539 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
545 NamedDecl *ExampleLookupResult =
546 Found.empty() ? nullptr : Found.getRepresentativeDecl();
547 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
548 if (Found.empty()) {
549 if (IsDependent) {
550 MemberOfUnknownSpecialization = true;
551 return false;
554 // If a 'template' keyword was used, a lookup that finds only non-template
555 // names is an error.
556 if (ExampleLookupResult && RequiredTemplate) {
557 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
558 << Found.getLookupName() << SS.getRange()
559 << RequiredTemplate.hasTemplateKeyword()
560 << RequiredTemplate.getTemplateKeywordLoc();
561 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
562 diag::note_template_kw_refers_to_non_template)
563 << Found.getLookupName();
564 return true;
567 return false;
570 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
571 !getLangOpts().CPlusPlus11) {
572 // C++03 [basic.lookup.classref]p1:
573 // [...] If the lookup in the class of the object expression finds a
574 // template, the name is also looked up in the context of the entire
575 // postfix-expression and [...]
577 // Note: C++11 does not perform this second lookup.
578 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
579 LookupOrdinaryName);
580 FoundOuter.setTemplateNameLookup(true);
581 LookupName(FoundOuter, S);
582 // FIXME: We silently accept an ambiguous lookup here, in violation of
583 // [basic.lookup]/1.
584 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
586 NamedDecl *OuterTemplate;
587 if (FoundOuter.empty()) {
588 // - if the name is not found, the name found in the class of the
589 // object expression is used, otherwise
590 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
591 !(OuterTemplate =
592 getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
593 // - if the name is found in the context of the entire
594 // postfix-expression and does not name a class template, the name
595 // found in the class of the object expression is used, otherwise
596 FoundOuter.clear();
597 } else if (!Found.isSuppressingAmbiguousDiagnostics()) {
598 // - if the name found is a class template, it must refer to the same
599 // entity as the one found in the class of the object expression,
600 // otherwise the program is ill-formed.
601 if (!Found.isSingleResult() ||
602 getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
603 OuterTemplate->getCanonicalDecl()) {
604 Diag(Found.getNameLoc(),
605 diag::ext_nested_name_member_ref_lookup_ambiguous)
606 << Found.getLookupName()
607 << ObjectType;
608 Diag(Found.getRepresentativeDecl()->getLocation(),
609 diag::note_ambig_member_ref_object_type)
610 << ObjectType;
611 Diag(FoundOuter.getFoundDecl()->getLocation(),
612 diag::note_ambig_member_ref_scope);
614 // Recover by taking the template that we found in the object
615 // expression's type.
620 return false;
623 void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
624 SourceLocation Less,
625 SourceLocation Greater) {
626 if (TemplateName.isInvalid())
627 return;
629 DeclarationNameInfo NameInfo;
630 CXXScopeSpec SS;
631 LookupNameKind LookupKind;
633 DeclContext *LookupCtx = nullptr;
634 NamedDecl *Found = nullptr;
635 bool MissingTemplateKeyword = false;
637 // Figure out what name we looked up.
638 if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
639 NameInfo = DRE->getNameInfo();
640 SS.Adopt(DRE->getQualifierLoc());
641 LookupKind = LookupOrdinaryName;
642 Found = DRE->getFoundDecl();
643 } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
644 NameInfo = ME->getMemberNameInfo();
645 SS.Adopt(ME->getQualifierLoc());
646 LookupKind = LookupMemberName;
647 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
648 Found = ME->getMemberDecl();
649 } else if (auto *DSDRE =
650 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
651 NameInfo = DSDRE->getNameInfo();
652 SS.Adopt(DSDRE->getQualifierLoc());
653 MissingTemplateKeyword = true;
654 } else if (auto *DSME =
655 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
656 NameInfo = DSME->getMemberNameInfo();
657 SS.Adopt(DSME->getQualifierLoc());
658 MissingTemplateKeyword = true;
659 } else {
660 llvm_unreachable("unexpected kind of potential template name");
663 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
664 // was missing.
665 if (MissingTemplateKeyword) {
666 Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
667 << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater);
668 return;
671 // Try to correct the name by looking for templates and C++ named casts.
672 struct TemplateCandidateFilter : CorrectionCandidateCallback {
673 Sema &S;
674 TemplateCandidateFilter(Sema &S) : S(S) {
675 WantTypeSpecifiers = false;
676 WantExpressionKeywords = false;
677 WantRemainingKeywords = false;
678 WantCXXNamedCasts = true;
680 bool ValidateCandidate(const TypoCorrection &Candidate) override {
681 if (auto *ND = Candidate.getCorrectionDecl())
682 return S.getAsTemplateNameDecl(ND);
683 return Candidate.isKeyword();
686 std::unique_ptr<CorrectionCandidateCallback> clone() override {
687 return std::make_unique<TemplateCandidateFilter>(*this);
691 DeclarationName Name = NameInfo.getName();
692 TemplateCandidateFilter CCC(*this);
693 if (TypoCorrection Corrected = CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
694 CTK_ErrorRecovery, LookupCtx)) {
695 auto *ND = Corrected.getFoundDecl();
696 if (ND)
697 ND = getAsTemplateNameDecl(ND);
698 if (ND || Corrected.isKeyword()) {
699 if (LookupCtx) {
700 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
701 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
702 Name.getAsString() == CorrectedStr;
703 diagnoseTypo(Corrected,
704 PDiag(diag::err_non_template_in_member_template_id_suggest)
705 << Name << LookupCtx << DroppedSpecifier
706 << SS.getRange(), false);
707 } else {
708 diagnoseTypo(Corrected,
709 PDiag(diag::err_non_template_in_template_id_suggest)
710 << Name, false);
712 if (Found)
713 Diag(Found->getLocation(),
714 diag::note_non_template_in_template_id_found);
715 return;
719 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
720 << Name << SourceRange(Less, Greater);
721 if (Found)
722 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
725 /// ActOnDependentIdExpression - Handle a dependent id-expression that
726 /// was just parsed. This is only possible with an explicit scope
727 /// specifier naming a dependent type.
728 ExprResult
729 Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
730 SourceLocation TemplateKWLoc,
731 const DeclarationNameInfo &NameInfo,
732 bool isAddressOfOperand,
733 const TemplateArgumentListInfo *TemplateArgs) {
734 DeclContext *DC = getFunctionLevelDeclContext();
736 // C++11 [expr.prim.general]p12:
737 // An id-expression that denotes a non-static data member or non-static
738 // member function of a class can only be used:
739 // (...)
740 // - if that id-expression denotes a non-static data member and it
741 // appears in an unevaluated operand.
743 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
744 // CXXDependentScopeMemberExpr. The former can instantiate to either
745 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
746 // always a MemberExpr.
747 bool MightBeCxx11UnevalField =
748 getLangOpts().CPlusPlus11 && isUnevaluatedContext();
750 // Check if the nested name specifier is an enum type.
751 bool IsEnum = false;
752 if (NestedNameSpecifier *NNS = SS.getScopeRep())
753 IsEnum = isa_and_nonnull<EnumType>(NNS->getAsType());
755 if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
756 isa<CXXMethodDecl>(DC) &&
757 cast<CXXMethodDecl>(DC)->isImplicitObjectMemberFunction()) {
758 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType().getNonReferenceType();
760 // Since the 'this' expression is synthesized, we don't need to
761 // perform the double-lookup check.
762 NamedDecl *FirstQualifierInScope = nullptr;
764 return CXXDependentScopeMemberExpr::Create(
765 Context, /*This=*/nullptr, ThisType,
766 /*IsArrow=*/!Context.getLangOpts().HLSL,
767 /*Op=*/SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
768 FirstQualifierInScope, NameInfo, TemplateArgs);
771 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
774 ExprResult
775 Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
776 SourceLocation TemplateKWLoc,
777 const DeclarationNameInfo &NameInfo,
778 const TemplateArgumentListInfo *TemplateArgs) {
779 // DependentScopeDeclRefExpr::Create requires a valid QualifierLoc
780 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
781 if (!QualifierLoc)
782 return ExprError();
784 return DependentScopeDeclRefExpr::Create(
785 Context, QualifierLoc, TemplateKWLoc, NameInfo, TemplateArgs);
789 /// Determine whether we would be unable to instantiate this template (because
790 /// it either has no definition, or is in the process of being instantiated).
791 bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
792 NamedDecl *Instantiation,
793 bool InstantiatedFromMember,
794 const NamedDecl *Pattern,
795 const NamedDecl *PatternDef,
796 TemplateSpecializationKind TSK,
797 bool Complain /*= true*/) {
798 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
799 isa<VarDecl>(Instantiation));
801 bool IsEntityBeingDefined = false;
802 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
803 IsEntityBeingDefined = TD->isBeingDefined();
805 if (PatternDef && !IsEntityBeingDefined) {
806 NamedDecl *SuggestedDef = nullptr;
807 if (!hasReachableDefinition(const_cast<NamedDecl *>(PatternDef),
808 &SuggestedDef,
809 /*OnlyNeedComplete*/ false)) {
810 // If we're allowed to diagnose this and recover, do so.
811 bool Recover = Complain && !isSFINAEContext();
812 if (Complain)
813 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
814 Sema::MissingImportKind::Definition, Recover);
815 return !Recover;
817 return false;
820 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
821 return true;
823 std::optional<unsigned> Note;
824 QualType InstantiationTy;
825 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
826 InstantiationTy = Context.getTypeDeclType(TD);
827 if (PatternDef) {
828 Diag(PointOfInstantiation,
829 diag::err_template_instantiate_within_definition)
830 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
831 << InstantiationTy;
832 // Not much point in noting the template declaration here, since
833 // we're lexically inside it.
834 Instantiation->setInvalidDecl();
835 } else if (InstantiatedFromMember) {
836 if (isa<FunctionDecl>(Instantiation)) {
837 Diag(PointOfInstantiation,
838 diag::err_explicit_instantiation_undefined_member)
839 << /*member function*/ 1 << Instantiation->getDeclName()
840 << Instantiation->getDeclContext();
841 Note = diag::note_explicit_instantiation_here;
842 } else {
843 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
844 Diag(PointOfInstantiation,
845 diag::err_implicit_instantiate_member_undefined)
846 << InstantiationTy;
847 Note = diag::note_member_declared_at;
849 } else {
850 if (isa<FunctionDecl>(Instantiation)) {
851 Diag(PointOfInstantiation,
852 diag::err_explicit_instantiation_undefined_func_template)
853 << Pattern;
854 Note = diag::note_explicit_instantiation_here;
855 } else if (isa<TagDecl>(Instantiation)) {
856 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
857 << (TSK != TSK_ImplicitInstantiation)
858 << InstantiationTy;
859 Note = diag::note_template_decl_here;
860 } else {
861 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
862 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
863 Diag(PointOfInstantiation,
864 diag::err_explicit_instantiation_undefined_var_template)
865 << Instantiation;
866 Instantiation->setInvalidDecl();
867 } else
868 Diag(PointOfInstantiation,
869 diag::err_explicit_instantiation_undefined_member)
870 << /*static data member*/ 2 << Instantiation->getDeclName()
871 << Instantiation->getDeclContext();
872 Note = diag::note_explicit_instantiation_here;
875 if (Note) // Diagnostics were emitted.
876 Diag(Pattern->getLocation(), *Note);
878 // In general, Instantiation isn't marked invalid to get more than one
879 // error for multiple undefined instantiations. But the code that does
880 // explicit declaration -> explicit definition conversion can't handle
881 // invalid declarations, so mark as invalid in that case.
882 if (TSK == TSK_ExplicitInstantiationDeclaration)
883 Instantiation->setInvalidDecl();
884 return true;
887 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
888 /// that the template parameter 'PrevDecl' is being shadowed by a new
889 /// declaration at location Loc. Returns true to indicate that this is
890 /// an error, and false otherwise.
891 void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
892 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
894 // C++ [temp.local]p4:
895 // A template-parameter shall not be redeclared within its
896 // scope (including nested scopes).
898 // Make this a warning when MSVC compatibility is requested.
899 unsigned DiagId = getLangOpts().MSVCCompat ? diag::ext_template_param_shadow
900 : diag::err_template_param_shadow;
901 Diag(Loc, DiagId) << cast<NamedDecl>(PrevDecl)->getDeclName();
902 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
905 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
906 /// the parameter D to reference the templated declaration and return a pointer
907 /// to the template declaration. Otherwise, do nothing to D and return null.
908 TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
909 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
910 D = Temp->getTemplatedDecl();
911 return Temp;
913 return nullptr;
916 ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
917 SourceLocation EllipsisLoc) const {
918 assert(Kind == Template &&
919 "Only template template arguments can be pack expansions here");
920 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
921 "Template template argument pack expansion without packs");
922 ParsedTemplateArgument Result(*this);
923 Result.EllipsisLoc = EllipsisLoc;
924 return Result;
927 static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
928 const ParsedTemplateArgument &Arg) {
930 switch (Arg.getKind()) {
931 case ParsedTemplateArgument::Type: {
932 TypeSourceInfo *DI;
933 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
934 if (!DI)
935 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
936 return TemplateArgumentLoc(TemplateArgument(T), DI);
939 case ParsedTemplateArgument::NonType: {
940 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
941 return TemplateArgumentLoc(TemplateArgument(E), E);
944 case ParsedTemplateArgument::Template: {
945 TemplateName Template = Arg.getAsTemplate().get();
946 TemplateArgument TArg;
947 if (Arg.getEllipsisLoc().isValid())
948 TArg = TemplateArgument(Template, std::optional<unsigned int>());
949 else
950 TArg = Template;
951 return TemplateArgumentLoc(
952 SemaRef.Context, TArg,
953 Arg.getScopeSpec().getWithLocInContext(SemaRef.Context),
954 Arg.getLocation(), Arg.getEllipsisLoc());
958 llvm_unreachable("Unhandled parsed template argument");
961 /// Translates template arguments as provided by the parser
962 /// into template arguments used by semantic analysis.
963 void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
964 TemplateArgumentListInfo &TemplateArgs) {
965 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
966 TemplateArgs.addArgument(translateTemplateArgument(*this,
967 TemplateArgsIn[I]));
970 static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
971 SourceLocation Loc,
972 IdentifierInfo *Name) {
973 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
974 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
975 if (PrevDecl && PrevDecl->isTemplateParameter())
976 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
979 /// Convert a parsed type into a parsed template argument. This is mostly
980 /// trivial, except that we may have parsed a C++17 deduced class template
981 /// specialization type, in which case we should form a template template
982 /// argument instead of a type template argument.
983 ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) {
984 TypeSourceInfo *TInfo;
985 QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
986 if (T.isNull())
987 return ParsedTemplateArgument();
988 assert(TInfo && "template argument with no location");
990 // If we might have formed a deduced template specialization type, convert
991 // it to a template template argument.
992 if (getLangOpts().CPlusPlus17) {
993 TypeLoc TL = TInfo->getTypeLoc();
994 SourceLocation EllipsisLoc;
995 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
996 EllipsisLoc = PET.getEllipsisLoc();
997 TL = PET.getPatternLoc();
1000 CXXScopeSpec SS;
1001 if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
1002 SS.Adopt(ET.getQualifierLoc());
1003 TL = ET.getNamedTypeLoc();
1006 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
1007 TemplateName Name = DTST.getTypePtr()->getTemplateName();
1008 if (SS.isSet())
1009 Name = Context.getQualifiedTemplateName(SS.getScopeRep(),
1010 /*HasTemplateKeyword=*/false,
1011 Name);
1012 ParsedTemplateArgument Result(SS, TemplateTy::make(Name),
1013 DTST.getTemplateNameLoc());
1014 if (EllipsisLoc.isValid())
1015 Result = Result.getTemplatePackExpansion(EllipsisLoc);
1016 return Result;
1020 // This is a normal type template argument. Note, if the type template
1021 // argument is an injected-class-name for a template, it has a dual nature
1022 // and can be used as either a type or a template. We handle that in
1023 // convertTypeTemplateArgumentToTemplate.
1024 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1025 ParsedType.get().getAsOpaquePtr(),
1026 TInfo->getTypeLoc().getBeginLoc());
1029 /// ActOnTypeParameter - Called when a C++ template type parameter
1030 /// (e.g., "typename T") has been parsed. Typename specifies whether
1031 /// the keyword "typename" was used to declare the type parameter
1032 /// (otherwise, "class" was used), and KeyLoc is the location of the
1033 /// "class" or "typename" keyword. ParamName is the name of the
1034 /// parameter (NULL indicates an unnamed template parameter) and
1035 /// ParamNameLoc is the location of the parameter name (if any).
1036 /// If the type parameter has a default argument, it will be added
1037 /// later via ActOnTypeParameterDefault.
1038 NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
1039 SourceLocation EllipsisLoc,
1040 SourceLocation KeyLoc,
1041 IdentifierInfo *ParamName,
1042 SourceLocation ParamNameLoc,
1043 unsigned Depth, unsigned Position,
1044 SourceLocation EqualLoc,
1045 ParsedType DefaultArg,
1046 bool HasTypeConstraint) {
1047 assert(S->isTemplateParamScope() &&
1048 "Template type parameter not in template parameter scope!");
1050 bool IsParameterPack = EllipsisLoc.isValid();
1051 TemplateTypeParmDecl *Param
1052 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1053 KeyLoc, ParamNameLoc, Depth, Position,
1054 ParamName, Typename, IsParameterPack,
1055 HasTypeConstraint);
1056 Param->setAccess(AS_public);
1058 if (Param->isParameterPack())
1059 if (auto *LSI = getEnclosingLambda())
1060 LSI->LocalPacks.push_back(Param);
1062 if (ParamName) {
1063 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1065 // Add the template parameter into the current scope.
1066 S->AddDecl(Param);
1067 IdResolver.AddDecl(Param);
1070 // C++0x [temp.param]p9:
1071 // A default template-argument may be specified for any kind of
1072 // template-parameter that is not a template parameter pack.
1073 if (DefaultArg && IsParameterPack) {
1074 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1075 DefaultArg = nullptr;
1078 // Handle the default argument, if provided.
1079 if (DefaultArg) {
1080 TypeSourceInfo *DefaultTInfo;
1081 GetTypeFromParser(DefaultArg, &DefaultTInfo);
1083 assert(DefaultTInfo && "expected source information for type");
1085 // Check for unexpanded parameter packs.
1086 if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
1087 UPPC_DefaultArgument))
1088 return Param;
1090 // Check the template argument itself.
1091 if (CheckTemplateArgument(DefaultTInfo)) {
1092 Param->setInvalidDecl();
1093 return Param;
1096 Param->setDefaultArgument(DefaultTInfo);
1099 return Param;
1102 /// Convert the parser's template argument list representation into our form.
1103 static TemplateArgumentListInfo
1104 makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
1105 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1106 TemplateId.RAngleLoc);
1107 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1108 TemplateId.NumArgs);
1109 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
1110 return TemplateArgs;
1113 bool Sema::CheckTypeConstraint(TemplateIdAnnotation *TypeConstr) {
1115 TemplateName TN = TypeConstr->Template.get();
1116 ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl());
1118 // C++2a [temp.param]p4:
1119 // [...] The concept designated by a type-constraint shall be a type
1120 // concept ([temp.concept]).
1121 if (!CD->isTypeConcept()) {
1122 Diag(TypeConstr->TemplateNameLoc,
1123 diag::err_type_constraint_non_type_concept);
1124 return true;
1127 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1129 if (!WereArgsSpecified &&
1130 CD->getTemplateParameters()->getMinRequiredArguments() > 1) {
1131 Diag(TypeConstr->TemplateNameLoc,
1132 diag::err_type_constraint_missing_arguments)
1133 << CD;
1134 return true;
1136 return false;
1139 bool Sema::ActOnTypeConstraint(const CXXScopeSpec &SS,
1140 TemplateIdAnnotation *TypeConstr,
1141 TemplateTypeParmDecl *ConstrainedParameter,
1142 SourceLocation EllipsisLoc) {
1143 return BuildTypeConstraint(SS, TypeConstr, ConstrainedParameter, EllipsisLoc,
1144 false);
1147 bool Sema::BuildTypeConstraint(const CXXScopeSpec &SS,
1148 TemplateIdAnnotation *TypeConstr,
1149 TemplateTypeParmDecl *ConstrainedParameter,
1150 SourceLocation EllipsisLoc,
1151 bool AllowUnexpandedPack) {
1153 if (CheckTypeConstraint(TypeConstr))
1154 return true;
1156 TemplateName TN = TypeConstr->Template.get();
1157 ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl());
1159 DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1160 TypeConstr->TemplateNameLoc);
1162 TemplateArgumentListInfo TemplateArgs;
1163 if (TypeConstr->LAngleLoc.isValid()) {
1164 TemplateArgs =
1165 makeTemplateArgumentListInfo(*this, *TypeConstr);
1167 if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1168 for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1169 if (DiagnoseUnexpandedParameterPack(Arg, UPPC_TypeConstraint))
1170 return true;
1174 return AttachTypeConstraint(
1175 SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1176 ConceptName, CD,
1177 TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1178 ConstrainedParameter, EllipsisLoc);
1181 template<typename ArgumentLocAppender>
1182 static ExprResult formImmediatelyDeclaredConstraint(
1183 Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo,
1184 ConceptDecl *NamedConcept, SourceLocation LAngleLoc,
1185 SourceLocation RAngleLoc, QualType ConstrainedType,
1186 SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1187 SourceLocation EllipsisLoc) {
1189 TemplateArgumentListInfo ConstraintArgs;
1190 ConstraintArgs.addArgument(
1191 S.getTrivialTemplateArgumentLoc(TemplateArgument(ConstrainedType),
1192 /*NTTPType=*/QualType(), ParamNameLoc));
1194 ConstraintArgs.setRAngleLoc(RAngleLoc);
1195 ConstraintArgs.setLAngleLoc(LAngleLoc);
1196 Appender(ConstraintArgs);
1198 // C++2a [temp.param]p4:
1199 // [...] This constraint-expression E is called the immediately-declared
1200 // constraint of T. [...]
1201 CXXScopeSpec SS;
1202 SS.Adopt(NS);
1203 ExprResult ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1204 SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
1205 /*FoundDecl=*/NamedConcept, NamedConcept, &ConstraintArgs);
1206 if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1207 return ImmediatelyDeclaredConstraint;
1209 // C++2a [temp.param]p4:
1210 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1212 // We have the following case:
1214 // template<typename T> concept C1 = true;
1215 // template<C1... T> struct s1;
1217 // The constraint: (C1<T> && ...)
1219 // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1220 // any unqualified lookups for 'operator&&' here.
1221 return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
1222 /*LParenLoc=*/SourceLocation(),
1223 ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1224 EllipsisLoc, /*RHS=*/nullptr,
1225 /*RParenLoc=*/SourceLocation(),
1226 /*NumExpansions=*/std::nullopt);
1229 /// Attach a type-constraint to a template parameter.
1230 /// \returns true if an error occurred. This can happen if the
1231 /// immediately-declared constraint could not be formed (e.g. incorrect number
1232 /// of arguments for the named concept).
1233 bool Sema::AttachTypeConstraint(NestedNameSpecifierLoc NS,
1234 DeclarationNameInfo NameInfo,
1235 ConceptDecl *NamedConcept,
1236 const TemplateArgumentListInfo *TemplateArgs,
1237 TemplateTypeParmDecl *ConstrainedParameter,
1238 SourceLocation EllipsisLoc) {
1239 // C++2a [temp.param]p4:
1240 // [...] If Q is of the form C<A1, ..., An>, then let E' be
1241 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1242 const ASTTemplateArgumentListInfo *ArgsAsWritten =
1243 TemplateArgs ? ASTTemplateArgumentListInfo::Create(Context,
1244 *TemplateArgs) : nullptr;
1246 QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1248 ExprResult ImmediatelyDeclaredConstraint =
1249 formImmediatelyDeclaredConstraint(
1250 *this, NS, NameInfo, NamedConcept,
1251 TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1252 TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1253 ParamAsArgument, ConstrainedParameter->getLocation(),
1254 [&] (TemplateArgumentListInfo &ConstraintArgs) {
1255 if (TemplateArgs)
1256 for (const auto &ArgLoc : TemplateArgs->arguments())
1257 ConstraintArgs.addArgument(ArgLoc);
1258 }, EllipsisLoc);
1259 if (ImmediatelyDeclaredConstraint.isInvalid())
1260 return true;
1262 auto *CL = ConceptReference::Create(Context, /*NNS=*/NS,
1263 /*TemplateKWLoc=*/SourceLocation{},
1264 /*ConceptNameInfo=*/NameInfo,
1265 /*FoundDecl=*/NamedConcept,
1266 /*NamedConcept=*/NamedConcept,
1267 /*ArgsWritten=*/ArgsAsWritten);
1268 ConstrainedParameter->setTypeConstraint(CL,
1269 ImmediatelyDeclaredConstraint.get());
1270 return false;
1273 bool Sema::AttachTypeConstraint(AutoTypeLoc TL,
1274 NonTypeTemplateParmDecl *NewConstrainedParm,
1275 NonTypeTemplateParmDecl *OrigConstrainedParm,
1276 SourceLocation EllipsisLoc) {
1277 if (NewConstrainedParm->getType() != TL.getType() ||
1278 TL.getAutoKeyword() != AutoTypeKeyword::Auto) {
1279 Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1280 diag::err_unsupported_placeholder_constraint)
1281 << NewConstrainedParm->getTypeSourceInfo()
1282 ->getTypeLoc()
1283 .getSourceRange();
1284 return true;
1286 // FIXME: Concepts: This should be the type of the placeholder, but this is
1287 // unclear in the wording right now.
1288 DeclRefExpr *Ref =
1289 BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(),
1290 VK_PRValue, OrigConstrainedParm->getLocation());
1291 if (!Ref)
1292 return true;
1293 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1294 *this, TL.getNestedNameSpecifierLoc(), TL.getConceptNameInfo(),
1295 TL.getNamedConcept(), TL.getLAngleLoc(), TL.getRAngleLoc(),
1296 BuildDecltypeType(Ref), OrigConstrainedParm->getLocation(),
1297 [&](TemplateArgumentListInfo &ConstraintArgs) {
1298 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1299 ConstraintArgs.addArgument(TL.getArgLoc(I));
1301 EllipsisLoc);
1302 if (ImmediatelyDeclaredConstraint.isInvalid() ||
1303 !ImmediatelyDeclaredConstraint.isUsable())
1304 return true;
1306 NewConstrainedParm->setPlaceholderTypeConstraint(
1307 ImmediatelyDeclaredConstraint.get());
1308 return false;
1311 /// Check that the type of a non-type template parameter is
1312 /// well-formed.
1314 /// \returns the (possibly-promoted) parameter type if valid;
1315 /// otherwise, produces a diagnostic and returns a NULL type.
1316 QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
1317 SourceLocation Loc) {
1318 if (TSI->getType()->isUndeducedType()) {
1319 // C++17 [temp.dep.expr]p3:
1320 // An id-expression is type-dependent if it contains
1321 // - an identifier associated by name lookup with a non-type
1322 // template-parameter declared with a type that contains a
1323 // placeholder type (7.1.7.4),
1324 TSI = SubstAutoTypeSourceInfoDependent(TSI);
1327 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
1330 /// Require the given type to be a structural type, and diagnose if it is not.
1332 /// \return \c true if an error was produced.
1333 bool Sema::RequireStructuralType(QualType T, SourceLocation Loc) {
1334 if (T->isDependentType())
1335 return false;
1337 if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))
1338 return true;
1340 if (T->isStructuralType())
1341 return false;
1343 // Structural types are required to be object types or lvalue references.
1344 if (T->isRValueReferenceType()) {
1345 Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;
1346 return true;
1349 // Don't mention structural types in our diagnostic prior to C++20. Also,
1350 // there's not much more we can say about non-scalar non-class types --
1351 // because we can't see functions or arrays here, those can only be language
1352 // extensions.
1353 if (!getLangOpts().CPlusPlus20 ||
1354 (!T->isScalarType() && !T->isRecordType())) {
1355 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1356 return true;
1359 // Structural types are required to be literal types.
1360 if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))
1361 return true;
1363 Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;
1365 // Drill down into the reason why the class is non-structural.
1366 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1367 // All members are required to be public and non-mutable, and can't be of
1368 // rvalue reference type. Check these conditions first to prefer a "local"
1369 // reason over a more distant one.
1370 for (const FieldDecl *FD : RD->fields()) {
1371 if (FD->getAccess() != AS_public) {
1372 Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;
1373 return true;
1375 if (FD->isMutable()) {
1376 Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;
1377 return true;
1379 if (FD->getType()->isRValueReferenceType()) {
1380 Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)
1381 << T;
1382 return true;
1386 // All bases are required to be public.
1387 for (const auto &BaseSpec : RD->bases()) {
1388 if (BaseSpec.getAccessSpecifier() != AS_public) {
1389 Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)
1390 << T << 1;
1391 return true;
1395 // All subobjects are required to be of structural types.
1396 SourceLocation SubLoc;
1397 QualType SubType;
1398 int Kind = -1;
1400 for (const FieldDecl *FD : RD->fields()) {
1401 QualType T = Context.getBaseElementType(FD->getType());
1402 if (!T->isStructuralType()) {
1403 SubLoc = FD->getLocation();
1404 SubType = T;
1405 Kind = 0;
1406 break;
1410 if (Kind == -1) {
1411 for (const auto &BaseSpec : RD->bases()) {
1412 QualType T = BaseSpec.getType();
1413 if (!T->isStructuralType()) {
1414 SubLoc = BaseSpec.getBaseTypeLoc();
1415 SubType = T;
1416 Kind = 1;
1417 break;
1422 assert(Kind != -1 && "couldn't find reason why type is not structural");
1423 Diag(SubLoc, diag::note_not_structural_subobject)
1424 << T << Kind << SubType;
1425 T = SubType;
1426 RD = T->getAsCXXRecordDecl();
1429 return true;
1432 QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
1433 SourceLocation Loc) {
1434 // We don't allow variably-modified types as the type of non-type template
1435 // parameters.
1436 if (T->isVariablyModifiedType()) {
1437 Diag(Loc, diag::err_variably_modified_nontype_template_param)
1438 << T;
1439 return QualType();
1442 // C++ [temp.param]p4:
1444 // A non-type template-parameter shall have one of the following
1445 // (optionally cv-qualified) types:
1447 // -- integral or enumeration type,
1448 if (T->isIntegralOrEnumerationType() ||
1449 // -- pointer to object or pointer to function,
1450 T->isPointerType() ||
1451 // -- lvalue reference to object or lvalue reference to function,
1452 T->isLValueReferenceType() ||
1453 // -- pointer to member,
1454 T->isMemberPointerType() ||
1455 // -- std::nullptr_t, or
1456 T->isNullPtrType() ||
1457 // -- a type that contains a placeholder type.
1458 T->isUndeducedType()) {
1459 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1460 // are ignored when determining its type.
1461 return T.getUnqualifiedType();
1464 // C++ [temp.param]p8:
1466 // A non-type template-parameter of type "array of T" or
1467 // "function returning T" is adjusted to be of type "pointer to
1468 // T" or "pointer to function returning T", respectively.
1469 if (T->isArrayType() || T->isFunctionType())
1470 return Context.getDecayedType(T);
1472 // If T is a dependent type, we can't do the check now, so we
1473 // assume that it is well-formed. Note that stripping off the
1474 // qualifiers here is not really correct if T turns out to be
1475 // an array type, but we'll recompute the type everywhere it's
1476 // used during instantiation, so that should be OK. (Using the
1477 // qualified type is equally wrong.)
1478 if (T->isDependentType())
1479 return T.getUnqualifiedType();
1481 // C++20 [temp.param]p6:
1482 // -- a structural type
1483 if (RequireStructuralType(T, Loc))
1484 return QualType();
1486 if (!getLangOpts().CPlusPlus20) {
1487 // FIXME: Consider allowing structural types as an extension in C++17. (In
1488 // earlier language modes, the template argument evaluation rules are too
1489 // inflexible.)
1490 Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;
1491 return QualType();
1494 Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1495 return T.getUnqualifiedType();
1498 NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
1499 unsigned Depth,
1500 unsigned Position,
1501 SourceLocation EqualLoc,
1502 Expr *Default) {
1503 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
1505 // Check that we have valid decl-specifiers specified.
1506 auto CheckValidDeclSpecifiers = [this, &D] {
1507 // C++ [temp.param]
1508 // p1
1509 // template-parameter:
1510 // ...
1511 // parameter-declaration
1512 // p2
1513 // ... A storage class shall not be specified in a template-parameter
1514 // declaration.
1515 // [dcl.typedef]p1:
1516 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1517 // of a parameter-declaration
1518 const DeclSpec &DS = D.getDeclSpec();
1519 auto EmitDiag = [this](SourceLocation Loc) {
1520 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1521 << FixItHint::CreateRemoval(Loc);
1523 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
1524 EmitDiag(DS.getStorageClassSpecLoc());
1526 if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
1527 EmitDiag(DS.getThreadStorageClassSpecLoc());
1529 // [dcl.inline]p1:
1530 // The inline specifier can be applied only to the declaration or
1531 // definition of a variable or function.
1533 if (DS.isInlineSpecified())
1534 EmitDiag(DS.getInlineSpecLoc());
1536 // [dcl.constexpr]p1:
1537 // The constexpr specifier shall be applied only to the definition of a
1538 // variable or variable template or the declaration of a function or
1539 // function template.
1541 if (DS.hasConstexprSpecifier())
1542 EmitDiag(DS.getConstexprSpecLoc());
1544 // [dcl.fct.spec]p1:
1545 // Function-specifiers can be used only in function declarations.
1547 if (DS.isVirtualSpecified())
1548 EmitDiag(DS.getVirtualSpecLoc());
1550 if (DS.hasExplicitSpecifier())
1551 EmitDiag(DS.getExplicitSpecLoc());
1553 if (DS.isNoreturnSpecified())
1554 EmitDiag(DS.getNoreturnSpecLoc());
1557 CheckValidDeclSpecifiers();
1559 if (const auto *T = TInfo->getType()->getContainedDeducedType())
1560 if (isa<AutoType>(T))
1561 Diag(D.getIdentifierLoc(),
1562 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1563 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1565 assert(S->isTemplateParamScope() &&
1566 "Non-type template parameter not in template parameter scope!");
1567 bool Invalid = false;
1569 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
1570 if (T.isNull()) {
1571 T = Context.IntTy; // Recover with an 'int' type.
1572 Invalid = true;
1575 CheckFunctionOrTemplateParamDeclarator(S, D);
1577 IdentifierInfo *ParamName = D.getIdentifier();
1578 bool IsParameterPack = D.hasEllipsis();
1579 NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create(
1580 Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1581 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1582 TInfo);
1583 Param->setAccess(AS_public);
1585 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc())
1586 if (TL.isConstrained())
1587 if (AttachTypeConstraint(TL, Param, Param, D.getEllipsisLoc()))
1588 Invalid = true;
1590 if (Invalid)
1591 Param->setInvalidDecl();
1593 if (Param->isParameterPack())
1594 if (auto *LSI = getEnclosingLambda())
1595 LSI->LocalPacks.push_back(Param);
1597 if (ParamName) {
1598 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
1599 ParamName);
1601 // Add the template parameter into the current scope.
1602 S->AddDecl(Param);
1603 IdResolver.AddDecl(Param);
1606 // C++0x [temp.param]p9:
1607 // A default template-argument may be specified for any kind of
1608 // template-parameter that is not a template parameter pack.
1609 if (Default && IsParameterPack) {
1610 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1611 Default = nullptr;
1614 // Check the well-formedness of the default template argument, if provided.
1615 if (Default) {
1616 // Check for unexpanded parameter packs.
1617 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
1618 return Param;
1620 Param->setDefaultArgument(Default);
1623 return Param;
1626 /// ActOnTemplateTemplateParameter - Called when a C++ template template
1627 /// parameter (e.g. T in template <template \<typename> class T> class array)
1628 /// has been parsed. S is the current scope.
1629 NamedDecl *Sema::ActOnTemplateTemplateParameter(Scope* S,
1630 SourceLocation TmpLoc,
1631 TemplateParameterList *Params,
1632 SourceLocation EllipsisLoc,
1633 IdentifierInfo *Name,
1634 SourceLocation NameLoc,
1635 unsigned Depth,
1636 unsigned Position,
1637 SourceLocation EqualLoc,
1638 ParsedTemplateArgument Default) {
1639 assert(S->isTemplateParamScope() &&
1640 "Template template parameter not in template parameter scope!");
1642 // Construct the parameter object.
1643 bool IsParameterPack = EllipsisLoc.isValid();
1644 TemplateTemplateParmDecl *Param =
1645 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1646 NameLoc.isInvalid()? TmpLoc : NameLoc,
1647 Depth, Position, IsParameterPack,
1648 Name, Params);
1649 Param->setAccess(AS_public);
1651 if (Param->isParameterPack())
1652 if (auto *LSI = getEnclosingLambda())
1653 LSI->LocalPacks.push_back(Param);
1655 // If the template template parameter has a name, then link the identifier
1656 // into the scope and lookup mechanisms.
1657 if (Name) {
1658 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1660 S->AddDecl(Param);
1661 IdResolver.AddDecl(Param);
1664 if (Params->size() == 0) {
1665 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1666 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1667 Param->setInvalidDecl();
1670 // C++0x [temp.param]p9:
1671 // A default template-argument may be specified for any kind of
1672 // template-parameter that is not a template parameter pack.
1673 if (IsParameterPack && !Default.isInvalid()) {
1674 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1675 Default = ParsedTemplateArgument();
1678 if (!Default.isInvalid()) {
1679 // Check only that we have a template template argument. We don't want to
1680 // try to check well-formedness now, because our template template parameter
1681 // might have dependent types in its template parameters, which we wouldn't
1682 // be able to match now.
1684 // If none of the template template parameter's template arguments mention
1685 // other template parameters, we could actually perform more checking here.
1686 // However, it isn't worth doing.
1687 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
1688 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1689 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1690 << DefaultArg.getSourceRange();
1691 return Param;
1694 // Check for unexpanded parameter packs.
1695 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
1696 DefaultArg.getArgument().getAsTemplate(),
1697 UPPC_DefaultArgument))
1698 return Param;
1700 Param->setDefaultArgument(Context, DefaultArg);
1703 return Param;
1706 namespace {
1707 class ConstraintRefersToContainingTemplateChecker
1708 : public TreeTransform<ConstraintRefersToContainingTemplateChecker> {
1709 bool Result = false;
1710 const FunctionDecl *Friend = nullptr;
1711 unsigned TemplateDepth = 0;
1713 // Check a record-decl that we've seen to see if it is a lexical parent of the
1714 // Friend, likely because it was referred to without its template arguments.
1715 void CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1716 CheckingRD = CheckingRD->getMostRecentDecl();
1718 for (const DeclContext *DC = Friend->getLexicalDeclContext();
1719 DC && !DC->isFileContext(); DC = DC->getParent())
1720 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
1721 if (CheckingRD == RD->getMostRecentDecl())
1722 Result = true;
1725 void CheckNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
1726 assert(D->getDepth() <= TemplateDepth &&
1727 "Nothing should reference a value below the actual template depth, "
1728 "depth is likely wrong");
1729 if (D->getDepth() != TemplateDepth)
1730 Result = true;
1732 // Necessary because the type of the NTTP might be what refers to the parent
1733 // constriant.
1734 TransformType(D->getType());
1737 public:
1738 using inherited = TreeTransform<ConstraintRefersToContainingTemplateChecker>;
1740 ConstraintRefersToContainingTemplateChecker(Sema &SemaRef,
1741 const FunctionDecl *Friend,
1742 unsigned TemplateDepth)
1743 : inherited(SemaRef), Friend(Friend), TemplateDepth(TemplateDepth) {}
1744 bool getResult() const { return Result; }
1746 // This should be the only template parm type that we have to deal with.
1747 // SubstTempalteTypeParmPack, SubstNonTypeTemplateParmPack, and
1748 // FunctionParmPackExpr are all partially substituted, which cannot happen
1749 // with concepts at this point in translation.
1750 using inherited::TransformTemplateTypeParmType;
1751 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1752 TemplateTypeParmTypeLoc TL, bool) {
1753 assert(TL.getDecl()->getDepth() <= TemplateDepth &&
1754 "Nothing should reference a value below the actual template depth, "
1755 "depth is likely wrong");
1756 if (TL.getDecl()->getDepth() != TemplateDepth)
1757 Result = true;
1758 return inherited::TransformTemplateTypeParmType(
1759 TLB, TL,
1760 /*SuppressObjCLifetime=*/false);
1763 Decl *TransformDecl(SourceLocation Loc, Decl *D) {
1764 if (!D)
1765 return D;
1766 // FIXME : This is possibly an incomplete list, but it is unclear what other
1767 // Decl kinds could be used to refer to the template parameters. This is a
1768 // best guess so far based on examples currently available, but the
1769 // unreachable should catch future instances/cases.
1770 if (auto *TD = dyn_cast<TypedefNameDecl>(D))
1771 TransformType(TD->getUnderlyingType());
1772 else if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(D))
1773 CheckNonTypeTemplateParmDecl(NTTPD);
1774 else if (auto *VD = dyn_cast<ValueDecl>(D))
1775 TransformType(VD->getType());
1776 else if (auto *TD = dyn_cast<TemplateDecl>(D))
1777 TransformTemplateParameterList(TD->getTemplateParameters());
1778 else if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1779 CheckIfContainingRecord(RD);
1780 else if (isa<NamedDecl>(D)) {
1781 // No direct types to visit here I believe.
1782 } else
1783 llvm_unreachable("Don't know how to handle this declaration type yet");
1784 return D;
1787 } // namespace
1789 bool Sema::ConstraintExpressionDependsOnEnclosingTemplate(
1790 const FunctionDecl *Friend, unsigned TemplateDepth,
1791 const Expr *Constraint) {
1792 assert(Friend->getFriendObjectKind() && "Only works on a friend");
1793 ConstraintRefersToContainingTemplateChecker Checker(*this, Friend,
1794 TemplateDepth);
1795 Checker.TransformExpr(const_cast<Expr *>(Constraint));
1796 return Checker.getResult();
1799 /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
1800 /// constrained by RequiresClause, that contains the template parameters in
1801 /// Params.
1802 TemplateParameterList *
1803 Sema::ActOnTemplateParameterList(unsigned Depth,
1804 SourceLocation ExportLoc,
1805 SourceLocation TemplateLoc,
1806 SourceLocation LAngleLoc,
1807 ArrayRef<NamedDecl *> Params,
1808 SourceLocation RAngleLoc,
1809 Expr *RequiresClause) {
1810 if (ExportLoc.isValid())
1811 Diag(ExportLoc, diag::warn_template_export_unsupported);
1813 for (NamedDecl *P : Params)
1814 warnOnReservedIdentifier(P);
1816 return TemplateParameterList::Create(
1817 Context, TemplateLoc, LAngleLoc,
1818 llvm::ArrayRef(Params.data(), Params.size()), RAngleLoc, RequiresClause);
1821 static void SetNestedNameSpecifier(Sema &S, TagDecl *T,
1822 const CXXScopeSpec &SS) {
1823 if (SS.isSet())
1824 T->setQualifierInfo(SS.getWithLocInContext(S.Context));
1827 DeclResult Sema::CheckClassTemplate(
1828 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1829 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1830 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1831 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1832 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1833 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1834 assert(TemplateParams && TemplateParams->size() > 0 &&
1835 "No template parameters");
1836 assert(TUK != TUK_Reference && "Can only declare or define class templates");
1837 bool Invalid = false;
1839 // Check that we can declare a template here.
1840 if (CheckTemplateDeclScope(S, TemplateParams))
1841 return true;
1843 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1844 assert(Kind != TagTypeKind::Enum &&
1845 "can't build template of enumerated type");
1847 // There is no such thing as an unnamed class template.
1848 if (!Name) {
1849 Diag(KWLoc, diag::err_template_unnamed_class);
1850 return true;
1853 // Find any previous declaration with this name. For a friend with no
1854 // scope explicitly specified, we only look for tag declarations (per
1855 // C++11 [basic.lookup.elab]p2).
1856 DeclContext *SemanticContext;
1857 LookupResult Previous(*this, Name, NameLoc,
1858 (SS.isEmpty() && TUK == TUK_Friend)
1859 ? LookupTagName : LookupOrdinaryName,
1860 forRedeclarationInCurContext());
1861 if (SS.isNotEmpty() && !SS.isInvalid()) {
1862 SemanticContext = computeDeclContext(SS, true);
1863 if (!SemanticContext) {
1864 // FIXME: Horrible, horrible hack! We can't currently represent this
1865 // in the AST, and historically we have just ignored such friend
1866 // class templates, so don't complain here.
1867 Diag(NameLoc, TUK == TUK_Friend
1868 ? diag::warn_template_qualified_friend_ignored
1869 : diag::err_template_qualified_declarator_no_match)
1870 << SS.getScopeRep() << SS.getRange();
1871 return TUK != TUK_Friend;
1874 if (RequireCompleteDeclContext(SS, SemanticContext))
1875 return true;
1877 // If we're adding a template to a dependent context, we may need to
1878 // rebuilding some of the types used within the template parameter list,
1879 // now that we know what the current instantiation is.
1880 if (SemanticContext->isDependentContext()) {
1881 ContextRAII SavedContext(*this, SemanticContext);
1882 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1883 Invalid = true;
1884 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
1885 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc, false);
1887 LookupQualifiedName(Previous, SemanticContext);
1888 } else {
1889 SemanticContext = CurContext;
1891 // C++14 [class.mem]p14:
1892 // If T is the name of a class, then each of the following shall have a
1893 // name different from T:
1894 // -- every member template of class T
1895 if (TUK != TUK_Friend &&
1896 DiagnoseClassNameShadow(SemanticContext,
1897 DeclarationNameInfo(Name, NameLoc)))
1898 return true;
1900 LookupName(Previous, S);
1903 if (Previous.isAmbiguous())
1904 return true;
1906 NamedDecl *PrevDecl = nullptr;
1907 if (Previous.begin() != Previous.end())
1908 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1910 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1911 // Maybe we will complain about the shadowed template parameter.
1912 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1913 // Just pretend that we didn't see the previous declaration.
1914 PrevDecl = nullptr;
1917 // If there is a previous declaration with the same name, check
1918 // whether this is a valid redeclaration.
1919 ClassTemplateDecl *PrevClassTemplate =
1920 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1922 // We may have found the injected-class-name of a class template,
1923 // class template partial specialization, or class template specialization.
1924 // In these cases, grab the template that is being defined or specialized.
1925 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
1926 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1927 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1928 PrevClassTemplate
1929 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1930 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1931 PrevClassTemplate
1932 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1933 ->getSpecializedTemplate();
1937 if (TUK == TUK_Friend) {
1938 // C++ [namespace.memdef]p3:
1939 // [...] When looking for a prior declaration of a class or a function
1940 // declared as a friend, and when the name of the friend class or
1941 // function is neither a qualified name nor a template-id, scopes outside
1942 // the innermost enclosing namespace scope are not considered.
1943 if (!SS.isSet()) {
1944 DeclContext *OutermostContext = CurContext;
1945 while (!OutermostContext->isFileContext())
1946 OutermostContext = OutermostContext->getLookupParent();
1948 if (PrevDecl &&
1949 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1950 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1951 SemanticContext = PrevDecl->getDeclContext();
1952 } else {
1953 // Declarations in outer scopes don't matter. However, the outermost
1954 // context we computed is the semantic context for our new
1955 // declaration.
1956 PrevDecl = PrevClassTemplate = nullptr;
1957 SemanticContext = OutermostContext;
1959 // Check that the chosen semantic context doesn't already contain a
1960 // declaration of this name as a non-tag type.
1961 Previous.clear(LookupOrdinaryName);
1962 DeclContext *LookupContext = SemanticContext;
1963 while (LookupContext->isTransparentContext())
1964 LookupContext = LookupContext->getLookupParent();
1965 LookupQualifiedName(Previous, LookupContext);
1967 if (Previous.isAmbiguous())
1968 return true;
1970 if (Previous.begin() != Previous.end())
1971 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1974 } else if (PrevDecl &&
1975 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1976 S, SS.isValid()))
1977 PrevDecl = PrevClassTemplate = nullptr;
1979 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1980 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1981 if (SS.isEmpty() &&
1982 !(PrevClassTemplate &&
1983 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1984 SemanticContext->getRedeclContext()))) {
1985 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1986 Diag(Shadow->getTargetDecl()->getLocation(),
1987 diag::note_using_decl_target);
1988 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
1989 // Recover by ignoring the old declaration.
1990 PrevDecl = PrevClassTemplate = nullptr;
1994 if (PrevClassTemplate) {
1995 // Ensure that the template parameter lists are compatible. Skip this check
1996 // for a friend in a dependent context: the template parameter list itself
1997 // could be dependent.
1998 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1999 !TemplateParameterListsAreEqual(
2000 TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
2001 : CurContext,
2002 CurContext, KWLoc),
2003 TemplateParams, PrevClassTemplate,
2004 PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
2005 TPL_TemplateMatch))
2006 return true;
2008 // C++ [temp.class]p4:
2009 // In a redeclaration, partial specialization, explicit
2010 // specialization or explicit instantiation of a class template,
2011 // the class-key shall agree in kind with the original class
2012 // template declaration (7.1.5.3).
2013 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
2014 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
2015 TUK == TUK_Definition, KWLoc, Name)) {
2016 Diag(KWLoc, diag::err_use_with_wrong_tag)
2017 << Name
2018 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
2019 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
2020 Kind = PrevRecordDecl->getTagKind();
2023 // Check for redefinition of this class template.
2024 if (TUK == TUK_Definition) {
2025 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2026 // If we have a prior definition that is not visible, treat this as
2027 // simply making that previous definition visible.
2028 NamedDecl *Hidden = nullptr;
2029 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
2030 SkipBody->ShouldSkip = true;
2031 SkipBody->Previous = Def;
2032 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
2033 assert(Tmpl && "original definition of a class template is not a "
2034 "class template?");
2035 makeMergedDefinitionVisible(Hidden);
2036 makeMergedDefinitionVisible(Tmpl);
2037 } else {
2038 Diag(NameLoc, diag::err_redefinition) << Name;
2039 Diag(Def->getLocation(), diag::note_previous_definition);
2040 // FIXME: Would it make sense to try to "forget" the previous
2041 // definition, as part of error recovery?
2042 return true;
2046 } else if (PrevDecl) {
2047 // C++ [temp]p5:
2048 // A class template shall not have the same name as any other
2049 // template, class, function, object, enumeration, enumerator,
2050 // namespace, or type in the same scope (3.3), except as specified
2051 // in (14.5.4).
2052 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2053 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2054 return true;
2057 // Check the template parameter list of this declaration, possibly
2058 // merging in the template parameter list from the previous class
2059 // template declaration. Skip this check for a friend in a dependent
2060 // context, because the template parameter list might be dependent.
2061 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
2062 CheckTemplateParameterList(
2063 TemplateParams,
2064 PrevClassTemplate
2065 ? PrevClassTemplate->getMostRecentDecl()->getTemplateParameters()
2066 : nullptr,
2067 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2068 SemanticContext->isDependentContext())
2069 ? TPC_ClassTemplateMember
2070 : TUK == TUK_Friend ? TPC_FriendClassTemplate : TPC_ClassTemplate,
2071 SkipBody))
2072 Invalid = true;
2074 if (SS.isSet()) {
2075 // If the name of the template was qualified, we must be defining the
2076 // template out-of-line.
2077 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
2078 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
2079 : diag::err_member_decl_does_not_match)
2080 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
2081 Invalid = true;
2085 // If this is a templated friend in a dependent context we should not put it
2086 // on the redecl chain. In some cases, the templated friend can be the most
2087 // recent declaration tricking the template instantiator to make substitutions
2088 // there.
2089 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2090 bool ShouldAddRedecl
2091 = !(TUK == TUK_Friend && CurContext->isDependentContext());
2093 CXXRecordDecl *NewClass =
2094 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
2095 PrevClassTemplate && ShouldAddRedecl ?
2096 PrevClassTemplate->getTemplatedDecl() : nullptr,
2097 /*DelayTypeCreation=*/true);
2098 SetNestedNameSpecifier(*this, NewClass, SS);
2099 if (NumOuterTemplateParamLists > 0)
2100 NewClass->setTemplateParameterListsInfo(
2101 Context,
2102 llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2104 // Add alignment attributes if necessary; these attributes are checked when
2105 // the ASTContext lays out the structure.
2106 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2107 AddAlignmentAttributesForRecord(NewClass);
2108 AddMsStructLayoutForRecord(NewClass);
2111 ClassTemplateDecl *NewTemplate
2112 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
2113 DeclarationName(Name), TemplateParams,
2114 NewClass);
2116 if (ShouldAddRedecl)
2117 NewTemplate->setPreviousDecl(PrevClassTemplate);
2119 NewClass->setDescribedClassTemplate(NewTemplate);
2121 if (ModulePrivateLoc.isValid())
2122 NewTemplate->setModulePrivate();
2124 // Build the type for the class template declaration now.
2125 QualType T = NewTemplate->getInjectedClassNameSpecialization();
2126 T = Context.getInjectedClassNameType(NewClass, T);
2127 assert(T->isDependentType() && "Class template type is not dependent?");
2128 (void)T;
2130 // If we are providing an explicit specialization of a member that is a
2131 // class template, make a note of that.
2132 if (PrevClassTemplate &&
2133 PrevClassTemplate->getInstantiatedFromMemberTemplate())
2134 PrevClassTemplate->setMemberSpecialization();
2136 // Set the access specifier.
2137 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
2138 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
2140 // Set the lexical context of these templates
2141 NewClass->setLexicalDeclContext(CurContext);
2142 NewTemplate->setLexicalDeclContext(CurContext);
2144 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
2145 NewClass->startDefinition();
2147 ProcessDeclAttributeList(S, NewClass, Attr);
2149 if (PrevClassTemplate)
2150 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2152 AddPushedVisibilityAttribute(NewClass);
2153 inferGslOwnerPointerAttribute(NewClass);
2155 if (TUK != TUK_Friend) {
2156 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2157 Scope *Outer = S;
2158 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2159 Outer = Outer->getParent();
2160 PushOnScopeChains(NewTemplate, Outer);
2161 } else {
2162 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2163 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2164 NewClass->setAccess(PrevClassTemplate->getAccess());
2167 NewTemplate->setObjectOfFriendDecl();
2169 // Friend templates are visible in fairly strange ways.
2170 if (!CurContext->isDependentContext()) {
2171 DeclContext *DC = SemanticContext->getRedeclContext();
2172 DC->makeDeclVisibleInContext(NewTemplate);
2173 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2174 PushOnScopeChains(NewTemplate, EnclosingScope,
2175 /* AddToContext = */ false);
2178 FriendDecl *Friend = FriendDecl::Create(
2179 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
2180 Friend->setAccess(AS_public);
2181 CurContext->addDecl(Friend);
2184 if (PrevClassTemplate)
2185 CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);
2187 if (Invalid) {
2188 NewTemplate->setInvalidDecl();
2189 NewClass->setInvalidDecl();
2192 ActOnDocumentableDecl(NewTemplate);
2194 if (SkipBody && SkipBody->ShouldSkip)
2195 return SkipBody->Previous;
2197 return NewTemplate;
2200 namespace {
2201 /// Tree transform to "extract" a transformed type from a class template's
2202 /// constructor to a deduction guide.
2203 class ExtractTypeForDeductionGuide
2204 : public TreeTransform<ExtractTypeForDeductionGuide> {
2205 llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs;
2207 public:
2208 typedef TreeTransform<ExtractTypeForDeductionGuide> Base;
2209 ExtractTypeForDeductionGuide(
2210 Sema &SemaRef,
2211 llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs)
2212 : Base(SemaRef), MaterializedTypedefs(MaterializedTypedefs) {}
2214 TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); }
2216 QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) {
2217 ASTContext &Context = SemaRef.getASTContext();
2218 TypedefNameDecl *OrigDecl = TL.getTypedefNameDecl();
2219 TypedefNameDecl *Decl = OrigDecl;
2220 // Transform the underlying type of the typedef and clone the Decl only if
2221 // the typedef has a dependent context.
2222 if (OrigDecl->getDeclContext()->isDependentContext()) {
2223 TypeLocBuilder InnerTLB;
2224 QualType Transformed =
2225 TransformType(InnerTLB, OrigDecl->getTypeSourceInfo()->getTypeLoc());
2226 TypeSourceInfo *TSI = InnerTLB.getTypeSourceInfo(Context, Transformed);
2227 if (isa<TypeAliasDecl>(OrigDecl))
2228 Decl = TypeAliasDecl::Create(
2229 Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(),
2230 OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI);
2231 else {
2232 assert(isa<TypedefDecl>(OrigDecl) && "Not a Type alias or typedef");
2233 Decl = TypedefDecl::Create(
2234 Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(),
2235 OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI);
2237 MaterializedTypedefs.push_back(Decl);
2240 QualType TDTy = Context.getTypedefType(Decl);
2241 TypedefTypeLoc TypedefTL = TLB.push<TypedefTypeLoc>(TDTy);
2242 TypedefTL.setNameLoc(TL.getNameLoc());
2244 return TDTy;
2248 /// Transform to convert portions of a constructor declaration into the
2249 /// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
2250 struct ConvertConstructorToDeductionGuideTransform {
2251 ConvertConstructorToDeductionGuideTransform(Sema &S,
2252 ClassTemplateDecl *Template)
2253 : SemaRef(S), Template(Template) {}
2255 Sema &SemaRef;
2256 ClassTemplateDecl *Template;
2258 DeclContext *DC = Template->getDeclContext();
2259 CXXRecordDecl *Primary = Template->getTemplatedDecl();
2260 DeclarationName DeductionGuideName =
2261 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template);
2263 QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
2265 // Index adjustment to apply to convert depth-1 template parameters into
2266 // depth-0 template parameters.
2267 unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
2269 /// Transform a constructor declaration into a deduction guide.
2270 NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
2271 CXXConstructorDecl *CD) {
2272 SmallVector<TemplateArgument, 16> SubstArgs;
2274 LocalInstantiationScope Scope(SemaRef);
2276 // C++ [over.match.class.deduct]p1:
2277 // -- For each constructor of the class template designated by the
2278 // template-name, a function template with the following properties:
2280 // -- The template parameters are the template parameters of the class
2281 // template followed by the template parameters (including default
2282 // template arguments) of the constructor, if any.
2283 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2284 if (FTD) {
2285 TemplateParameterList *InnerParams = FTD->getTemplateParameters();
2286 SmallVector<NamedDecl *, 16> AllParams;
2287 AllParams.reserve(TemplateParams->size() + InnerParams->size());
2288 AllParams.insert(AllParams.begin(),
2289 TemplateParams->begin(), TemplateParams->end());
2290 SubstArgs.reserve(InnerParams->size());
2292 // Later template parameters could refer to earlier ones, so build up
2293 // a list of substituted template arguments as we go.
2294 for (NamedDecl *Param : *InnerParams) {
2295 MultiLevelTemplateArgumentList Args;
2296 Args.setKind(TemplateSubstitutionKind::Rewrite);
2297 Args.addOuterTemplateArguments(SubstArgs);
2298 Args.addOuterRetainedLevel();
2299 NamedDecl *NewParam = transformTemplateParameter(Param, Args);
2300 if (!NewParam)
2301 return nullptr;
2302 AllParams.push_back(NewParam);
2303 SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
2304 SemaRef.Context.getInjectedTemplateArg(NewParam)));
2307 // Substitute new template parameters into requires-clause if present.
2308 Expr *RequiresClause = nullptr;
2309 if (Expr *InnerRC = InnerParams->getRequiresClause()) {
2310 MultiLevelTemplateArgumentList Args;
2311 Args.setKind(TemplateSubstitutionKind::Rewrite);
2312 Args.addOuterTemplateArguments(SubstArgs);
2313 Args.addOuterRetainedLevel();
2314 ExprResult E = SemaRef.SubstExpr(InnerRC, Args);
2315 if (E.isInvalid())
2316 return nullptr;
2317 RequiresClause = E.getAs<Expr>();
2320 TemplateParams = TemplateParameterList::Create(
2321 SemaRef.Context, InnerParams->getTemplateLoc(),
2322 InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
2323 RequiresClause);
2326 // If we built a new template-parameter-list, track that we need to
2327 // substitute references to the old parameters into references to the
2328 // new ones.
2329 MultiLevelTemplateArgumentList Args;
2330 Args.setKind(TemplateSubstitutionKind::Rewrite);
2331 if (FTD) {
2332 Args.addOuterTemplateArguments(SubstArgs);
2333 Args.addOuterRetainedLevel();
2336 FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc()
2337 .getAsAdjusted<FunctionProtoTypeLoc>();
2338 assert(FPTL && "no prototype for constructor declaration");
2340 // Transform the type of the function, adjusting the return type and
2341 // replacing references to the old parameters with references to the
2342 // new ones.
2343 TypeLocBuilder TLB;
2344 SmallVector<ParmVarDecl*, 8> Params;
2345 SmallVector<TypedefNameDecl *, 4> MaterializedTypedefs;
2346 QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args,
2347 MaterializedTypedefs);
2348 if (NewType.isNull())
2349 return nullptr;
2350 TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
2352 return buildDeductionGuide(TemplateParams, CD, CD->getExplicitSpecifier(),
2353 NewTInfo, CD->getBeginLoc(), CD->getLocation(),
2354 CD->getEndLoc(), MaterializedTypedefs);
2357 /// Build a deduction guide with the specified parameter types.
2358 NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
2359 SourceLocation Loc = Template->getLocation();
2361 // Build the requested type.
2362 FunctionProtoType::ExtProtoInfo EPI;
2363 EPI.HasTrailingReturn = true;
2364 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
2365 DeductionGuideName, EPI);
2366 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
2368 FunctionProtoTypeLoc FPTL =
2369 TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
2371 // Build the parameters, needed during deduction / substitution.
2372 SmallVector<ParmVarDecl*, 4> Params;
2373 for (auto T : ParamTypes) {
2374 ParmVarDecl *NewParam = ParmVarDecl::Create(
2375 SemaRef.Context, DC, Loc, Loc, nullptr, T,
2376 SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
2377 NewParam->setScopeInfo(0, Params.size());
2378 FPTL.setParam(Params.size(), NewParam);
2379 Params.push_back(NewParam);
2382 return buildDeductionGuide(Template->getTemplateParameters(), nullptr,
2383 ExplicitSpecifier(), TSI, Loc, Loc, Loc);
2386 private:
2387 /// Transform a constructor template parameter into a deduction guide template
2388 /// parameter, rebuilding any internal references to earlier parameters and
2389 /// renumbering as we go.
2390 NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
2391 MultiLevelTemplateArgumentList &Args) {
2392 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
2393 // TemplateTypeParmDecl's index cannot be changed after creation, so
2394 // substitute it directly.
2395 auto *NewTTP = TemplateTypeParmDecl::Create(
2396 SemaRef.Context, DC, TTP->getBeginLoc(), TTP->getLocation(),
2397 /*Depth*/ 0, Depth1IndexAdjustment + TTP->getIndex(),
2398 TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
2399 TTP->isParameterPack(), TTP->hasTypeConstraint(),
2400 TTP->isExpandedParameterPack()
2401 ? std::optional<unsigned>(TTP->getNumExpansionParameters())
2402 : std::nullopt);
2403 if (const auto *TC = TTP->getTypeConstraint())
2404 SemaRef.SubstTypeConstraint(NewTTP, TC, Args,
2405 /*EvaluateConstraint*/ true);
2406 if (TTP->hasDefaultArgument()) {
2407 TypeSourceInfo *InstantiatedDefaultArg =
2408 SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
2409 TTP->getDefaultArgumentLoc(), TTP->getDeclName());
2410 if (InstantiatedDefaultArg)
2411 NewTTP->setDefaultArgument(InstantiatedDefaultArg);
2413 SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam,
2414 NewTTP);
2415 return NewTTP;
2418 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
2419 return transformTemplateParameterImpl(TTP, Args);
2421 return transformTemplateParameterImpl(
2422 cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
2424 template<typename TemplateParmDecl>
2425 TemplateParmDecl *
2426 transformTemplateParameterImpl(TemplateParmDecl *OldParam,
2427 MultiLevelTemplateArgumentList &Args) {
2428 // Ask the template instantiator to do the heavy lifting for us, then adjust
2429 // the index of the parameter once it's done.
2430 auto *NewParam =
2431 cast<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
2432 assert(NewParam->getDepth() == 0 && "unexpected template param depth");
2433 NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
2434 return NewParam;
2437 QualType transformFunctionProtoType(
2438 TypeLocBuilder &TLB, FunctionProtoTypeLoc TL,
2439 SmallVectorImpl<ParmVarDecl *> &Params,
2440 MultiLevelTemplateArgumentList &Args,
2441 SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) {
2442 SmallVector<QualType, 4> ParamTypes;
2443 const FunctionProtoType *T = TL.getTypePtr();
2445 // -- The types of the function parameters are those of the constructor.
2446 for (auto *OldParam : TL.getParams()) {
2447 ParmVarDecl *NewParam =
2448 transformFunctionTypeParam(OldParam, Args, MaterializedTypedefs);
2449 if (!NewParam)
2450 return QualType();
2451 ParamTypes.push_back(NewParam->getType());
2452 Params.push_back(NewParam);
2455 // -- The return type is the class template specialization designated by
2456 // the template-name and template arguments corresponding to the
2457 // template parameters obtained from the class template.
2459 // We use the injected-class-name type of the primary template instead.
2460 // This has the convenient property that it is different from any type that
2461 // the user can write in a deduction-guide (because they cannot enter the
2462 // context of the template), so implicit deduction guides can never collide
2463 // with explicit ones.
2464 QualType ReturnType = DeducedType;
2465 TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
2467 // Resolving a wording defect, we also inherit the variadicness of the
2468 // constructor.
2469 FunctionProtoType::ExtProtoInfo EPI;
2470 EPI.Variadic = T->isVariadic();
2471 EPI.HasTrailingReturn = true;
2473 QualType Result = SemaRef.BuildFunctionType(
2474 ReturnType, ParamTypes, TL.getBeginLoc(), DeductionGuideName, EPI);
2475 if (Result.isNull())
2476 return QualType();
2478 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
2479 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
2480 NewTL.setLParenLoc(TL.getLParenLoc());
2481 NewTL.setRParenLoc(TL.getRParenLoc());
2482 NewTL.setExceptionSpecRange(SourceRange());
2483 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
2484 for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
2485 NewTL.setParam(I, Params[I]);
2487 return Result;
2490 ParmVarDecl *transformFunctionTypeParam(
2491 ParmVarDecl *OldParam, MultiLevelTemplateArgumentList &Args,
2492 llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) {
2493 TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
2494 TypeSourceInfo *NewDI;
2495 if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
2496 // Expand out the one and only element in each inner pack.
2497 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
2498 NewDI =
2499 SemaRef.SubstType(PackTL.getPatternLoc(), Args,
2500 OldParam->getLocation(), OldParam->getDeclName());
2501 if (!NewDI) return nullptr;
2502 NewDI =
2503 SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
2504 PackTL.getTypePtr()->getNumExpansions());
2505 } else
2506 NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
2507 OldParam->getDeclName());
2508 if (!NewDI)
2509 return nullptr;
2511 // Extract the type. This (for instance) replaces references to typedef
2512 // members of the current instantiations with the definitions of those
2513 // typedefs, avoiding triggering instantiation of the deduced type during
2514 // deduction.
2515 NewDI = ExtractTypeForDeductionGuide(SemaRef, MaterializedTypedefs)
2516 .transform(NewDI);
2518 // Resolving a wording defect, we also inherit default arguments from the
2519 // constructor.
2520 ExprResult NewDefArg;
2521 if (OldParam->hasDefaultArg()) {
2522 // We don't care what the value is (we won't use it); just create a
2523 // placeholder to indicate there is a default argument.
2524 QualType ParamTy = NewDI->getType();
2525 NewDefArg = new (SemaRef.Context)
2526 OpaqueValueExpr(OldParam->getDefaultArg()->getBeginLoc(),
2527 ParamTy.getNonLValueExprType(SemaRef.Context),
2528 ParamTy->isLValueReferenceType() ? VK_LValue
2529 : ParamTy->isRValueReferenceType() ? VK_XValue
2530 : VK_PRValue);
2533 ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
2534 OldParam->getInnerLocStart(),
2535 OldParam->getLocation(),
2536 OldParam->getIdentifier(),
2537 NewDI->getType(),
2538 NewDI,
2539 OldParam->getStorageClass(),
2540 NewDefArg.get());
2541 NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
2542 OldParam->getFunctionScopeIndex());
2543 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam);
2544 return NewParam;
2547 FunctionTemplateDecl *buildDeductionGuide(
2548 TemplateParameterList *TemplateParams, CXXConstructorDecl *Ctor,
2549 ExplicitSpecifier ES, TypeSourceInfo *TInfo, SourceLocation LocStart,
2550 SourceLocation Loc, SourceLocation LocEnd,
2551 llvm::ArrayRef<TypedefNameDecl *> MaterializedTypedefs = {}) {
2552 DeclarationNameInfo Name(DeductionGuideName, Loc);
2553 ArrayRef<ParmVarDecl *> Params =
2554 TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
2556 // Build the implicit deduction guide template.
2557 auto *Guide =
2558 CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, ES, Name,
2559 TInfo->getType(), TInfo, LocEnd, Ctor);
2560 Guide->setImplicit();
2561 Guide->setParams(Params);
2563 for (auto *Param : Params)
2564 Param->setDeclContext(Guide);
2565 for (auto *TD : MaterializedTypedefs)
2566 TD->setDeclContext(Guide);
2568 auto *GuideTemplate = FunctionTemplateDecl::Create(
2569 SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
2570 GuideTemplate->setImplicit();
2571 Guide->setDescribedFunctionTemplate(GuideTemplate);
2573 if (isa<CXXRecordDecl>(DC)) {
2574 Guide->setAccess(AS_public);
2575 GuideTemplate->setAccess(AS_public);
2578 DC->addDecl(GuideTemplate);
2579 return GuideTemplate;
2584 FunctionTemplateDecl *Sema::DeclareImplicitDeductionGuideFromInitList(
2585 TemplateDecl *Template, MutableArrayRef<QualType> ParamTypes,
2586 SourceLocation Loc) {
2587 if (CXXRecordDecl *DefRecord =
2588 cast<CXXRecordDecl>(Template->getTemplatedDecl())->getDefinition()) {
2589 if (TemplateDecl *DescribedTemplate =
2590 DefRecord->getDescribedClassTemplate())
2591 Template = DescribedTemplate;
2594 DeclContext *DC = Template->getDeclContext();
2595 if (DC->isDependentContext())
2596 return nullptr;
2598 ConvertConstructorToDeductionGuideTransform Transform(
2599 *this, cast<ClassTemplateDecl>(Template));
2600 if (!isCompleteType(Loc, Transform.DeducedType))
2601 return nullptr;
2603 // In case we were expanding a pack when we attempted to declare deduction
2604 // guides, turn off pack expansion for everything we're about to do.
2605 ArgumentPackSubstitutionIndexRAII SubstIndex(*this,
2606 /*NewSubstitutionIndex=*/-1);
2607 // Create a template instantiation record to track the "instantiation" of
2608 // constructors into deduction guides.
2609 InstantiatingTemplate BuildingDeductionGuides(
2610 *this, Loc, Template,
2611 Sema::InstantiatingTemplate::BuildingDeductionGuidesTag{});
2612 if (BuildingDeductionGuides.isInvalid())
2613 return nullptr;
2615 return cast<FunctionTemplateDecl>(
2616 Transform.buildSimpleDeductionGuide(ParamTypes));
2619 void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
2620 SourceLocation Loc) {
2621 if (CXXRecordDecl *DefRecord =
2622 cast<CXXRecordDecl>(Template->getTemplatedDecl())->getDefinition()) {
2623 if (TemplateDecl *DescribedTemplate = DefRecord->getDescribedClassTemplate())
2624 Template = DescribedTemplate;
2627 DeclContext *DC = Template->getDeclContext();
2628 if (DC->isDependentContext())
2629 return;
2631 ConvertConstructorToDeductionGuideTransform Transform(
2632 *this, cast<ClassTemplateDecl>(Template));
2633 if (!isCompleteType(Loc, Transform.DeducedType))
2634 return;
2636 // Check whether we've already declared deduction guides for this template.
2637 // FIXME: Consider storing a flag on the template to indicate this.
2638 auto Existing = DC->lookup(Transform.DeductionGuideName);
2639 for (auto *D : Existing)
2640 if (D->isImplicit())
2641 return;
2643 // In case we were expanding a pack when we attempted to declare deduction
2644 // guides, turn off pack expansion for everything we're about to do.
2645 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
2646 // Create a template instantiation record to track the "instantiation" of
2647 // constructors into deduction guides.
2648 InstantiatingTemplate BuildingDeductionGuides(
2649 *this, Loc, Template,
2650 Sema::InstantiatingTemplate::BuildingDeductionGuidesTag{});
2651 if (BuildingDeductionGuides.isInvalid())
2652 return;
2654 // Convert declared constructors into deduction guide templates.
2655 // FIXME: Skip constructors for which deduction must necessarily fail (those
2656 // for which some class template parameter without a default argument never
2657 // appears in a deduced context).
2658 llvm::SmallPtrSet<NamedDecl *, 8> ProcessedCtors;
2659 bool AddedAny = false;
2660 for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
2661 D = D->getUnderlyingDecl();
2662 if (D->isInvalidDecl() || D->isImplicit())
2663 continue;
2665 D = cast<NamedDecl>(D->getCanonicalDecl());
2667 // Within C++20 modules, we may have multiple same constructors in
2668 // multiple same RecordDecls. And it doesn't make sense to create
2669 // duplicated deduction guides for the duplicated constructors.
2670 if (ProcessedCtors.count(D))
2671 continue;
2673 auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
2674 auto *CD =
2675 dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
2676 // Class-scope explicit specializations (MS extension) do not result in
2677 // deduction guides.
2678 if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
2679 continue;
2681 // Cannot make a deduction guide when unparsed arguments are present.
2682 if (llvm::any_of(CD->parameters(), [](ParmVarDecl *P) {
2683 return !P || P->hasUnparsedDefaultArg();
2685 continue;
2687 ProcessedCtors.insert(D);
2688 Transform.transformConstructor(FTD, CD);
2689 AddedAny = true;
2692 // C++17 [over.match.class.deduct]
2693 // -- If C is not defined or does not declare any constructors, an
2694 // additional function template derived as above from a hypothetical
2695 // constructor C().
2696 if (!AddedAny)
2697 Transform.buildSimpleDeductionGuide(std::nullopt);
2699 // -- An additional function template derived as above from a hypothetical
2700 // constructor C(C), called the copy deduction candidate.
2701 cast<CXXDeductionGuideDecl>(
2702 cast<FunctionTemplateDecl>(
2703 Transform.buildSimpleDeductionGuide(Transform.DeducedType))
2704 ->getTemplatedDecl())
2705 ->setDeductionCandidateKind(DeductionCandidate::Copy);
2708 /// Diagnose the presence of a default template argument on a
2709 /// template parameter, which is ill-formed in certain contexts.
2711 /// \returns true if the default template argument should be dropped.
2712 static bool DiagnoseDefaultTemplateArgument(Sema &S,
2713 Sema::TemplateParamListContext TPC,
2714 SourceLocation ParamLoc,
2715 SourceRange DefArgRange) {
2716 switch (TPC) {
2717 case Sema::TPC_ClassTemplate:
2718 case Sema::TPC_VarTemplate:
2719 case Sema::TPC_TypeAliasTemplate:
2720 return false;
2722 case Sema::TPC_FunctionTemplate:
2723 case Sema::TPC_FriendFunctionTemplateDefinition:
2724 // C++ [temp.param]p9:
2725 // A default template-argument shall not be specified in a
2726 // function template declaration or a function template
2727 // definition [...]
2728 // If a friend function template declaration specifies a default
2729 // template-argument, that declaration shall be a definition and shall be
2730 // the only declaration of the function template in the translation unit.
2731 // (C++98/03 doesn't have this wording; see DR226).
2732 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
2733 diag::warn_cxx98_compat_template_parameter_default_in_function_template
2734 : diag::ext_template_parameter_default_in_function_template)
2735 << DefArgRange;
2736 return false;
2738 case Sema::TPC_ClassTemplateMember:
2739 // C++0x [temp.param]p9:
2740 // A default template-argument shall not be specified in the
2741 // template-parameter-lists of the definition of a member of a
2742 // class template that appears outside of the member's class.
2743 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2744 << DefArgRange;
2745 return true;
2747 case Sema::TPC_FriendClassTemplate:
2748 case Sema::TPC_FriendFunctionTemplate:
2749 // C++ [temp.param]p9:
2750 // A default template-argument shall not be specified in a
2751 // friend template declaration.
2752 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2753 << DefArgRange;
2754 return true;
2756 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2757 // for friend function templates if there is only a single
2758 // declaration (and it is a definition). Strange!
2761 llvm_unreachable("Invalid TemplateParamListContext!");
2764 /// Check for unexpanded parameter packs within the template parameters
2765 /// of a template template parameter, recursively.
2766 static bool DiagnoseUnexpandedParameterPacks(Sema &S,
2767 TemplateTemplateParmDecl *TTP) {
2768 // A template template parameter which is a parameter pack is also a pack
2769 // expansion.
2770 if (TTP->isParameterPack())
2771 return false;
2773 TemplateParameterList *Params = TTP->getTemplateParameters();
2774 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2775 NamedDecl *P = Params->getParam(I);
2776 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
2777 if (!TTP->isParameterPack())
2778 if (const TypeConstraint *TC = TTP->getTypeConstraint())
2779 if (TC->hasExplicitTemplateArgs())
2780 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2781 if (S.DiagnoseUnexpandedParameterPack(ArgLoc,
2782 Sema::UPPC_TypeConstraint))
2783 return true;
2784 continue;
2787 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2788 if (!NTTP->isParameterPack() &&
2789 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2790 NTTP->getTypeSourceInfo(),
2791 Sema::UPPC_NonTypeTemplateParameterType))
2792 return true;
2794 continue;
2797 if (TemplateTemplateParmDecl *InnerTTP
2798 = dyn_cast<TemplateTemplateParmDecl>(P))
2799 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2800 return true;
2803 return false;
2806 /// Checks the validity of a template parameter list, possibly
2807 /// considering the template parameter list from a previous
2808 /// declaration.
2810 /// If an "old" template parameter list is provided, it must be
2811 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
2812 /// template parameter list.
2814 /// \param NewParams Template parameter list for a new template
2815 /// declaration. This template parameter list will be updated with any
2816 /// default arguments that are carried through from the previous
2817 /// template parameter list.
2819 /// \param OldParams If provided, template parameter list from a
2820 /// previous declaration of the same template. Default template
2821 /// arguments will be merged from the old template parameter list to
2822 /// the new template parameter list.
2824 /// \param TPC Describes the context in which we are checking the given
2825 /// template parameter list.
2827 /// \param SkipBody If we might have already made a prior merged definition
2828 /// of this template visible, the corresponding body-skipping information.
2829 /// Default argument redefinition is not an error when skipping such a body,
2830 /// because (under the ODR) we can assume the default arguments are the same
2831 /// as the prior merged definition.
2833 /// \returns true if an error occurred, false otherwise.
2834 bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
2835 TemplateParameterList *OldParams,
2836 TemplateParamListContext TPC,
2837 SkipBodyInfo *SkipBody) {
2838 bool Invalid = false;
2840 // C++ [temp.param]p10:
2841 // The set of default template-arguments available for use with a
2842 // template declaration or definition is obtained by merging the
2843 // default arguments from the definition (if in scope) and all
2844 // declarations in scope in the same way default function
2845 // arguments are (8.3.6).
2846 bool SawDefaultArgument = false;
2847 SourceLocation PreviousDefaultArgLoc;
2849 // Dummy initialization to avoid warnings.
2850 TemplateParameterList::iterator OldParam = NewParams->end();
2851 if (OldParams)
2852 OldParam = OldParams->begin();
2854 bool RemoveDefaultArguments = false;
2855 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2856 NewParamEnd = NewParams->end();
2857 NewParam != NewParamEnd; ++NewParam) {
2858 // Whether we've seen a duplicate default argument in the same translation
2859 // unit.
2860 bool RedundantDefaultArg = false;
2861 // Whether we've found inconsis inconsitent default arguments in different
2862 // translation unit.
2863 bool InconsistentDefaultArg = false;
2864 // The name of the module which contains the inconsistent default argument.
2865 std::string PrevModuleName;
2867 SourceLocation OldDefaultLoc;
2868 SourceLocation NewDefaultLoc;
2870 // Variable used to diagnose missing default arguments
2871 bool MissingDefaultArg = false;
2873 // Variable used to diagnose non-final parameter packs
2874 bool SawParameterPack = false;
2876 if (TemplateTypeParmDecl *NewTypeParm
2877 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2878 // Check the presence of a default argument here.
2879 if (NewTypeParm->hasDefaultArgument() &&
2880 DiagnoseDefaultTemplateArgument(*this, TPC,
2881 NewTypeParm->getLocation(),
2882 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
2883 .getSourceRange()))
2884 NewTypeParm->removeDefaultArgument();
2886 // Merge default arguments for template type parameters.
2887 TemplateTypeParmDecl *OldTypeParm
2888 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2889 if (NewTypeParm->isParameterPack()) {
2890 assert(!NewTypeParm->hasDefaultArgument() &&
2891 "Parameter packs can't have a default argument!");
2892 SawParameterPack = true;
2893 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2894 NewTypeParm->hasDefaultArgument() &&
2895 (!SkipBody || !SkipBody->ShouldSkip)) {
2896 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2897 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2898 SawDefaultArgument = true;
2900 if (!OldTypeParm->getOwningModule())
2901 RedundantDefaultArg = true;
2902 else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm,
2903 NewTypeParm)) {
2904 InconsistentDefaultArg = true;
2905 PrevModuleName =
2906 OldTypeParm->getImportedOwningModule()->getFullModuleName();
2908 PreviousDefaultArgLoc = NewDefaultLoc;
2909 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2910 // Merge the default argument from the old declaration to the
2911 // new declaration.
2912 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2913 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2914 } else if (NewTypeParm->hasDefaultArgument()) {
2915 SawDefaultArgument = true;
2916 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2917 } else if (SawDefaultArgument)
2918 MissingDefaultArg = true;
2919 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2920 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2921 // Check for unexpanded parameter packs.
2922 if (!NewNonTypeParm->isParameterPack() &&
2923 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2924 NewNonTypeParm->getTypeSourceInfo(),
2925 UPPC_NonTypeTemplateParameterType)) {
2926 Invalid = true;
2927 continue;
2930 // Check the presence of a default argument here.
2931 if (NewNonTypeParm->hasDefaultArgument() &&
2932 DiagnoseDefaultTemplateArgument(*this, TPC,
2933 NewNonTypeParm->getLocation(),
2934 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
2935 NewNonTypeParm->removeDefaultArgument();
2938 // Merge default arguments for non-type template parameters
2939 NonTypeTemplateParmDecl *OldNonTypeParm
2940 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2941 if (NewNonTypeParm->isParameterPack()) {
2942 assert(!NewNonTypeParm->hasDefaultArgument() &&
2943 "Parameter packs can't have a default argument!");
2944 if (!NewNonTypeParm->isPackExpansion())
2945 SawParameterPack = true;
2946 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2947 NewNonTypeParm->hasDefaultArgument() &&
2948 (!SkipBody || !SkipBody->ShouldSkip)) {
2949 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2950 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2951 SawDefaultArgument = true;
2952 if (!OldNonTypeParm->getOwningModule())
2953 RedundantDefaultArg = true;
2954 else if (!getASTContext().isSameDefaultTemplateArgument(
2955 OldNonTypeParm, NewNonTypeParm)) {
2956 InconsistentDefaultArg = true;
2957 PrevModuleName =
2958 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
2960 PreviousDefaultArgLoc = NewDefaultLoc;
2961 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2962 // Merge the default argument from the old declaration to the
2963 // new declaration.
2964 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2965 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2966 } else if (NewNonTypeParm->hasDefaultArgument()) {
2967 SawDefaultArgument = true;
2968 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2969 } else if (SawDefaultArgument)
2970 MissingDefaultArg = true;
2971 } else {
2972 TemplateTemplateParmDecl *NewTemplateParm
2973 = cast<TemplateTemplateParmDecl>(*NewParam);
2975 // Check for unexpanded parameter packs, recursively.
2976 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2977 Invalid = true;
2978 continue;
2981 // Check the presence of a default argument here.
2982 if (NewTemplateParm->hasDefaultArgument() &&
2983 DiagnoseDefaultTemplateArgument(*this, TPC,
2984 NewTemplateParm->getLocation(),
2985 NewTemplateParm->getDefaultArgument().getSourceRange()))
2986 NewTemplateParm->removeDefaultArgument();
2988 // Merge default arguments for template template parameters
2989 TemplateTemplateParmDecl *OldTemplateParm
2990 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2991 if (NewTemplateParm->isParameterPack()) {
2992 assert(!NewTemplateParm->hasDefaultArgument() &&
2993 "Parameter packs can't have a default argument!");
2994 if (!NewTemplateParm->isPackExpansion())
2995 SawParameterPack = true;
2996 } else if (OldTemplateParm &&
2997 hasVisibleDefaultArgument(OldTemplateParm) &&
2998 NewTemplateParm->hasDefaultArgument() &&
2999 (!SkipBody || !SkipBody->ShouldSkip)) {
3000 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
3001 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
3002 SawDefaultArgument = true;
3003 if (!OldTemplateParm->getOwningModule())
3004 RedundantDefaultArg = true;
3005 else if (!getASTContext().isSameDefaultTemplateArgument(
3006 OldTemplateParm, NewTemplateParm)) {
3007 InconsistentDefaultArg = true;
3008 PrevModuleName =
3009 OldTemplateParm->getImportedOwningModule()->getFullModuleName();
3011 PreviousDefaultArgLoc = NewDefaultLoc;
3012 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
3013 // Merge the default argument from the old declaration to the
3014 // new declaration.
3015 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
3016 PreviousDefaultArgLoc
3017 = OldTemplateParm->getDefaultArgument().getLocation();
3018 } else if (NewTemplateParm->hasDefaultArgument()) {
3019 SawDefaultArgument = true;
3020 PreviousDefaultArgLoc
3021 = NewTemplateParm->getDefaultArgument().getLocation();
3022 } else if (SawDefaultArgument)
3023 MissingDefaultArg = true;
3026 // C++11 [temp.param]p11:
3027 // If a template parameter of a primary class template or alias template
3028 // is a template parameter pack, it shall be the last template parameter.
3029 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
3030 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
3031 TPC == TPC_TypeAliasTemplate)) {
3032 Diag((*NewParam)->getLocation(),
3033 diag::err_template_param_pack_must_be_last_template_parameter);
3034 Invalid = true;
3037 // [basic.def.odr]/13:
3038 // There can be more than one definition of a
3039 // ...
3040 // default template argument
3041 // ...
3042 // in a program provided that each definition appears in a different
3043 // translation unit and the definitions satisfy the [same-meaning
3044 // criteria of the ODR].
3046 // Simply, the design of modules allows the definition of template default
3047 // argument to be repeated across translation unit. Note that the ODR is
3048 // checked elsewhere. But it is still not allowed to repeat template default
3049 // argument in the same translation unit.
3050 if (RedundantDefaultArg) {
3051 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
3052 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
3053 Invalid = true;
3054 } else if (InconsistentDefaultArg) {
3055 // We could only diagnose about the case that the OldParam is imported.
3056 // The case NewParam is imported should be handled in ASTReader.
3057 Diag(NewDefaultLoc,
3058 diag::err_template_param_default_arg_inconsistent_redefinition);
3059 Diag(OldDefaultLoc,
3060 diag::note_template_param_prev_default_arg_in_other_module)
3061 << PrevModuleName;
3062 Invalid = true;
3063 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
3064 // C++ [temp.param]p11:
3065 // If a template-parameter of a class template has a default
3066 // template-argument, each subsequent template-parameter shall either
3067 // have a default template-argument supplied or be a template parameter
3068 // pack.
3069 Diag((*NewParam)->getLocation(),
3070 diag::err_template_param_default_arg_missing);
3071 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
3072 Invalid = true;
3073 RemoveDefaultArguments = true;
3076 // If we have an old template parameter list that we're merging
3077 // in, move on to the next parameter.
3078 if (OldParams)
3079 ++OldParam;
3082 // We were missing some default arguments at the end of the list, so remove
3083 // all of the default arguments.
3084 if (RemoveDefaultArguments) {
3085 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
3086 NewParamEnd = NewParams->end();
3087 NewParam != NewParamEnd; ++NewParam) {
3088 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
3089 TTP->removeDefaultArgument();
3090 else if (NonTypeTemplateParmDecl *NTTP
3091 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
3092 NTTP->removeDefaultArgument();
3093 else
3094 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
3098 return Invalid;
3101 namespace {
3103 /// A class which looks for a use of a certain level of template
3104 /// parameter.
3105 struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
3106 typedef RecursiveASTVisitor<DependencyChecker> super;
3108 unsigned Depth;
3110 // Whether we're looking for a use of a template parameter that makes the
3111 // overall construct type-dependent / a dependent type. This is strictly
3112 // best-effort for now; we may fail to match at all for a dependent type
3113 // in some cases if this is set.
3114 bool IgnoreNonTypeDependent;
3116 bool Match;
3117 SourceLocation MatchLoc;
3119 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
3120 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
3121 Match(false) {}
3123 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
3124 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
3125 NamedDecl *ND = Params->getParam(0);
3126 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
3127 Depth = PD->getDepth();
3128 } else if (NonTypeTemplateParmDecl *PD =
3129 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
3130 Depth = PD->getDepth();
3131 } else {
3132 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
3136 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
3137 if (ParmDepth >= Depth) {
3138 Match = true;
3139 MatchLoc = Loc;
3140 return true;
3142 return false;
3145 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
3146 // Prune out non-type-dependent expressions if requested. This can
3147 // sometimes result in us failing to find a template parameter reference
3148 // (if a value-dependent expression creates a dependent type), but this
3149 // mode is best-effort only.
3150 if (auto *E = dyn_cast_or_null<Expr>(S))
3151 if (IgnoreNonTypeDependent && !E->isTypeDependent())
3152 return true;
3153 return super::TraverseStmt(S, Q);
3156 bool TraverseTypeLoc(TypeLoc TL) {
3157 if (IgnoreNonTypeDependent && !TL.isNull() &&
3158 !TL.getType()->isDependentType())
3159 return true;
3160 return super::TraverseTypeLoc(TL);
3163 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
3164 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
3167 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
3168 // For a best-effort search, keep looking until we find a location.
3169 return IgnoreNonTypeDependent || !Matches(T->getDepth());
3172 bool TraverseTemplateName(TemplateName N) {
3173 if (TemplateTemplateParmDecl *PD =
3174 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
3175 if (Matches(PD->getDepth()))
3176 return false;
3177 return super::TraverseTemplateName(N);
3180 bool VisitDeclRefExpr(DeclRefExpr *E) {
3181 if (NonTypeTemplateParmDecl *PD =
3182 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
3183 if (Matches(PD->getDepth(), E->getExprLoc()))
3184 return false;
3185 return super::VisitDeclRefExpr(E);
3188 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
3189 return TraverseType(T->getReplacementType());
3192 bool
3193 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
3194 return TraverseTemplateArgument(T->getArgumentPack());
3197 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
3198 return TraverseType(T->getInjectedSpecializationType());
3201 } // end anonymous namespace
3203 /// Determines whether a given type depends on the given parameter
3204 /// list.
3205 static bool
3206 DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
3207 if (!Params->size())
3208 return false;
3210 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
3211 Checker.TraverseType(T);
3212 return Checker.Match;
3215 // Find the source range corresponding to the named type in the given
3216 // nested-name-specifier, if any.
3217 static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
3218 QualType T,
3219 const CXXScopeSpec &SS) {
3220 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
3221 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
3222 if (const Type *CurType = NNS->getAsType()) {
3223 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
3224 return NNSLoc.getTypeLoc().getSourceRange();
3225 } else
3226 break;
3228 NNSLoc = NNSLoc.getPrefix();
3231 return SourceRange();
3234 /// Match the given template parameter lists to the given scope
3235 /// specifier, returning the template parameter list that applies to the
3236 /// name.
3238 /// \param DeclStartLoc the start of the declaration that has a scope
3239 /// specifier or a template parameter list.
3241 /// \param DeclLoc The location of the declaration itself.
3243 /// \param SS the scope specifier that will be matched to the given template
3244 /// parameter lists. This scope specifier precedes a qualified name that is
3245 /// being declared.
3247 /// \param TemplateId The template-id following the scope specifier, if there
3248 /// is one. Used to check for a missing 'template<>'.
3250 /// \param ParamLists the template parameter lists, from the outermost to the
3251 /// innermost template parameter lists.
3253 /// \param IsFriend Whether to apply the slightly different rules for
3254 /// matching template parameters to scope specifiers in friend
3255 /// declarations.
3257 /// \param IsMemberSpecialization will be set true if the scope specifier
3258 /// denotes a fully-specialized type, and therefore this is a declaration of
3259 /// a member specialization.
3261 /// \returns the template parameter list, if any, that corresponds to the
3262 /// name that is preceded by the scope specifier @p SS. This template
3263 /// parameter list may have template parameters (if we're declaring a
3264 /// template) or may have no template parameters (if we're declaring a
3265 /// template specialization), or may be NULL (if what we're declaring isn't
3266 /// itself a template).
3267 TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
3268 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
3269 TemplateIdAnnotation *TemplateId,
3270 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
3271 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
3272 IsMemberSpecialization = false;
3273 Invalid = false;
3275 // The sequence of nested types to which we will match up the template
3276 // parameter lists. We first build this list by starting with the type named
3277 // by the nested-name-specifier and walking out until we run out of types.
3278 SmallVector<QualType, 4> NestedTypes;
3279 QualType T;
3280 if (SS.getScopeRep()) {
3281 if (CXXRecordDecl *Record
3282 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
3283 T = Context.getTypeDeclType(Record);
3284 else
3285 T = QualType(SS.getScopeRep()->getAsType(), 0);
3288 // If we found an explicit specialization that prevents us from needing
3289 // 'template<>' headers, this will be set to the location of that
3290 // explicit specialization.
3291 SourceLocation ExplicitSpecLoc;
3293 while (!T.isNull()) {
3294 NestedTypes.push_back(T);
3296 // Retrieve the parent of a record type.
3297 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
3298 // If this type is an explicit specialization, we're done.
3299 if (ClassTemplateSpecializationDecl *Spec
3300 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
3301 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
3302 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
3303 ExplicitSpecLoc = Spec->getLocation();
3304 break;
3306 } else if (Record->getTemplateSpecializationKind()
3307 == TSK_ExplicitSpecialization) {
3308 ExplicitSpecLoc = Record->getLocation();
3309 break;
3312 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
3313 T = Context.getTypeDeclType(Parent);
3314 else
3315 T = QualType();
3316 continue;
3319 if (const TemplateSpecializationType *TST
3320 = T->getAs<TemplateSpecializationType>()) {
3321 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
3322 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
3323 T = Context.getTypeDeclType(Parent);
3324 else
3325 T = QualType();
3326 continue;
3330 // Look one step prior in a dependent template specialization type.
3331 if (const DependentTemplateSpecializationType *DependentTST
3332 = T->getAs<DependentTemplateSpecializationType>()) {
3333 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
3334 T = QualType(NNS->getAsType(), 0);
3335 else
3336 T = QualType();
3337 continue;
3340 // Look one step prior in a dependent name type.
3341 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
3342 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
3343 T = QualType(NNS->getAsType(), 0);
3344 else
3345 T = QualType();
3346 continue;
3349 // Retrieve the parent of an enumeration type.
3350 if (const EnumType *EnumT = T->getAs<EnumType>()) {
3351 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
3352 // check here.
3353 EnumDecl *Enum = EnumT->getDecl();
3355 // Get to the parent type.
3356 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
3357 T = Context.getTypeDeclType(Parent);
3358 else
3359 T = QualType();
3360 continue;
3363 T = QualType();
3365 // Reverse the nested types list, since we want to traverse from the outermost
3366 // to the innermost while checking template-parameter-lists.
3367 std::reverse(NestedTypes.begin(), NestedTypes.end());
3369 // C++0x [temp.expl.spec]p17:
3370 // A member or a member template may be nested within many
3371 // enclosing class templates. In an explicit specialization for
3372 // such a member, the member declaration shall be preceded by a
3373 // template<> for each enclosing class template that is
3374 // explicitly specialized.
3375 bool SawNonEmptyTemplateParameterList = false;
3377 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
3378 if (SawNonEmptyTemplateParameterList) {
3379 if (!SuppressDiagnostic)
3380 Diag(DeclLoc, diag::err_specialize_member_of_template)
3381 << !Recovery << Range;
3382 Invalid = true;
3383 IsMemberSpecialization = false;
3384 return true;
3387 return false;
3390 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
3391 // Check that we can have an explicit specialization here.
3392 if (CheckExplicitSpecialization(Range, true))
3393 return true;
3395 // We don't have a template header, but we should.
3396 SourceLocation ExpectedTemplateLoc;
3397 if (!ParamLists.empty())
3398 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
3399 else
3400 ExpectedTemplateLoc = DeclStartLoc;
3402 if (!SuppressDiagnostic)
3403 Diag(DeclLoc, diag::err_template_spec_needs_header)
3404 << Range
3405 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
3406 return false;
3409 unsigned ParamIdx = 0;
3410 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
3411 ++TypeIdx) {
3412 T = NestedTypes[TypeIdx];
3414 // Whether we expect a 'template<>' header.
3415 bool NeedEmptyTemplateHeader = false;
3417 // Whether we expect a template header with parameters.
3418 bool NeedNonemptyTemplateHeader = false;
3420 // For a dependent type, the set of template parameters that we
3421 // expect to see.
3422 TemplateParameterList *ExpectedTemplateParams = nullptr;
3424 // C++0x [temp.expl.spec]p15:
3425 // A member or a member template may be nested within many enclosing
3426 // class templates. In an explicit specialization for such a member, the
3427 // member declaration shall be preceded by a template<> for each
3428 // enclosing class template that is explicitly specialized.
3429 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
3430 if (ClassTemplatePartialSpecializationDecl *Partial
3431 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
3432 ExpectedTemplateParams = Partial->getTemplateParameters();
3433 NeedNonemptyTemplateHeader = true;
3434 } else if (Record->isDependentType()) {
3435 if (Record->getDescribedClassTemplate()) {
3436 ExpectedTemplateParams = Record->getDescribedClassTemplate()
3437 ->getTemplateParameters();
3438 NeedNonemptyTemplateHeader = true;
3440 } else if (ClassTemplateSpecializationDecl *Spec
3441 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
3442 // C++0x [temp.expl.spec]p4:
3443 // Members of an explicitly specialized class template are defined
3444 // in the same manner as members of normal classes, and not using
3445 // the template<> syntax.
3446 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
3447 NeedEmptyTemplateHeader = true;
3448 else
3449 continue;
3450 } else if (Record->getTemplateSpecializationKind()) {
3451 if (Record->getTemplateSpecializationKind()
3452 != TSK_ExplicitSpecialization &&
3453 TypeIdx == NumTypes - 1)
3454 IsMemberSpecialization = true;
3456 continue;
3458 } else if (const TemplateSpecializationType *TST
3459 = T->getAs<TemplateSpecializationType>()) {
3460 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
3461 ExpectedTemplateParams = Template->getTemplateParameters();
3462 NeedNonemptyTemplateHeader = true;
3464 } else if (T->getAs<DependentTemplateSpecializationType>()) {
3465 // FIXME: We actually could/should check the template arguments here
3466 // against the corresponding template parameter list.
3467 NeedNonemptyTemplateHeader = false;
3470 // C++ [temp.expl.spec]p16:
3471 // In an explicit specialization declaration for a member of a class
3472 // template or a member template that ap- pears in namespace scope, the
3473 // member template and some of its enclosing class templates may remain
3474 // unspecialized, except that the declaration shall not explicitly
3475 // specialize a class member template if its en- closing class templates
3476 // are not explicitly specialized as well.
3477 if (ParamIdx < ParamLists.size()) {
3478 if (ParamLists[ParamIdx]->size() == 0) {
3479 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3480 false))
3481 return nullptr;
3482 } else
3483 SawNonEmptyTemplateParameterList = true;
3486 if (NeedEmptyTemplateHeader) {
3487 // If we're on the last of the types, and we need a 'template<>' header
3488 // here, then it's a member specialization.
3489 if (TypeIdx == NumTypes - 1)
3490 IsMemberSpecialization = true;
3492 if (ParamIdx < ParamLists.size()) {
3493 if (ParamLists[ParamIdx]->size() > 0) {
3494 // The header has template parameters when it shouldn't. Complain.
3495 if (!SuppressDiagnostic)
3496 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3497 diag::err_template_param_list_matches_nontemplate)
3498 << T
3499 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
3500 ParamLists[ParamIdx]->getRAngleLoc())
3501 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
3502 Invalid = true;
3503 return nullptr;
3506 // Consume this template header.
3507 ++ParamIdx;
3508 continue;
3511 if (!IsFriend)
3512 if (DiagnoseMissingExplicitSpecialization(
3513 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
3514 return nullptr;
3516 continue;
3519 if (NeedNonemptyTemplateHeader) {
3520 // In friend declarations we can have template-ids which don't
3521 // depend on the corresponding template parameter lists. But
3522 // assume that empty parameter lists are supposed to match this
3523 // template-id.
3524 if (IsFriend && T->isDependentType()) {
3525 if (ParamIdx < ParamLists.size() &&
3526 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
3527 ExpectedTemplateParams = nullptr;
3528 else
3529 continue;
3532 if (ParamIdx < ParamLists.size()) {
3533 // Check the template parameter list, if we can.
3534 if (ExpectedTemplateParams &&
3535 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
3536 ExpectedTemplateParams,
3537 !SuppressDiagnostic, TPL_TemplateMatch))
3538 Invalid = true;
3540 if (!Invalid &&
3541 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
3542 TPC_ClassTemplateMember))
3543 Invalid = true;
3545 ++ParamIdx;
3546 continue;
3549 if (!SuppressDiagnostic)
3550 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
3551 << T
3552 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
3553 Invalid = true;
3554 continue;
3558 // If there were at least as many template-ids as there were template
3559 // parameter lists, then there are no template parameter lists remaining for
3560 // the declaration itself.
3561 if (ParamIdx >= ParamLists.size()) {
3562 if (TemplateId && !IsFriend) {
3563 // We don't have a template header for the declaration itself, but we
3564 // should.
3565 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
3566 TemplateId->RAngleLoc));
3568 // Fabricate an empty template parameter list for the invented header.
3569 return TemplateParameterList::Create(Context, SourceLocation(),
3570 SourceLocation(), std::nullopt,
3571 SourceLocation(), nullptr);
3574 return nullptr;
3577 // If there were too many template parameter lists, complain about that now.
3578 if (ParamIdx < ParamLists.size() - 1) {
3579 bool HasAnyExplicitSpecHeader = false;
3580 bool AllExplicitSpecHeaders = true;
3581 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3582 if (ParamLists[I]->size() == 0)
3583 HasAnyExplicitSpecHeader = true;
3584 else
3585 AllExplicitSpecHeaders = false;
3588 if (!SuppressDiagnostic)
3589 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3590 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
3591 : diag::err_template_spec_extra_headers)
3592 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3593 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3595 // If there was a specialization somewhere, such that 'template<>' is
3596 // not required, and there were any 'template<>' headers, note where the
3597 // specialization occurred.
3598 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3599 !SuppressDiagnostic)
3600 Diag(ExplicitSpecLoc,
3601 diag::note_explicit_template_spec_does_not_need_header)
3602 << NestedTypes.back();
3604 // We have a template parameter list with no corresponding scope, which
3605 // means that the resulting template declaration can't be instantiated
3606 // properly (we'll end up with dependent nodes when we shouldn't).
3607 if (!AllExplicitSpecHeaders)
3608 Invalid = true;
3611 // C++ [temp.expl.spec]p16:
3612 // In an explicit specialization declaration for a member of a class
3613 // template or a member template that ap- pears in namespace scope, the
3614 // member template and some of its enclosing class templates may remain
3615 // unspecialized, except that the declaration shall not explicitly
3616 // specialize a class member template if its en- closing class templates
3617 // are not explicitly specialized as well.
3618 if (ParamLists.back()->size() == 0 &&
3619 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3620 false))
3621 return nullptr;
3623 // Return the last template parameter list, which corresponds to the
3624 // entity being declared.
3625 return ParamLists.back();
3628 void Sema::NoteAllFoundTemplates(TemplateName Name) {
3629 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3630 Diag(Template->getLocation(), diag::note_template_declared_here)
3631 << (isa<FunctionTemplateDecl>(Template)
3633 : isa<ClassTemplateDecl>(Template)
3635 : isa<VarTemplateDecl>(Template)
3637 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
3638 << Template->getDeclName();
3639 return;
3642 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
3643 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3644 IEnd = OST->end();
3645 I != IEnd; ++I)
3646 Diag((*I)->getLocation(), diag::note_template_declared_here)
3647 << 0 << (*I)->getDeclName();
3649 return;
3653 static QualType
3654 checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
3655 ArrayRef<TemplateArgument> Converted,
3656 SourceLocation TemplateLoc,
3657 TemplateArgumentListInfo &TemplateArgs) {
3658 ASTContext &Context = SemaRef.getASTContext();
3660 switch (BTD->getBuiltinTemplateKind()) {
3661 case BTK__make_integer_seq: {
3662 // Specializations of __make_integer_seq<S, T, N> are treated like
3663 // S<T, 0, ..., N-1>.
3665 QualType OrigType = Converted[1].getAsType();
3666 // C++14 [inteseq.intseq]p1:
3667 // T shall be an integer type.
3668 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) {
3669 SemaRef.Diag(TemplateArgs[1].getLocation(),
3670 diag::err_integer_sequence_integral_element_type);
3671 return QualType();
3674 TemplateArgument NumArgsArg = Converted[2];
3675 if (NumArgsArg.isDependent())
3676 return Context.getCanonicalTemplateSpecializationType(TemplateName(BTD),
3677 Converted);
3679 TemplateArgumentListInfo SyntheticTemplateArgs;
3680 // The type argument, wrapped in substitution sugar, gets reused as the
3681 // first template argument in the synthetic template argument list.
3682 SyntheticTemplateArgs.addArgument(
3683 TemplateArgumentLoc(TemplateArgument(OrigType),
3684 SemaRef.Context.getTrivialTypeSourceInfo(
3685 OrigType, TemplateArgs[1].getLocation())));
3687 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3688 // Expand N into 0 ... N-1.
3689 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3690 I < NumArgs; ++I) {
3691 TemplateArgument TA(Context, I, OrigType);
3692 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3693 TA, OrigType, TemplateArgs[2].getLocation()));
3695 } else {
3696 // C++14 [inteseq.make]p1:
3697 // If N is negative the program is ill-formed.
3698 SemaRef.Diag(TemplateArgs[2].getLocation(),
3699 diag::err_integer_sequence_negative_length);
3700 return QualType();
3703 // The first template argument will be reused as the template decl that
3704 // our synthetic template arguments will be applied to.
3705 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
3706 TemplateLoc, SyntheticTemplateArgs);
3709 case BTK__type_pack_element:
3710 // Specializations of
3711 // __type_pack_element<Index, T_1, ..., T_N>
3712 // are treated like T_Index.
3713 assert(Converted.size() == 2 &&
3714 "__type_pack_element should be given an index and a parameter pack");
3716 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3717 if (IndexArg.isDependent() || Ts.isDependent())
3718 return Context.getCanonicalTemplateSpecializationType(TemplateName(BTD),
3719 Converted);
3721 llvm::APSInt Index = IndexArg.getAsIntegral();
3722 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3723 "type std::size_t, and hence be non-negative");
3724 // If the Index is out of bounds, the program is ill-formed.
3725 if (Index >= Ts.pack_size()) {
3726 SemaRef.Diag(TemplateArgs[0].getLocation(),
3727 diag::err_type_pack_element_out_of_bounds);
3728 return QualType();
3731 // We simply return the type at index `Index`.
3732 int64_t N = Index.getExtValue();
3733 return Ts.getPackAsArray()[N].getAsType();
3735 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3738 /// Determine whether this alias template is "enable_if_t".
3739 /// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3740 static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
3741 return AliasTemplate->getName().equals("enable_if_t") ||
3742 AliasTemplate->getName().equals("__enable_if_t");
3745 /// Collect all of the separable terms in the given condition, which
3746 /// might be a conjunction.
3748 /// FIXME: The right answer is to convert the logical expression into
3749 /// disjunctive normal form, so we can find the first failed term
3750 /// within each possible clause.
3751 static void collectConjunctionTerms(Expr *Clause,
3752 SmallVectorImpl<Expr *> &Terms) {
3753 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3754 if (BinOp->getOpcode() == BO_LAnd) {
3755 collectConjunctionTerms(BinOp->getLHS(), Terms);
3756 collectConjunctionTerms(BinOp->getRHS(), Terms);
3757 return;
3761 Terms.push_back(Clause);
3764 // The ranges-v3 library uses an odd pattern of a top-level "||" with
3765 // a left-hand side that is value-dependent but never true. Identify
3766 // the idiom and ignore that term.
3767 static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
3768 // Top-level '||'.
3769 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3770 if (!BinOp) return Cond;
3772 if (BinOp->getOpcode() != BO_LOr) return Cond;
3774 // With an inner '==' that has a literal on the right-hand side.
3775 Expr *LHS = BinOp->getLHS();
3776 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3777 if (!InnerBinOp) return Cond;
3779 if (InnerBinOp->getOpcode() != BO_EQ ||
3780 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3781 return Cond;
3783 // If the inner binary operation came from a macro expansion named
3784 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3785 // of the '||', which is the real, user-provided condition.
3786 SourceLocation Loc = InnerBinOp->getExprLoc();
3787 if (!Loc.isMacroID()) return Cond;
3789 StringRef MacroName = PP.getImmediateMacroName(Loc);
3790 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3791 return BinOp->getRHS();
3793 return Cond;
3796 namespace {
3798 // A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3799 // within failing boolean expression, such as substituting template parameters
3800 // for actual types.
3801 class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3802 public:
3803 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3804 : Policy(P) {}
3806 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3807 const auto *DR = dyn_cast<DeclRefExpr>(E);
3808 if (DR && DR->getQualifier()) {
3809 // If this is a qualified name, expand the template arguments in nested
3810 // qualifiers.
3811 DR->getQualifier()->print(OS, Policy, true);
3812 // Then print the decl itself.
3813 const ValueDecl *VD = DR->getDecl();
3814 OS << VD->getName();
3815 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3816 // This is a template variable, print the expanded template arguments.
3817 printTemplateArgumentList(
3818 OS, IV->getTemplateArgs().asArray(), Policy,
3819 IV->getSpecializedTemplate()->getTemplateParameters());
3821 return true;
3823 return false;
3826 private:
3827 const PrintingPolicy Policy;
3830 } // end anonymous namespace
3832 std::pair<Expr *, std::string>
3833 Sema::findFailedBooleanCondition(Expr *Cond) {
3834 Cond = lookThroughRangesV3Condition(PP, Cond);
3836 // Separate out all of the terms in a conjunction.
3837 SmallVector<Expr *, 4> Terms;
3838 collectConjunctionTerms(Cond, Terms);
3840 // Determine which term failed.
3841 Expr *FailedCond = nullptr;
3842 for (Expr *Term : Terms) {
3843 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3845 // Literals are uninteresting.
3846 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3847 isa<IntegerLiteral>(TermAsWritten))
3848 continue;
3850 // The initialization of the parameter from the argument is
3851 // a constant-evaluated context.
3852 EnterExpressionEvaluationContext ConstantEvaluated(
3853 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
3855 bool Succeeded;
3856 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3857 !Succeeded) {
3858 FailedCond = TermAsWritten;
3859 break;
3862 if (!FailedCond)
3863 FailedCond = Cond->IgnoreParenImpCasts();
3865 std::string Description;
3867 llvm::raw_string_ostream Out(Description);
3868 PrintingPolicy Policy = getPrintingPolicy();
3869 Policy.PrintCanonicalTypes = true;
3870 FailedBooleanConditionPrinterHelper Helper(Policy);
3871 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3873 return { FailedCond, Description };
3876 QualType Sema::CheckTemplateIdType(TemplateName Name,
3877 SourceLocation TemplateLoc,
3878 TemplateArgumentListInfo &TemplateArgs) {
3879 DependentTemplateName *DTN
3880 = Name.getUnderlying().getAsDependentTemplateName();
3881 if (DTN && DTN->isIdentifier())
3882 // When building a template-id where the template-name is dependent,
3883 // assume the template is a type template. Either our assumption is
3884 // correct, or the code is ill-formed and will be diagnosed when the
3885 // dependent name is substituted.
3886 return Context.getDependentTemplateSpecializationType(
3887 ElaboratedTypeKeyword::None, DTN->getQualifier(), DTN->getIdentifier(),
3888 TemplateArgs.arguments());
3890 if (Name.getAsAssumedTemplateName() &&
3891 resolveAssumedTemplateNameAsType(/*Scope*/nullptr, Name, TemplateLoc))
3892 return QualType();
3894 TemplateDecl *Template = Name.getAsTemplateDecl();
3895 if (!Template || isa<FunctionTemplateDecl>(Template) ||
3896 isa<VarTemplateDecl>(Template) || isa<ConceptDecl>(Template)) {
3897 // We might have a substituted template template parameter pack. If so,
3898 // build a template specialization type for it.
3899 if (Name.getAsSubstTemplateTemplateParmPack())
3900 return Context.getTemplateSpecializationType(Name,
3901 TemplateArgs.arguments());
3903 Diag(TemplateLoc, diag::err_template_id_not_a_type)
3904 << Name;
3905 NoteAllFoundTemplates(Name);
3906 return QualType();
3909 // Check that the template argument list is well-formed for this
3910 // template.
3911 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
3912 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs, false,
3913 SugaredConverted, CanonicalConverted,
3914 /*UpdateArgsWithConversions=*/true))
3915 return QualType();
3917 QualType CanonType;
3919 if (TypeAliasTemplateDecl *AliasTemplate =
3920 dyn_cast<TypeAliasTemplateDecl>(Template)) {
3922 // Find the canonical type for this type alias template specialization.
3923 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3924 if (Pattern->isInvalidDecl())
3925 return QualType();
3927 // Only substitute for the innermost template argument list.
3928 MultiLevelTemplateArgumentList TemplateArgLists;
3929 TemplateArgLists.addOuterTemplateArguments(Template, CanonicalConverted,
3930 /*Final=*/false);
3931 TemplateArgLists.addOuterRetainedLevels(
3932 AliasTemplate->getTemplateParameters()->getDepth());
3934 LocalInstantiationScope Scope(*this);
3935 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
3936 if (Inst.isInvalid())
3937 return QualType();
3939 CanonType = SubstType(Pattern->getUnderlyingType(),
3940 TemplateArgLists, AliasTemplate->getLocation(),
3941 AliasTemplate->getDeclName());
3942 if (CanonType.isNull()) {
3943 // If this was enable_if and we failed to find the nested type
3944 // within enable_if in a SFINAE context, dig out the specific
3945 // enable_if condition that failed and present that instead.
3946 if (isEnableIfAliasTemplate(AliasTemplate)) {
3947 if (auto DeductionInfo = isSFINAEContext()) {
3948 if (*DeductionInfo &&
3949 (*DeductionInfo)->hasSFINAEDiagnostic() &&
3950 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3951 diag::err_typename_nested_not_found_enable_if &&
3952 TemplateArgs[0].getArgument().getKind()
3953 == TemplateArgument::Expression) {
3954 Expr *FailedCond;
3955 std::string FailedDescription;
3956 std::tie(FailedCond, FailedDescription) =
3957 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
3959 // Remove the old SFINAE diagnostic.
3960 PartialDiagnosticAt OldDiag =
3961 {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3962 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3964 // Add a new SFINAE diagnostic specifying which condition
3965 // failed.
3966 (*DeductionInfo)->addSFINAEDiagnostic(
3967 OldDiag.first,
3968 PDiag(diag::err_typename_nested_not_found_requirement)
3969 << FailedDescription
3970 << FailedCond->getSourceRange());
3975 return QualType();
3977 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3978 CanonType = checkBuiltinTemplateIdType(*this, BTD, SugaredConverted,
3979 TemplateLoc, TemplateArgs);
3980 } else if (Name.isDependent() ||
3981 TemplateSpecializationType::anyDependentTemplateArguments(
3982 TemplateArgs, CanonicalConverted)) {
3983 // This class template specialization is a dependent
3984 // type. Therefore, its canonical type is another class template
3985 // specialization type that contains all of the converted
3986 // arguments in canonical form. This ensures that, e.g., A<T> and
3987 // A<T, T> have identical types when A is declared as:
3989 // template<typename T, typename U = T> struct A;
3990 CanonType = Context.getCanonicalTemplateSpecializationType(
3991 Name, CanonicalConverted);
3993 // This might work out to be a current instantiation, in which
3994 // case the canonical type needs to be the InjectedClassNameType.
3996 // TODO: in theory this could be a simple hashtable lookup; most
3997 // changes to CurContext don't change the set of current
3998 // instantiations.
3999 if (isa<ClassTemplateDecl>(Template)) {
4000 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
4001 // If we get out to a namespace, we're done.
4002 if (Ctx->isFileContext()) break;
4004 // If this isn't a record, keep looking.
4005 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
4006 if (!Record) continue;
4008 // Look for one of the two cases with InjectedClassNameTypes
4009 // and check whether it's the same template.
4010 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
4011 !Record->getDescribedClassTemplate())
4012 continue;
4014 // Fetch the injected class name type and check whether its
4015 // injected type is equal to the type we just built.
4016 QualType ICNT = Context.getTypeDeclType(Record);
4017 QualType Injected = cast<InjectedClassNameType>(ICNT)
4018 ->getInjectedSpecializationType();
4020 if (CanonType != Injected->getCanonicalTypeInternal())
4021 continue;
4023 // If so, the canonical type of this TST is the injected
4024 // class name type of the record we just found.
4025 assert(ICNT.isCanonical());
4026 CanonType = ICNT;
4027 break;
4030 } else if (ClassTemplateDecl *ClassTemplate =
4031 dyn_cast<ClassTemplateDecl>(Template)) {
4032 // Find the class template specialization declaration that
4033 // corresponds to these arguments.
4034 void *InsertPos = nullptr;
4035 ClassTemplateSpecializationDecl *Decl =
4036 ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
4037 if (!Decl) {
4038 // This is the first time we have referenced this class template
4039 // specialization. Create the canonical declaration and add it to
4040 // the set of specializations.
4041 Decl = ClassTemplateSpecializationDecl::Create(
4042 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
4043 ClassTemplate->getDeclContext(),
4044 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
4045 ClassTemplate->getLocation(), ClassTemplate, CanonicalConverted,
4046 nullptr);
4047 ClassTemplate->AddSpecialization(Decl, InsertPos);
4048 if (ClassTemplate->isOutOfLine())
4049 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
4052 if (Decl->getSpecializationKind() == TSK_Undeclared &&
4053 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
4054 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
4055 if (!Inst.isInvalid()) {
4056 MultiLevelTemplateArgumentList TemplateArgLists(Template,
4057 CanonicalConverted,
4058 /*Final=*/false);
4059 InstantiateAttrsForDecl(TemplateArgLists,
4060 ClassTemplate->getTemplatedDecl(), Decl);
4064 // Diagnose uses of this specialization.
4065 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
4067 CanonType = Context.getTypeDeclType(Decl);
4068 assert(isa<RecordType>(CanonType) &&
4069 "type of non-dependent specialization is not a RecordType");
4070 } else {
4071 llvm_unreachable("Unhandled template kind");
4074 // Build the fully-sugared type for this class template
4075 // specialization, which refers back to the class template
4076 // specialization we created or found.
4077 return Context.getTemplateSpecializationType(Name, TemplateArgs.arguments(),
4078 CanonType);
4081 void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName,
4082 TemplateNameKind &TNK,
4083 SourceLocation NameLoc,
4084 IdentifierInfo *&II) {
4085 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
4087 TemplateName Name = ParsedName.get();
4088 auto *ATN = Name.getAsAssumedTemplateName();
4089 assert(ATN && "not an assumed template name");
4090 II = ATN->getDeclName().getAsIdentifierInfo();
4092 if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) {
4093 // Resolved to a type template name.
4094 ParsedName = TemplateTy::make(Name);
4095 TNK = TNK_Type_template;
4099 bool Sema::resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
4100 SourceLocation NameLoc,
4101 bool Diagnose) {
4102 // We assumed this undeclared identifier to be an (ADL-only) function
4103 // template name, but it was used in a context where a type was required.
4104 // Try to typo-correct it now.
4105 AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName();
4106 assert(ATN && "not an assumed template name");
4108 LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName);
4109 struct CandidateCallback : CorrectionCandidateCallback {
4110 bool ValidateCandidate(const TypoCorrection &TC) override {
4111 return TC.getCorrectionDecl() &&
4112 getAsTypeTemplateDecl(TC.getCorrectionDecl());
4114 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4115 return std::make_unique<CandidateCallback>(*this);
4117 } FilterCCC;
4119 TypoCorrection Corrected =
4120 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
4121 FilterCCC, CTK_ErrorRecovery);
4122 if (Corrected && Corrected.getFoundDecl()) {
4123 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest)
4124 << ATN->getDeclName());
4125 Name = TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>());
4126 return false;
4129 if (Diagnose)
4130 Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName();
4131 return true;
4134 TypeResult Sema::ActOnTemplateIdType(
4135 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4136 TemplateTy TemplateD, IdentifierInfo *TemplateII,
4137 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
4138 ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc,
4139 bool IsCtorOrDtorName, bool IsClassName,
4140 ImplicitTypenameContext AllowImplicitTypename) {
4141 if (SS.isInvalid())
4142 return true;
4144 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
4145 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
4147 // C++ [temp.res]p3:
4148 // A qualified-id that refers to a type and in which the
4149 // nested-name-specifier depends on a template-parameter (14.6.2)
4150 // shall be prefixed by the keyword typename to indicate that the
4151 // qualified-id denotes a type, forming an
4152 // elaborated-type-specifier (7.1.5.3).
4153 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
4154 // C++2a relaxes some of those restrictions in [temp.res]p5.
4155 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
4156 if (getLangOpts().CPlusPlus20)
4157 Diag(SS.getBeginLoc(), diag::warn_cxx17_compat_implicit_typename);
4158 else
4159 Diag(SS.getBeginLoc(), diag::ext_implicit_typename)
4160 << SS.getScopeRep() << TemplateII->getName()
4161 << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename ");
4162 } else
4163 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
4164 << SS.getScopeRep() << TemplateII->getName();
4166 // FIXME: This is not quite correct recovery as we don't transform SS
4167 // into the corresponding dependent form (and we don't diagnose missing
4168 // 'template' keywords within SS as a result).
4169 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
4170 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
4171 TemplateArgsIn, RAngleLoc);
4174 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
4175 // it's not actually allowed to be used as a type in most cases. Because
4176 // we annotate it before we know whether it's valid, we have to check for
4177 // this case here.
4178 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
4179 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
4180 Diag(TemplateIILoc,
4181 TemplateKWLoc.isInvalid()
4182 ? diag::err_out_of_line_qualified_id_type_names_constructor
4183 : diag::ext_out_of_line_qualified_id_type_names_constructor)
4184 << TemplateII << 0 /*injected-class-name used as template name*/
4185 << 1 /*if any keyword was present, it was 'template'*/;
4189 TemplateName Template = TemplateD.get();
4190 if (Template.getAsAssumedTemplateName() &&
4191 resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc))
4192 return true;
4194 // Translate the parser's template argument list in our AST format.
4195 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4196 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4198 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
4199 assert(SS.getScopeRep() == DTN->getQualifier());
4200 QualType T = Context.getDependentTemplateSpecializationType(
4201 ElaboratedTypeKeyword::None, DTN->getQualifier(), DTN->getIdentifier(),
4202 TemplateArgs.arguments());
4203 // Build type-source information.
4204 TypeLocBuilder TLB;
4205 DependentTemplateSpecializationTypeLoc SpecTL
4206 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
4207 SpecTL.setElaboratedKeywordLoc(SourceLocation());
4208 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
4209 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4210 SpecTL.setTemplateNameLoc(TemplateIILoc);
4211 SpecTL.setLAngleLoc(LAngleLoc);
4212 SpecTL.setRAngleLoc(RAngleLoc);
4213 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
4214 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
4215 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
4218 QualType SpecTy = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
4219 if (SpecTy.isNull())
4220 return true;
4222 // Build type-source information.
4223 TypeLocBuilder TLB;
4224 TemplateSpecializationTypeLoc SpecTL =
4225 TLB.push<TemplateSpecializationTypeLoc>(SpecTy);
4226 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4227 SpecTL.setTemplateNameLoc(TemplateIILoc);
4228 SpecTL.setLAngleLoc(LAngleLoc);
4229 SpecTL.setRAngleLoc(RAngleLoc);
4230 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
4231 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
4233 // Create an elaborated-type-specifier containing the nested-name-specifier.
4234 QualType ElTy =
4235 getElaboratedType(ElaboratedTypeKeyword::None,
4236 !IsCtorOrDtorName ? SS : CXXScopeSpec(), SpecTy);
4237 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(ElTy);
4238 ElabTL.setElaboratedKeywordLoc(SourceLocation());
4239 if (!ElabTL.isEmpty())
4240 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
4241 return CreateParsedType(ElTy, TLB.getTypeSourceInfo(Context, ElTy));
4244 TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
4245 TypeSpecifierType TagSpec,
4246 SourceLocation TagLoc,
4247 CXXScopeSpec &SS,
4248 SourceLocation TemplateKWLoc,
4249 TemplateTy TemplateD,
4250 SourceLocation TemplateLoc,
4251 SourceLocation LAngleLoc,
4252 ASTTemplateArgsPtr TemplateArgsIn,
4253 SourceLocation RAngleLoc) {
4254 if (SS.isInvalid())
4255 return TypeResult(true);
4257 TemplateName Template = TemplateD.get();
4259 // Translate the parser's template argument list in our AST format.
4260 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4261 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4263 // Determine the tag kind
4264 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4265 ElaboratedTypeKeyword Keyword
4266 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
4268 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
4269 assert(SS.getScopeRep() == DTN->getQualifier());
4270 QualType T = Context.getDependentTemplateSpecializationType(
4271 Keyword, DTN->getQualifier(), DTN->getIdentifier(),
4272 TemplateArgs.arguments());
4274 // Build type-source information.
4275 TypeLocBuilder TLB;
4276 DependentTemplateSpecializationTypeLoc SpecTL
4277 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
4278 SpecTL.setElaboratedKeywordLoc(TagLoc);
4279 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
4280 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4281 SpecTL.setTemplateNameLoc(TemplateLoc);
4282 SpecTL.setLAngleLoc(LAngleLoc);
4283 SpecTL.setRAngleLoc(RAngleLoc);
4284 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
4285 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
4286 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
4289 if (TypeAliasTemplateDecl *TAT =
4290 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
4291 // C++0x [dcl.type.elab]p2:
4292 // If the identifier resolves to a typedef-name or the simple-template-id
4293 // resolves to an alias template specialization, the
4294 // elaborated-type-specifier is ill-formed.
4295 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
4296 << TAT << NTK_TypeAliasTemplate << llvm::to_underlying(TagKind);
4297 Diag(TAT->getLocation(), diag::note_declared_at);
4300 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
4301 if (Result.isNull())
4302 return TypeResult(true);
4304 // Check the tag kind
4305 if (const RecordType *RT = Result->getAs<RecordType>()) {
4306 RecordDecl *D = RT->getDecl();
4308 IdentifierInfo *Id = D->getIdentifier();
4309 assert(Id && "templated class must have an identifier");
4311 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
4312 TagLoc, Id)) {
4313 Diag(TagLoc, diag::err_use_with_wrong_tag)
4314 << Result
4315 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
4316 Diag(D->getLocation(), diag::note_previous_use);
4320 // Provide source-location information for the template specialization.
4321 TypeLocBuilder TLB;
4322 TemplateSpecializationTypeLoc SpecTL
4323 = TLB.push<TemplateSpecializationTypeLoc>(Result);
4324 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4325 SpecTL.setTemplateNameLoc(TemplateLoc);
4326 SpecTL.setLAngleLoc(LAngleLoc);
4327 SpecTL.setRAngleLoc(RAngleLoc);
4328 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
4329 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
4331 // Construct an elaborated type containing the nested-name-specifier (if any)
4332 // and tag keyword.
4333 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
4334 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
4335 ElabTL.setElaboratedKeywordLoc(TagLoc);
4336 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
4337 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
4340 static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
4341 NamedDecl *PrevDecl,
4342 SourceLocation Loc,
4343 bool IsPartialSpecialization);
4345 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
4347 static bool isTemplateArgumentTemplateParameter(
4348 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
4349 switch (Arg.getKind()) {
4350 case TemplateArgument::Null:
4351 case TemplateArgument::NullPtr:
4352 case TemplateArgument::Integral:
4353 case TemplateArgument::Declaration:
4354 case TemplateArgument::Pack:
4355 case TemplateArgument::TemplateExpansion:
4356 return false;
4358 case TemplateArgument::Type: {
4359 QualType Type = Arg.getAsType();
4360 const TemplateTypeParmType *TPT =
4361 Arg.getAsType()->getAs<TemplateTypeParmType>();
4362 return TPT && !Type.hasQualifiers() &&
4363 TPT->getDepth() == Depth && TPT->getIndex() == Index;
4366 case TemplateArgument::Expression: {
4367 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
4368 if (!DRE || !DRE->getDecl())
4369 return false;
4370 const NonTypeTemplateParmDecl *NTTP =
4371 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4372 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
4375 case TemplateArgument::Template:
4376 const TemplateTemplateParmDecl *TTP =
4377 dyn_cast_or_null<TemplateTemplateParmDecl>(
4378 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
4379 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
4381 llvm_unreachable("unexpected kind of template argument");
4384 static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
4385 ArrayRef<TemplateArgument> Args) {
4386 if (Params->size() != Args.size())
4387 return false;
4389 unsigned Depth = Params->getDepth();
4391 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4392 TemplateArgument Arg = Args[I];
4394 // If the parameter is a pack expansion, the argument must be a pack
4395 // whose only element is a pack expansion.
4396 if (Params->getParam(I)->isParameterPack()) {
4397 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4398 !Arg.pack_begin()->isPackExpansion())
4399 return false;
4400 Arg = Arg.pack_begin()->getPackExpansionPattern();
4403 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
4404 return false;
4407 return true;
4410 template<typename PartialSpecDecl>
4411 static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4412 if (Partial->getDeclContext()->isDependentContext())
4413 return;
4415 // FIXME: Get the TDK from deduction in order to provide better diagnostics
4416 // for non-substitution-failure issues?
4417 TemplateDeductionInfo Info(Partial->getLocation());
4418 if (S.isMoreSpecializedThanPrimary(Partial, Info))
4419 return;
4421 auto *Template = Partial->getSpecializedTemplate();
4422 S.Diag(Partial->getLocation(),
4423 diag::ext_partial_spec_not_more_specialized_than_primary)
4424 << isa<VarTemplateDecl>(Template);
4426 if (Info.hasSFINAEDiagnostic()) {
4427 PartialDiagnosticAt Diag = {SourceLocation(),
4428 PartialDiagnostic::NullDiagnostic()};
4429 Info.takeSFINAEDiagnostic(Diag);
4430 SmallString<128> SFINAEArgString;
4431 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
4432 S.Diag(Diag.first,
4433 diag::note_partial_spec_not_more_specialized_than_primary)
4434 << SFINAEArgString;
4437 S.Diag(Template->getLocation(), diag::note_template_decl_here);
4438 SmallVector<const Expr *, 3> PartialAC, TemplateAC;
4439 Template->getAssociatedConstraints(TemplateAC);
4440 Partial->getAssociatedConstraints(PartialAC);
4441 S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Partial, PartialAC, Template,
4442 TemplateAC);
4445 static void
4446 noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
4447 const llvm::SmallBitVector &DeducibleParams) {
4448 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4449 if (!DeducibleParams[I]) {
4450 NamedDecl *Param = TemplateParams->getParam(I);
4451 if (Param->getDeclName())
4452 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4453 << Param->getDeclName();
4454 else
4455 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4456 << "(anonymous)";
4462 template<typename PartialSpecDecl>
4463 static void checkTemplatePartialSpecialization(Sema &S,
4464 PartialSpecDecl *Partial) {
4465 // C++1z [temp.class.spec]p8: (DR1495)
4466 // - The specialization shall be more specialized than the primary
4467 // template (14.5.5.2).
4468 checkMoreSpecializedThanPrimary(S, Partial);
4470 // C++ [temp.class.spec]p8: (DR1315)
4471 // - Each template-parameter shall appear at least once in the
4472 // template-id outside a non-deduced context.
4473 // C++1z [temp.class.spec.match]p3 (P0127R2)
4474 // If the template arguments of a partial specialization cannot be
4475 // deduced because of the structure of its template-parameter-list
4476 // and the template-id, the program is ill-formed.
4477 auto *TemplateParams = Partial->getTemplateParameters();
4478 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4479 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4480 TemplateParams->getDepth(), DeducibleParams);
4482 if (!DeducibleParams.all()) {
4483 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4484 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4485 << isa<VarTemplatePartialSpecializationDecl>(Partial)
4486 << (NumNonDeducible > 1)
4487 << SourceRange(Partial->getLocation(),
4488 Partial->getTemplateArgsAsWritten()->RAngleLoc);
4489 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4493 void Sema::CheckTemplatePartialSpecialization(
4494 ClassTemplatePartialSpecializationDecl *Partial) {
4495 checkTemplatePartialSpecialization(*this, Partial);
4498 void Sema::CheckTemplatePartialSpecialization(
4499 VarTemplatePartialSpecializationDecl *Partial) {
4500 checkTemplatePartialSpecialization(*this, Partial);
4503 void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
4504 // C++1z [temp.param]p11:
4505 // A template parameter of a deduction guide template that does not have a
4506 // default-argument shall be deducible from the parameter-type-list of the
4507 // deduction guide template.
4508 auto *TemplateParams = TD->getTemplateParameters();
4509 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4510 MarkDeducedTemplateParameters(TD, DeducibleParams);
4511 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4512 // A parameter pack is deducible (to an empty pack).
4513 auto *Param = TemplateParams->getParam(I);
4514 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
4515 DeducibleParams[I] = true;
4518 if (!DeducibleParams.all()) {
4519 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4520 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
4521 << (NumNonDeducible > 1);
4522 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
4526 DeclResult Sema::ActOnVarTemplateSpecialization(
4527 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
4528 TemplateParameterList *TemplateParams, StorageClass SC,
4529 bool IsPartialSpecialization) {
4530 // D must be variable template id.
4531 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
4532 "Variable template specialization is declared with a template id.");
4534 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4535 TemplateArgumentListInfo TemplateArgs =
4536 makeTemplateArgumentListInfo(*this, *TemplateId);
4537 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4538 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4539 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4541 TemplateName Name = TemplateId->Template.get();
4543 // The template-id must name a variable template.
4544 VarTemplateDecl *VarTemplate =
4545 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
4546 if (!VarTemplate) {
4547 NamedDecl *FnTemplate;
4548 if (auto *OTS = Name.getAsOverloadedTemplate())
4549 FnTemplate = *OTS->begin();
4550 else
4551 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4552 if (FnTemplate)
4553 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
4554 << FnTemplate->getDeclName();
4555 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
4556 << IsPartialSpecialization;
4559 // Check for unexpanded parameter packs in any of the template arguments.
4560 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4561 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4562 UPPC_PartialSpecialization))
4563 return true;
4565 // Check that the template argument list is well-formed for this
4566 // template.
4567 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4568 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
4569 false, SugaredConverted, CanonicalConverted,
4570 /*UpdateArgsWithConversions=*/true))
4571 return true;
4573 // Find the variable template (partial) specialization declaration that
4574 // corresponds to these arguments.
4575 if (IsPartialSpecialization) {
4576 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
4577 TemplateArgs.size(),
4578 CanonicalConverted))
4579 return true;
4581 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
4582 // also do them during instantiation.
4583 if (!Name.isDependent() &&
4584 !TemplateSpecializationType::anyDependentTemplateArguments(
4585 TemplateArgs, CanonicalConverted)) {
4586 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4587 << VarTemplate->getDeclName();
4588 IsPartialSpecialization = false;
4591 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
4592 CanonicalConverted) &&
4593 (!Context.getLangOpts().CPlusPlus20 ||
4594 !TemplateParams->hasAssociatedConstraints())) {
4595 // C++ [temp.class.spec]p9b3:
4597 // -- The argument list of the specialization shall not be identical
4598 // to the implicit argument list of the primary template.
4599 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4600 << /*variable template*/ 1
4601 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
4602 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4603 // FIXME: Recover from this by treating the declaration as a redeclaration
4604 // of the primary template.
4605 return true;
4609 void *InsertPos = nullptr;
4610 VarTemplateSpecializationDecl *PrevDecl = nullptr;
4612 if (IsPartialSpecialization)
4613 PrevDecl = VarTemplate->findPartialSpecialization(
4614 CanonicalConverted, TemplateParams, InsertPos);
4615 else
4616 PrevDecl = VarTemplate->findSpecialization(CanonicalConverted, InsertPos);
4618 VarTemplateSpecializationDecl *Specialization = nullptr;
4620 // Check whether we can declare a variable template specialization in
4621 // the current scope.
4622 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
4623 TemplateNameLoc,
4624 IsPartialSpecialization))
4625 return true;
4627 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4628 // Since the only prior variable template specialization with these
4629 // arguments was referenced but not declared, reuse that
4630 // declaration node as our own, updating its source location and
4631 // the list of outer template parameters to reflect our new declaration.
4632 Specialization = PrevDecl;
4633 Specialization->setLocation(TemplateNameLoc);
4634 PrevDecl = nullptr;
4635 } else if (IsPartialSpecialization) {
4636 // Create a new class template partial specialization declaration node.
4637 VarTemplatePartialSpecializationDecl *PrevPartial =
4638 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
4639 VarTemplatePartialSpecializationDecl *Partial =
4640 VarTemplatePartialSpecializationDecl::Create(
4641 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
4642 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
4643 CanonicalConverted, TemplateArgs);
4645 if (!PrevPartial)
4646 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
4647 Specialization = Partial;
4649 // If we are providing an explicit specialization of a member variable
4650 // template specialization, make a note of that.
4651 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4652 PrevPartial->setMemberSpecialization();
4654 CheckTemplatePartialSpecialization(Partial);
4655 } else {
4656 // Create a new class template specialization declaration node for
4657 // this explicit specialization or friend declaration.
4658 Specialization = VarTemplateSpecializationDecl::Create(
4659 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4660 VarTemplate, DI->getType(), DI, SC, CanonicalConverted);
4661 Specialization->setTemplateArgsInfo(TemplateArgs);
4663 if (!PrevDecl)
4664 VarTemplate->AddSpecialization(Specialization, InsertPos);
4667 // C++ [temp.expl.spec]p6:
4668 // If a template, a member template or the member of a class template is
4669 // explicitly specialized then that specialization shall be declared
4670 // before the first use of that specialization that would cause an implicit
4671 // instantiation to take place, in every translation unit in which such a
4672 // use occurs; no diagnostic is required.
4673 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4674 bool Okay = false;
4675 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4676 // Is there any previous explicit specialization declaration?
4677 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
4678 Okay = true;
4679 break;
4683 if (!Okay) {
4684 SourceRange Range(TemplateNameLoc, RAngleLoc);
4685 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4686 << Name << Range;
4688 Diag(PrevDecl->getPointOfInstantiation(),
4689 diag::note_instantiation_required_here)
4690 << (PrevDecl->getTemplateSpecializationKind() !=
4691 TSK_ImplicitInstantiation);
4692 return true;
4696 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
4697 Specialization->setLexicalDeclContext(CurContext);
4699 // Add the specialization into its lexical context, so that it can
4700 // be seen when iterating through the list of declarations in that
4701 // context. However, specializations are not found by name lookup.
4702 CurContext->addDecl(Specialization);
4704 // Note that this is an explicit specialization.
4705 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4707 if (PrevDecl) {
4708 // Check that this isn't a redefinition of this specialization,
4709 // merging with previous declarations.
4710 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
4711 forRedeclarationInCurContext());
4712 PrevSpec.addDecl(PrevDecl);
4713 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
4714 } else if (Specialization->isStaticDataMember() &&
4715 Specialization->isOutOfLine()) {
4716 Specialization->setAccess(VarTemplate->getAccess());
4719 return Specialization;
4722 namespace {
4723 /// A partial specialization whose template arguments have matched
4724 /// a given template-id.
4725 struct PartialSpecMatchResult {
4726 VarTemplatePartialSpecializationDecl *Partial;
4727 TemplateArgumentList *Args;
4729 } // end anonymous namespace
4731 DeclResult
4732 Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
4733 SourceLocation TemplateNameLoc,
4734 const TemplateArgumentListInfo &TemplateArgs) {
4735 assert(Template && "A variable template id without template?");
4737 // Check that the template argument list is well-formed for this template.
4738 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4739 if (CheckTemplateArgumentList(
4740 Template, TemplateNameLoc,
4741 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
4742 SugaredConverted, CanonicalConverted,
4743 /*UpdateArgsWithConversions=*/true))
4744 return true;
4746 // Produce a placeholder value if the specialization is dependent.
4747 if (Template->getDeclContext()->isDependentContext() ||
4748 TemplateSpecializationType::anyDependentTemplateArguments(
4749 TemplateArgs, CanonicalConverted))
4750 return DeclResult();
4752 // Find the variable template specialization declaration that
4753 // corresponds to these arguments.
4754 void *InsertPos = nullptr;
4755 if (VarTemplateSpecializationDecl *Spec =
4756 Template->findSpecialization(CanonicalConverted, InsertPos)) {
4757 checkSpecializationReachability(TemplateNameLoc, Spec);
4758 // If we already have a variable template specialization, return it.
4759 return Spec;
4762 // This is the first time we have referenced this variable template
4763 // specialization. Create the canonical declaration and add it to
4764 // the set of specializations, based on the closest partial specialization
4765 // that it represents. That is,
4766 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4767 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
4768 CanonicalConverted);
4769 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
4770 bool AmbiguousPartialSpec = false;
4771 typedef PartialSpecMatchResult MatchResult;
4772 SmallVector<MatchResult, 4> Matched;
4773 SourceLocation PointOfInstantiation = TemplateNameLoc;
4774 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4775 /*ForTakingAddress=*/false);
4777 // 1. Attempt to find the closest partial specialization that this
4778 // specializes, if any.
4779 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4780 // Perhaps better after unification of DeduceTemplateArguments() and
4781 // getMoreSpecializedPartialSpecialization().
4782 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4783 Template->getPartialSpecializations(PartialSpecs);
4785 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
4786 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
4787 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4789 if (TemplateDeductionResult Result =
4790 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
4791 // Store the failed-deduction information for use in diagnostics, later.
4792 // TODO: Actually use the failed-deduction info?
4793 FailedCandidates.addCandidate().set(
4794 DeclAccessPair::make(Template, AS_public), Partial,
4795 MakeDeductionFailureInfo(Context, Result, Info));
4796 (void)Result;
4797 } else {
4798 Matched.push_back(PartialSpecMatchResult());
4799 Matched.back().Partial = Partial;
4800 Matched.back().Args = Info.takeCanonical();
4804 if (Matched.size() >= 1) {
4805 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4806 if (Matched.size() == 1) {
4807 // -- If exactly one matching specialization is found, the
4808 // instantiation is generated from that specialization.
4809 // We don't need to do anything for this.
4810 } else {
4811 // -- If more than one matching specialization is found, the
4812 // partial order rules (14.5.4.2) are used to determine
4813 // whether one of the specializations is more specialized
4814 // than the others. If none of the specializations is more
4815 // specialized than all of the other matching
4816 // specializations, then the use of the variable template is
4817 // ambiguous and the program is ill-formed.
4818 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4819 PEnd = Matched.end();
4820 P != PEnd; ++P) {
4821 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4822 PointOfInstantiation) ==
4823 P->Partial)
4824 Best = P;
4827 // Determine if the best partial specialization is more specialized than
4828 // the others.
4829 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4830 PEnd = Matched.end();
4831 P != PEnd; ++P) {
4832 if (P != Best && getMoreSpecializedPartialSpecialization(
4833 P->Partial, Best->Partial,
4834 PointOfInstantiation) != Best->Partial) {
4835 AmbiguousPartialSpec = true;
4836 break;
4841 // Instantiate using the best variable template partial specialization.
4842 InstantiationPattern = Best->Partial;
4843 InstantiationArgs = Best->Args;
4844 } else {
4845 // -- If no match is found, the instantiation is generated
4846 // from the primary template.
4847 // InstantiationPattern = Template->getTemplatedDecl();
4850 // 2. Create the canonical declaration.
4851 // Note that we do not instantiate a definition until we see an odr-use
4852 // in DoMarkVarDeclReferenced().
4853 // FIXME: LateAttrs et al.?
4854 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
4855 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
4856 CanonicalConverted, TemplateNameLoc /*, LateAttrs, StartingScope*/);
4857 if (!Decl)
4858 return true;
4860 if (AmbiguousPartialSpec) {
4861 // Partial ordering did not produce a clear winner. Complain.
4862 Decl->setInvalidDecl();
4863 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4864 << Decl;
4866 // Print the matching partial specializations.
4867 for (MatchResult P : Matched)
4868 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4869 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4870 *P.Args);
4871 return true;
4874 if (VarTemplatePartialSpecializationDecl *D =
4875 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4876 Decl->setInstantiationOf(D, InstantiationArgs);
4878 checkSpecializationReachability(TemplateNameLoc, Decl);
4880 assert(Decl && "No variable template specialization?");
4881 return Decl;
4884 ExprResult
4885 Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
4886 const DeclarationNameInfo &NameInfo,
4887 VarTemplateDecl *Template, SourceLocation TemplateLoc,
4888 const TemplateArgumentListInfo *TemplateArgs) {
4890 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4891 *TemplateArgs);
4892 if (Decl.isInvalid())
4893 return ExprError();
4895 if (!Decl.get())
4896 return ExprResult();
4898 VarDecl *Var = cast<VarDecl>(Decl.get());
4899 if (!Var->getTemplateSpecializationKind())
4900 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
4901 NameInfo.getLoc());
4903 // Build an ordinary singleton decl ref.
4904 return BuildDeclarationNameExpr(SS, NameInfo, Var,
4905 /*FoundD=*/nullptr, TemplateArgs);
4908 void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
4909 SourceLocation Loc) {
4910 Diag(Loc, diag::err_template_missing_args)
4911 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4912 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4913 Diag(TD->getLocation(), diag::note_template_decl_here)
4914 << TD->getTemplateParameters()->getSourceRange();
4918 ExprResult
4919 Sema::CheckConceptTemplateId(const CXXScopeSpec &SS,
4920 SourceLocation TemplateKWLoc,
4921 const DeclarationNameInfo &ConceptNameInfo,
4922 NamedDecl *FoundDecl,
4923 ConceptDecl *NamedConcept,
4924 const TemplateArgumentListInfo *TemplateArgs) {
4925 assert(NamedConcept && "A concept template id without a template?");
4927 llvm::SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4928 if (CheckTemplateArgumentList(
4929 NamedConcept, ConceptNameInfo.getLoc(),
4930 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4931 /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted,
4932 /*UpdateArgsWithConversions=*/false))
4933 return ExprError();
4935 auto *CSD = ImplicitConceptSpecializationDecl::Create(
4936 Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(),
4937 CanonicalConverted);
4938 ConstraintSatisfaction Satisfaction;
4939 bool AreArgsDependent =
4940 TemplateSpecializationType::anyDependentTemplateArguments(
4941 *TemplateArgs, CanonicalConverted);
4942 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CanonicalConverted,
4943 /*Final=*/false);
4944 LocalInstantiationScope Scope(*this);
4946 EnterExpressionEvaluationContext EECtx{
4947 *this, ExpressionEvaluationContext::ConstantEvaluated, CSD};
4949 if (!AreArgsDependent &&
4950 CheckConstraintSatisfaction(
4951 NamedConcept, {NamedConcept->getConstraintExpr()}, MLTAL,
4952 SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4953 TemplateArgs->getRAngleLoc()),
4954 Satisfaction))
4955 return ExprError();
4956 auto *CL = ConceptReference::Create(
4957 Context,
4958 SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc{},
4959 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
4960 ASTTemplateArgumentListInfo::Create(Context, *TemplateArgs));
4961 return ConceptSpecializationExpr::Create(
4962 Context, CL, CSD, AreArgsDependent ? nullptr : &Satisfaction);
4965 ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
4966 SourceLocation TemplateKWLoc,
4967 LookupResult &R,
4968 bool RequiresADL,
4969 const TemplateArgumentListInfo *TemplateArgs) {
4970 // FIXME: Can we do any checking at this point? I guess we could check the
4971 // template arguments that we have against the template name, if the template
4972 // name refers to a single template. That's not a terribly common case,
4973 // though.
4974 // foo<int> could identify a single function unambiguously
4975 // This approach does NOT work, since f<int>(1);
4976 // gets resolved prior to resorting to overload resolution
4977 // i.e., template<class T> void f(double);
4978 // vs template<class T, class U> void f(U);
4980 // These should be filtered out by our callers.
4981 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4983 // Non-function templates require a template argument list.
4984 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4985 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4986 diagnoseMissingTemplateArguments(TemplateName(TD), R.getNameLoc());
4987 return ExprError();
4990 bool KnownDependent = false;
4991 // In C++1y, check variable template ids.
4992 if (R.getAsSingle<VarTemplateDecl>()) {
4993 ExprResult Res = CheckVarTemplateId(SS, R.getLookupNameInfo(),
4994 R.getAsSingle<VarTemplateDecl>(),
4995 TemplateKWLoc, TemplateArgs);
4996 if (Res.isInvalid() || Res.isUsable())
4997 return Res;
4998 // Result is dependent. Carry on to build an UnresolvedLookupEpxr.
4999 KnownDependent = true;
5002 if (R.getAsSingle<ConceptDecl>()) {
5003 return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
5004 R.getFoundDecl(),
5005 R.getAsSingle<ConceptDecl>(), TemplateArgs);
5008 // We don't want lookup warnings at this point.
5009 R.suppressDiagnostics();
5011 UnresolvedLookupExpr *ULE = UnresolvedLookupExpr::Create(
5012 Context, R.getNamingClass(), SS.getWithLocInContext(Context),
5013 TemplateKWLoc, R.getLookupNameInfo(), RequiresADL, TemplateArgs,
5014 R.begin(), R.end(), KnownDependent);
5016 return ULE;
5019 // We actually only call this from template instantiation.
5020 ExprResult
5021 Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
5022 SourceLocation TemplateKWLoc,
5023 const DeclarationNameInfo &NameInfo,
5024 const TemplateArgumentListInfo *TemplateArgs) {
5026 assert(TemplateArgs || TemplateKWLoc.isValid());
5027 DeclContext *DC;
5028 if (!(DC = computeDeclContext(SS, false)) ||
5029 DC->isDependentContext() ||
5030 RequireCompleteDeclContext(SS, DC))
5031 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
5033 bool MemberOfUnknownSpecialization;
5034 LookupResult R(*this, NameInfo, LookupOrdinaryName);
5035 if (LookupTemplateName(R, (Scope *)nullptr, SS, QualType(),
5036 /*Entering*/false, MemberOfUnknownSpecialization,
5037 TemplateKWLoc))
5038 return ExprError();
5040 if (R.isAmbiguous())
5041 return ExprError();
5043 if (R.empty()) {
5044 Diag(NameInfo.getLoc(), diag::err_no_member)
5045 << NameInfo.getName() << DC << SS.getRange();
5046 return ExprError();
5049 auto DiagnoseTypeTemplateDecl = [&](TemplateDecl *Temp,
5050 bool isTypeAliasTemplateDecl) {
5051 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
5052 << SS.getScopeRep() << NameInfo.getName().getAsString() << SS.getRange()
5053 << isTypeAliasTemplateDecl;
5054 Diag(Temp->getLocation(), diag::note_referenced_type_template) << 0;
5055 return ExprError();
5058 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>())
5059 return DiagnoseTypeTemplateDecl(Temp, false);
5061 if (TypeAliasTemplateDecl *Temp = R.getAsSingle<TypeAliasTemplateDecl>())
5062 return DiagnoseTypeTemplateDecl(Temp, true);
5064 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
5067 /// Form a template name from a name that is syntactically required to name a
5068 /// template, either due to use of the 'template' keyword or because a name in
5069 /// this syntactic context is assumed to name a template (C++ [temp.names]p2-4).
5071 /// This action forms a template name given the name of the template and its
5072 /// optional scope specifier. This is used when the 'template' keyword is used
5073 /// or when the parsing context unambiguously treats a following '<' as
5074 /// introducing a template argument list. Note that this may produce a
5075 /// non-dependent template name if we can perform the lookup now and identify
5076 /// the named template.
5078 /// For example, given "x.MetaFun::template apply", the scope specifier
5079 /// \p SS will be "MetaFun::", \p TemplateKWLoc contains the location
5080 /// of the "template" keyword, and "apply" is the \p Name.
5081 TemplateNameKind Sema::ActOnTemplateName(Scope *S,
5082 CXXScopeSpec &SS,
5083 SourceLocation TemplateKWLoc,
5084 const UnqualifiedId &Name,
5085 ParsedType ObjectType,
5086 bool EnteringContext,
5087 TemplateTy &Result,
5088 bool AllowInjectedClassName) {
5089 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
5090 Diag(TemplateKWLoc,
5091 getLangOpts().CPlusPlus11 ?
5092 diag::warn_cxx98_compat_template_outside_of_template :
5093 diag::ext_template_outside_of_template)
5094 << FixItHint::CreateRemoval(TemplateKWLoc);
5096 if (SS.isInvalid())
5097 return TNK_Non_template;
5099 // Figure out where isTemplateName is going to look.
5100 DeclContext *LookupCtx = nullptr;
5101 if (SS.isNotEmpty())
5102 LookupCtx = computeDeclContext(SS, EnteringContext);
5103 else if (ObjectType)
5104 LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));
5106 // C++0x [temp.names]p5:
5107 // If a name prefixed by the keyword template is not the name of
5108 // a template, the program is ill-formed. [Note: the keyword
5109 // template may not be applied to non-template members of class
5110 // templates. -end note ] [ Note: as is the case with the
5111 // typename prefix, the template prefix is allowed in cases
5112 // where it is not strictly necessary; i.e., when the
5113 // nested-name-specifier or the expression on the left of the ->
5114 // or . is not dependent on a template-parameter, or the use
5115 // does not appear in the scope of a template. -end note]
5117 // Note: C++03 was more strict here, because it banned the use of
5118 // the "template" keyword prior to a template-name that was not a
5119 // dependent name. C++ DR468 relaxed this requirement (the
5120 // "template" keyword is now permitted). We follow the C++0x
5121 // rules, even in C++03 mode with a warning, retroactively applying the DR.
5122 bool MemberOfUnknownSpecialization;
5123 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
5124 ObjectType, EnteringContext, Result,
5125 MemberOfUnknownSpecialization);
5126 if (TNK != TNK_Non_template) {
5127 // We resolved this to a (non-dependent) template name. Return it.
5128 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
5129 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
5130 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
5131 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
5132 // C++14 [class.qual]p2:
5133 // In a lookup in which function names are not ignored and the
5134 // nested-name-specifier nominates a class C, if the name specified
5135 // [...] is the injected-class-name of C, [...] the name is instead
5136 // considered to name the constructor
5138 // We don't get here if naming the constructor would be valid, so we
5139 // just reject immediately and recover by treating the
5140 // injected-class-name as naming the template.
5141 Diag(Name.getBeginLoc(),
5142 diag::ext_out_of_line_qualified_id_type_names_constructor)
5143 << Name.Identifier
5144 << 0 /*injected-class-name used as template name*/
5145 << TemplateKWLoc.isValid();
5147 return TNK;
5150 if (!MemberOfUnknownSpecialization) {
5151 // Didn't find a template name, and the lookup wasn't dependent.
5152 // Do the lookup again to determine if this is a "nothing found" case or
5153 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
5154 // need to do this.
5155 DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
5156 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
5157 LookupOrdinaryName);
5158 bool MOUS;
5159 // Tell LookupTemplateName that we require a template so that it diagnoses
5160 // cases where it finds a non-template.
5161 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
5162 ? RequiredTemplateKind(TemplateKWLoc)
5163 : TemplateNameIsRequired;
5164 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, MOUS,
5165 RTK, nullptr, /*AllowTypoCorrection=*/false) &&
5166 !R.isAmbiguous()) {
5167 if (LookupCtx)
5168 Diag(Name.getBeginLoc(), diag::err_no_member)
5169 << DNI.getName() << LookupCtx << SS.getRange();
5170 else
5171 Diag(Name.getBeginLoc(), diag::err_undeclared_use)
5172 << DNI.getName() << SS.getRange();
5174 return TNK_Non_template;
5177 NestedNameSpecifier *Qualifier = SS.getScopeRep();
5179 switch (Name.getKind()) {
5180 case UnqualifiedIdKind::IK_Identifier:
5181 Result = TemplateTy::make(
5182 Context.getDependentTemplateName(Qualifier, Name.Identifier));
5183 return TNK_Dependent_template_name;
5185 case UnqualifiedIdKind::IK_OperatorFunctionId:
5186 Result = TemplateTy::make(Context.getDependentTemplateName(
5187 Qualifier, Name.OperatorFunctionId.Operator));
5188 return TNK_Function_template;
5190 case UnqualifiedIdKind::IK_LiteralOperatorId:
5191 // This is a kind of template name, but can never occur in a dependent
5192 // scope (literal operators can only be declared at namespace scope).
5193 break;
5195 default:
5196 break;
5199 // This name cannot possibly name a dependent template. Diagnose this now
5200 // rather than building a dependent template name that can never be valid.
5201 Diag(Name.getBeginLoc(),
5202 diag::err_template_kw_refers_to_dependent_non_template)
5203 << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
5204 << TemplateKWLoc.isValid() << TemplateKWLoc;
5205 return TNK_Non_template;
5208 bool Sema::CheckTemplateTypeArgument(
5209 TemplateTypeParmDecl *Param, TemplateArgumentLoc &AL,
5210 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5211 SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
5212 const TemplateArgument &Arg = AL.getArgument();
5213 QualType ArgType;
5214 TypeSourceInfo *TSI = nullptr;
5216 // Check template type parameter.
5217 switch(Arg.getKind()) {
5218 case TemplateArgument::Type:
5219 // C++ [temp.arg.type]p1:
5220 // A template-argument for a template-parameter which is a
5221 // type shall be a type-id.
5222 ArgType = Arg.getAsType();
5223 TSI = AL.getTypeSourceInfo();
5224 break;
5225 case TemplateArgument::Template:
5226 case TemplateArgument::TemplateExpansion: {
5227 // We have a template type parameter but the template argument
5228 // is a template without any arguments.
5229 SourceRange SR = AL.getSourceRange();
5230 TemplateName Name = Arg.getAsTemplateOrTemplatePattern();
5231 diagnoseMissingTemplateArguments(Name, SR.getEnd());
5232 return true;
5234 case TemplateArgument::Expression: {
5235 // We have a template type parameter but the template argument is an
5236 // expression; see if maybe it is missing the "typename" keyword.
5237 CXXScopeSpec SS;
5238 DeclarationNameInfo NameInfo;
5240 if (DependentScopeDeclRefExpr *ArgExpr =
5241 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
5242 SS.Adopt(ArgExpr->getQualifierLoc());
5243 NameInfo = ArgExpr->getNameInfo();
5244 } else if (CXXDependentScopeMemberExpr *ArgExpr =
5245 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
5246 if (ArgExpr->isImplicitAccess()) {
5247 SS.Adopt(ArgExpr->getQualifierLoc());
5248 NameInfo = ArgExpr->getMemberNameInfo();
5252 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
5253 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
5254 LookupParsedName(Result, CurScope, &SS);
5256 if (Result.getAsSingle<TypeDecl>() ||
5257 Result.getResultKind() ==
5258 LookupResult::NotFoundInCurrentInstantiation) {
5259 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
5260 // Suggest that the user add 'typename' before the NNS.
5261 SourceLocation Loc = AL.getSourceRange().getBegin();
5262 Diag(Loc, getLangOpts().MSVCCompat
5263 ? diag::ext_ms_template_type_arg_missing_typename
5264 : diag::err_template_arg_must_be_type_suggest)
5265 << FixItHint::CreateInsertion(Loc, "typename ");
5266 Diag(Param->getLocation(), diag::note_template_param_here);
5268 // Recover by synthesizing a type using the location information that we
5269 // already have.
5270 ArgType = Context.getDependentNameType(ElaboratedTypeKeyword::Typename,
5271 SS.getScopeRep(), II);
5272 TypeLocBuilder TLB;
5273 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
5274 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
5275 TL.setQualifierLoc(SS.getWithLocInContext(Context));
5276 TL.setNameLoc(NameInfo.getLoc());
5277 TSI = TLB.getTypeSourceInfo(Context, ArgType);
5279 // Overwrite our input TemplateArgumentLoc so that we can recover
5280 // properly.
5281 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
5282 TemplateArgumentLocInfo(TSI));
5284 break;
5287 // fallthrough
5288 [[fallthrough]];
5290 default: {
5291 // We have a template type parameter but the template argument
5292 // is not a type.
5293 SourceRange SR = AL.getSourceRange();
5294 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
5295 Diag(Param->getLocation(), diag::note_template_param_here);
5297 return true;
5301 if (CheckTemplateArgument(TSI))
5302 return true;
5304 // Objective-C ARC:
5305 // If an explicitly-specified template argument type is a lifetime type
5306 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
5307 if (getLangOpts().ObjCAutoRefCount &&
5308 ArgType->isObjCLifetimeType() &&
5309 !ArgType.getObjCLifetime()) {
5310 Qualifiers Qs;
5311 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
5312 ArgType = Context.getQualifiedType(ArgType, Qs);
5315 SugaredConverted.push_back(TemplateArgument(ArgType));
5316 CanonicalConverted.push_back(
5317 TemplateArgument(Context.getCanonicalType(ArgType)));
5318 return false;
5321 /// Substitute template arguments into the default template argument for
5322 /// the given template type parameter.
5324 /// \param SemaRef the semantic analysis object for which we are performing
5325 /// the substitution.
5327 /// \param Template the template that we are synthesizing template arguments
5328 /// for.
5330 /// \param TemplateLoc the location of the template name that started the
5331 /// template-id we are checking.
5333 /// \param RAngleLoc the location of the right angle bracket ('>') that
5334 /// terminates the template-id.
5336 /// \param Param the template template parameter whose default we are
5337 /// substituting into.
5339 /// \param Converted the list of template arguments provided for template
5340 /// parameters that precede \p Param in the template parameter list.
5341 /// \returns the substituted template argument, or NULL if an error occurred.
5342 static TypeSourceInfo *SubstDefaultTemplateArgument(
5343 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5344 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
5345 ArrayRef<TemplateArgument> SugaredConverted,
5346 ArrayRef<TemplateArgument> CanonicalConverted) {
5347 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
5349 // If the argument type is dependent, instantiate it now based
5350 // on the previously-computed template arguments.
5351 if (ArgType->getType()->isInstantiationDependentType()) {
5352 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5353 SugaredConverted,
5354 SourceRange(TemplateLoc, RAngleLoc));
5355 if (Inst.isInvalid())
5356 return nullptr;
5358 // Only substitute for the innermost template argument list.
5359 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5360 /*Final=*/true);
5361 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5362 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5364 bool ForLambdaCallOperator = false;
5365 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext()))
5366 ForLambdaCallOperator = Rec->isLambda();
5367 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
5368 !ForLambdaCallOperator);
5369 ArgType =
5370 SemaRef.SubstType(ArgType, TemplateArgLists,
5371 Param->getDefaultArgumentLoc(), Param->getDeclName());
5374 return ArgType;
5377 /// Substitute template arguments into the default template argument for
5378 /// the given non-type template parameter.
5380 /// \param SemaRef the semantic analysis object for which we are performing
5381 /// the substitution.
5383 /// \param Template the template that we are synthesizing template arguments
5384 /// for.
5386 /// \param TemplateLoc the location of the template name that started the
5387 /// template-id we are checking.
5389 /// \param RAngleLoc the location of the right angle bracket ('>') that
5390 /// terminates the template-id.
5392 /// \param Param the non-type template parameter whose default we are
5393 /// substituting into.
5395 /// \param Converted the list of template arguments provided for template
5396 /// parameters that precede \p Param in the template parameter list.
5398 /// \returns the substituted template argument, or NULL if an error occurred.
5399 static ExprResult SubstDefaultTemplateArgument(
5400 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5401 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5402 ArrayRef<TemplateArgument> SugaredConverted,
5403 ArrayRef<TemplateArgument> CanonicalConverted) {
5404 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5405 SugaredConverted,
5406 SourceRange(TemplateLoc, RAngleLoc));
5407 if (Inst.isInvalid())
5408 return ExprError();
5410 // Only substitute for the innermost template argument list.
5411 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5412 /*Final=*/true);
5413 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5414 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5416 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5417 EnterExpressionEvaluationContext ConstantEvaluated(
5418 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5419 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
5422 /// Substitute template arguments into the default template argument for
5423 /// the given template template parameter.
5425 /// \param SemaRef the semantic analysis object for which we are performing
5426 /// the substitution.
5428 /// \param Template the template that we are synthesizing template arguments
5429 /// for.
5431 /// \param TemplateLoc the location of the template name that started the
5432 /// template-id we are checking.
5434 /// \param RAngleLoc the location of the right angle bracket ('>') that
5435 /// terminates the template-id.
5437 /// \param Param the template template parameter whose default we are
5438 /// substituting into.
5440 /// \param Converted the list of template arguments provided for template
5441 /// parameters that precede \p Param in the template parameter list.
5443 /// \param QualifierLoc Will be set to the nested-name-specifier (with
5444 /// source-location information) that precedes the template name.
5446 /// \returns the substituted template argument, or NULL if an error occurred.
5447 static TemplateName SubstDefaultTemplateArgument(
5448 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5449 SourceLocation RAngleLoc, TemplateTemplateParmDecl *Param,
5450 ArrayRef<TemplateArgument> SugaredConverted,
5451 ArrayRef<TemplateArgument> CanonicalConverted,
5452 NestedNameSpecifierLoc &QualifierLoc) {
5453 Sema::InstantiatingTemplate Inst(
5454 SemaRef, TemplateLoc, TemplateParameter(Param), Template,
5455 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
5456 if (Inst.isInvalid())
5457 return TemplateName();
5459 // Only substitute for the innermost template argument list.
5460 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5461 /*Final=*/true);
5462 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5463 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5465 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5466 // Substitute into the nested-name-specifier first,
5467 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
5468 if (QualifierLoc) {
5469 QualifierLoc =
5470 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
5471 if (!QualifierLoc)
5472 return TemplateName();
5475 return SemaRef.SubstTemplateName(
5476 QualifierLoc,
5477 Param->getDefaultArgument().getArgument().getAsTemplate(),
5478 Param->getDefaultArgument().getTemplateNameLoc(),
5479 TemplateArgLists);
5482 /// If the given template parameter has a default template
5483 /// argument, substitute into that default template argument and
5484 /// return the corresponding template argument.
5485 TemplateArgumentLoc Sema::SubstDefaultTemplateArgumentIfAvailable(
5486 TemplateDecl *Template, SourceLocation TemplateLoc,
5487 SourceLocation RAngleLoc, Decl *Param,
5488 ArrayRef<TemplateArgument> SugaredConverted,
5489 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
5490 HasDefaultArg = false;
5492 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
5493 if (!hasReachableDefaultArgument(TypeParm))
5494 return TemplateArgumentLoc();
5496 HasDefaultArg = true;
5497 TypeSourceInfo *DI = SubstDefaultTemplateArgument(
5498 *this, Template, TemplateLoc, RAngleLoc, TypeParm, SugaredConverted,
5499 CanonicalConverted);
5500 if (DI)
5501 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
5503 return TemplateArgumentLoc();
5506 if (NonTypeTemplateParmDecl *NonTypeParm
5507 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5508 if (!hasReachableDefaultArgument(NonTypeParm))
5509 return TemplateArgumentLoc();
5511 HasDefaultArg = true;
5512 ExprResult Arg = SubstDefaultTemplateArgument(
5513 *this, Template, TemplateLoc, RAngleLoc, NonTypeParm, SugaredConverted,
5514 CanonicalConverted);
5515 if (Arg.isInvalid())
5516 return TemplateArgumentLoc();
5518 Expr *ArgE = Arg.getAs<Expr>();
5519 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
5522 TemplateTemplateParmDecl *TempTempParm
5523 = cast<TemplateTemplateParmDecl>(Param);
5524 if (!hasReachableDefaultArgument(TempTempParm))
5525 return TemplateArgumentLoc();
5527 HasDefaultArg = true;
5528 NestedNameSpecifierLoc QualifierLoc;
5529 TemplateName TName = SubstDefaultTemplateArgument(
5530 *this, Template, TemplateLoc, RAngleLoc, TempTempParm, SugaredConverted,
5531 CanonicalConverted, QualifierLoc);
5532 if (TName.isNull())
5533 return TemplateArgumentLoc();
5535 return TemplateArgumentLoc(
5536 Context, TemplateArgument(TName),
5537 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
5538 TempTempParm->getDefaultArgument().getTemplateNameLoc());
5541 /// Convert a template-argument that we parsed as a type into a template, if
5542 /// possible. C++ permits injected-class-names to perform dual service as
5543 /// template template arguments and as template type arguments.
5544 static TemplateArgumentLoc
5545 convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc) {
5546 // Extract and step over any surrounding nested-name-specifier.
5547 NestedNameSpecifierLoc QualLoc;
5548 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
5549 if (ETLoc.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None)
5550 return TemplateArgumentLoc();
5552 QualLoc = ETLoc.getQualifierLoc();
5553 TLoc = ETLoc.getNamedTypeLoc();
5555 // If this type was written as an injected-class-name, it can be used as a
5556 // template template argument.
5557 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
5558 return TemplateArgumentLoc(Context, InjLoc.getTypePtr()->getTemplateName(),
5559 QualLoc, InjLoc.getNameLoc());
5561 // If this type was written as an injected-class-name, it may have been
5562 // converted to a RecordType during instantiation. If the RecordType is
5563 // *not* wrapped in a TemplateSpecializationType and denotes a class
5564 // template specialization, it must have come from an injected-class-name.
5565 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
5566 if (auto *CTSD =
5567 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
5568 return TemplateArgumentLoc(Context,
5569 TemplateName(CTSD->getSpecializedTemplate()),
5570 QualLoc, RecLoc.getNameLoc());
5572 return TemplateArgumentLoc();
5575 /// Check that the given template argument corresponds to the given
5576 /// template parameter.
5578 /// \param Param The template parameter against which the argument will be
5579 /// checked.
5581 /// \param Arg The template argument, which may be updated due to conversions.
5583 /// \param Template The template in which the template argument resides.
5585 /// \param TemplateLoc The location of the template name for the template
5586 /// whose argument list we're matching.
5588 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
5589 /// the template argument list.
5591 /// \param ArgumentPackIndex The index into the argument pack where this
5592 /// argument will be placed. Only valid if the parameter is a parameter pack.
5594 /// \param Converted The checked, converted argument will be added to the
5595 /// end of this small vector.
5597 /// \param CTAK Describes how we arrived at this particular template argument:
5598 /// explicitly written, deduced, etc.
5600 /// \returns true on error, false otherwise.
5601 bool Sema::CheckTemplateArgument(
5602 NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template,
5603 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
5604 unsigned ArgumentPackIndex,
5605 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5606 SmallVectorImpl<TemplateArgument> &CanonicalConverted,
5607 CheckTemplateArgumentKind CTAK) {
5608 // Check template type parameters.
5609 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5610 return CheckTemplateTypeArgument(TTP, Arg, SugaredConverted,
5611 CanonicalConverted);
5613 // Check non-type template parameters.
5614 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5615 // Do substitution on the type of the non-type template parameter
5616 // with the template arguments we've seen thus far. But if the
5617 // template has a dependent context then we cannot substitute yet.
5618 QualType NTTPType = NTTP->getType();
5619 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5620 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
5622 if (NTTPType->isInstantiationDependentType() &&
5623 !isa<TemplateTemplateParmDecl>(Template) &&
5624 !Template->getDeclContext()->isDependentContext()) {
5625 // Do substitution on the type of the non-type template parameter.
5626 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5627 SugaredConverted,
5628 SourceRange(TemplateLoc, RAngleLoc));
5629 if (Inst.isInvalid())
5630 return true;
5632 MultiLevelTemplateArgumentList MLTAL(Template, SugaredConverted,
5633 /*Final=*/true);
5634 // If the parameter is a pack expansion, expand this slice of the pack.
5635 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5636 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this,
5637 ArgumentPackIndex);
5638 NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(),
5639 NTTP->getDeclName());
5640 } else {
5641 NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(),
5642 NTTP->getDeclName());
5645 // If that worked, check the non-type template parameter type
5646 // for validity.
5647 if (!NTTPType.isNull())
5648 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
5649 NTTP->getLocation());
5650 if (NTTPType.isNull())
5651 return true;
5654 switch (Arg.getArgument().getKind()) {
5655 case TemplateArgument::Null:
5656 llvm_unreachable("Should never see a NULL template argument here");
5658 case TemplateArgument::Expression: {
5659 Expr *E = Arg.getArgument().getAsExpr();
5660 TemplateArgument SugaredResult, CanonicalResult;
5661 unsigned CurSFINAEErrors = NumSFINAEErrors;
5662 ExprResult Res = CheckTemplateArgument(NTTP, NTTPType, E, SugaredResult,
5663 CanonicalResult, CTAK);
5664 if (Res.isInvalid())
5665 return true;
5666 // If the current template argument causes an error, give up now.
5667 if (CurSFINAEErrors < NumSFINAEErrors)
5668 return true;
5670 // If the resulting expression is new, then use it in place of the
5671 // old expression in the template argument.
5672 if (Res.get() != E) {
5673 TemplateArgument TA(Res.get());
5674 Arg = TemplateArgumentLoc(TA, Res.get());
5677 SugaredConverted.push_back(SugaredResult);
5678 CanonicalConverted.push_back(CanonicalResult);
5679 break;
5682 case TemplateArgument::Declaration:
5683 case TemplateArgument::Integral:
5684 case TemplateArgument::NullPtr:
5685 // We've already checked this template argument, so just copy
5686 // it to the list of converted arguments.
5687 SugaredConverted.push_back(Arg.getArgument());
5688 CanonicalConverted.push_back(
5689 Context.getCanonicalTemplateArgument(Arg.getArgument()));
5690 break;
5692 case TemplateArgument::Template:
5693 case TemplateArgument::TemplateExpansion:
5694 // We were given a template template argument. It may not be ill-formed;
5695 // see below.
5696 if (DependentTemplateName *DTN
5697 = Arg.getArgument().getAsTemplateOrTemplatePattern()
5698 .getAsDependentTemplateName()) {
5699 // We have a template argument such as \c T::template X, which we
5700 // parsed as a template template argument. However, since we now
5701 // know that we need a non-type template argument, convert this
5702 // template name into an expression.
5704 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
5705 Arg.getTemplateNameLoc());
5707 CXXScopeSpec SS;
5708 SS.Adopt(Arg.getTemplateQualifierLoc());
5709 // FIXME: the template-template arg was a DependentTemplateName,
5710 // so it was provided with a template keyword. However, its source
5711 // location is not stored in the template argument structure.
5712 SourceLocation TemplateKWLoc;
5713 ExprResult E = DependentScopeDeclRefExpr::Create(
5714 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5715 nullptr);
5717 // If we parsed the template argument as a pack expansion, create a
5718 // pack expansion expression.
5719 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
5720 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
5721 if (E.isInvalid())
5722 return true;
5725 TemplateArgument SugaredResult, CanonicalResult;
5726 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), SugaredResult,
5727 CanonicalResult, CTAK_Specified);
5728 if (E.isInvalid())
5729 return true;
5731 SugaredConverted.push_back(SugaredResult);
5732 CanonicalConverted.push_back(CanonicalResult);
5733 break;
5736 // We have a template argument that actually does refer to a class
5737 // template, alias template, or template template parameter, and
5738 // therefore cannot be a non-type template argument.
5739 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
5740 << Arg.getSourceRange();
5742 Diag(Param->getLocation(), diag::note_template_param_here);
5743 return true;
5745 case TemplateArgument::Type: {
5746 // We have a non-type template parameter but the template
5747 // argument is a type.
5749 // C++ [temp.arg]p2:
5750 // In a template-argument, an ambiguity between a type-id and
5751 // an expression is resolved to a type-id, regardless of the
5752 // form of the corresponding template-parameter.
5754 // We warn specifically about this case, since it can be rather
5755 // confusing for users.
5756 QualType T = Arg.getArgument().getAsType();
5757 SourceRange SR = Arg.getSourceRange();
5758 if (T->isFunctionType())
5759 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5760 else
5761 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5762 Diag(Param->getLocation(), diag::note_template_param_here);
5763 return true;
5766 case TemplateArgument::Pack:
5767 llvm_unreachable("Caller must expand template argument packs");
5770 return false;
5774 // Check template template parameters.
5775 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
5777 TemplateParameterList *Params = TempParm->getTemplateParameters();
5778 if (TempParm->isExpandedParameterPack())
5779 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5781 // Substitute into the template parameter list of the template
5782 // template parameter, since previously-supplied template arguments
5783 // may appear within the template template parameter.
5785 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5787 // Set up a template instantiation context.
5788 LocalInstantiationScope Scope(*this);
5789 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5790 SugaredConverted,
5791 SourceRange(TemplateLoc, RAngleLoc));
5792 if (Inst.isInvalid())
5793 return true;
5795 Params =
5796 SubstTemplateParams(Params, CurContext,
5797 MultiLevelTemplateArgumentList(
5798 Template, SugaredConverted, /*Final=*/true),
5799 /*EvaluateConstraints=*/false);
5800 if (!Params)
5801 return true;
5804 // C++1z [temp.local]p1: (DR1004)
5805 // When [the injected-class-name] is used [...] as a template-argument for
5806 // a template template-parameter [...] it refers to the class template
5807 // itself.
5808 if (Arg.getArgument().getKind() == TemplateArgument::Type) {
5809 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
5810 Context, Arg.getTypeSourceInfo()->getTypeLoc());
5811 if (!ConvertedArg.getArgument().isNull())
5812 Arg = ConvertedArg;
5815 switch (Arg.getArgument().getKind()) {
5816 case TemplateArgument::Null:
5817 llvm_unreachable("Should never see a NULL template argument here");
5819 case TemplateArgument::Template:
5820 case TemplateArgument::TemplateExpansion:
5821 if (CheckTemplateTemplateArgument(TempParm, Params, Arg))
5822 return true;
5824 SugaredConverted.push_back(Arg.getArgument());
5825 CanonicalConverted.push_back(
5826 Context.getCanonicalTemplateArgument(Arg.getArgument()));
5827 break;
5829 case TemplateArgument::Expression:
5830 case TemplateArgument::Type:
5831 // We have a template template parameter but the template
5832 // argument does not refer to a template.
5833 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
5834 << getLangOpts().CPlusPlus11;
5835 return true;
5837 case TemplateArgument::Declaration:
5838 llvm_unreachable("Declaration argument with template template parameter");
5839 case TemplateArgument::Integral:
5840 llvm_unreachable("Integral argument with template template parameter");
5841 case TemplateArgument::NullPtr:
5842 llvm_unreachable("Null pointer argument with template template parameter");
5844 case TemplateArgument::Pack:
5845 llvm_unreachable("Caller must expand template argument packs");
5848 return false;
5851 /// Diagnose a missing template argument.
5852 template<typename TemplateParmDecl>
5853 static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
5854 TemplateDecl *TD,
5855 const TemplateParmDecl *D,
5856 TemplateArgumentListInfo &Args) {
5857 // Dig out the most recent declaration of the template parameter; there may be
5858 // declarations of the template that are more recent than TD.
5859 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
5860 ->getTemplateParameters()
5861 ->getParam(D->getIndex()));
5863 // If there's a default argument that's not reachable, diagnose that we're
5864 // missing a module import.
5865 llvm::SmallVector<Module*, 8> Modules;
5866 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, &Modules)) {
5867 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
5868 D->getDefaultArgumentLoc(), Modules,
5869 Sema::MissingImportKind::DefaultArgument,
5870 /*Recover*/true);
5871 return true;
5874 // FIXME: If there's a more recent default argument that *is* visible,
5875 // diagnose that it was declared too late.
5877 TemplateParameterList *Params = TD->getTemplateParameters();
5879 S.Diag(Loc, diag::err_template_arg_list_different_arity)
5880 << /*not enough args*/0
5881 << (int)S.getTemplateNameKindForDiagnostics(TemplateName(TD))
5882 << TD;
5883 S.Diag(TD->getLocation(), diag::note_template_decl_here)
5884 << Params->getSourceRange();
5885 return true;
5888 /// Check that the given template argument list is well-formed
5889 /// for specializing the given template.
5890 bool Sema::CheckTemplateArgumentList(
5891 TemplateDecl *Template, SourceLocation TemplateLoc,
5892 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
5893 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5894 SmallVectorImpl<TemplateArgument> &CanonicalConverted,
5895 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
5897 if (ConstraintsNotSatisfied)
5898 *ConstraintsNotSatisfied = false;
5900 // Make a copy of the template arguments for processing. Only make the
5901 // changes at the end when successful in matching the arguments to the
5902 // template.
5903 TemplateArgumentListInfo NewArgs = TemplateArgs;
5905 // Make sure we get the template parameter list from the most
5906 // recent declaration, since that is the only one that is guaranteed to
5907 // have all the default template argument information.
5908 TemplateParameterList *Params =
5909 cast<TemplateDecl>(Template->getMostRecentDecl())
5910 ->getTemplateParameters();
5912 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5914 // C++ [temp.arg]p1:
5915 // [...] The type and form of each template-argument specified in
5916 // a template-id shall match the type and form specified for the
5917 // corresponding parameter declared by the template in its
5918 // template-parameter-list.
5919 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
5920 SmallVector<TemplateArgument, 2> SugaredArgumentPack;
5921 SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
5922 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5923 LocalInstantiationScope InstScope(*this, true);
5924 for (TemplateParameterList::iterator Param = Params->begin(),
5925 ParamEnd = Params->end();
5926 Param != ParamEnd; /* increment in loop */) {
5927 // If we have an expanded parameter pack, make sure we don't have too
5928 // many arguments.
5929 if (std::optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
5930 if (*Expansions == SugaredArgumentPack.size()) {
5931 // We're done with this parameter pack. Pack up its arguments and add
5932 // them to the list.
5933 SugaredConverted.push_back(
5934 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5935 SugaredArgumentPack.clear();
5937 CanonicalConverted.push_back(
5938 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5939 CanonicalArgumentPack.clear();
5941 // This argument is assigned to the next parameter.
5942 ++Param;
5943 continue;
5944 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5945 // Not enough arguments for this parameter pack.
5946 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5947 << /*not enough args*/0
5948 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
5949 << Template;
5950 Diag(Template->getLocation(), diag::note_template_decl_here)
5951 << Params->getSourceRange();
5952 return true;
5956 if (ArgIdx < NumArgs) {
5957 // Check the template argument we were given.
5958 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template, TemplateLoc,
5959 RAngleLoc, SugaredArgumentPack.size(),
5960 SugaredConverted, CanonicalConverted,
5961 CTAK_Specified))
5962 return true;
5964 CanonicalConverted.back().setIsDefaulted(
5965 clang::isSubstitutedDefaultArgument(
5966 Context, NewArgs[ArgIdx].getArgument(), *Param,
5967 CanonicalConverted, Params->getDepth()));
5969 bool PackExpansionIntoNonPack =
5970 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
5971 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
5972 if (PackExpansionIntoNonPack && (isa<TypeAliasTemplateDecl>(Template) ||
5973 isa<ConceptDecl>(Template))) {
5974 // Core issue 1430: we have a pack expansion as an argument to an
5975 // alias template, and it's not part of a parameter pack. This
5976 // can't be canonicalized, so reject it now.
5977 // As for concepts - we cannot normalize constraints where this
5978 // situation exists.
5979 Diag(NewArgs[ArgIdx].getLocation(),
5980 diag::err_template_expansion_into_fixed_list)
5981 << (isa<ConceptDecl>(Template) ? 1 : 0)
5982 << NewArgs[ArgIdx].getSourceRange();
5983 Diag((*Param)->getLocation(), diag::note_template_param_here);
5984 return true;
5987 // We're now done with this argument.
5988 ++ArgIdx;
5990 if ((*Param)->isTemplateParameterPack()) {
5991 // The template parameter was a template parameter pack, so take the
5992 // deduced argument and place it on the argument pack. Note that we
5993 // stay on the same template parameter so that we can deduce more
5994 // arguments.
5995 SugaredArgumentPack.push_back(SugaredConverted.pop_back_val());
5996 CanonicalArgumentPack.push_back(CanonicalConverted.pop_back_val());
5997 } else {
5998 // Move to the next template parameter.
5999 ++Param;
6002 // If we just saw a pack expansion into a non-pack, then directly convert
6003 // the remaining arguments, because we don't know what parameters they'll
6004 // match up with.
6005 if (PackExpansionIntoNonPack) {
6006 if (!SugaredArgumentPack.empty()) {
6007 // If we were part way through filling in an expanded parameter pack,
6008 // fall back to just producing individual arguments.
6009 SugaredConverted.insert(SugaredConverted.end(),
6010 SugaredArgumentPack.begin(),
6011 SugaredArgumentPack.end());
6012 SugaredArgumentPack.clear();
6014 CanonicalConverted.insert(CanonicalConverted.end(),
6015 CanonicalArgumentPack.begin(),
6016 CanonicalArgumentPack.end());
6017 CanonicalArgumentPack.clear();
6020 while (ArgIdx < NumArgs) {
6021 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
6022 SugaredConverted.push_back(Arg);
6023 CanonicalConverted.push_back(
6024 Context.getCanonicalTemplateArgument(Arg));
6025 ++ArgIdx;
6028 return false;
6031 continue;
6034 // If we're checking a partial template argument list, we're done.
6035 if (PartialTemplateArgs) {
6036 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
6037 SugaredConverted.push_back(
6038 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6039 CanonicalConverted.push_back(
6040 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6042 return false;
6045 // If we have a template parameter pack with no more corresponding
6046 // arguments, just break out now and we'll fill in the argument pack below.
6047 if ((*Param)->isTemplateParameterPack()) {
6048 assert(!getExpandedPackSize(*Param) &&
6049 "Should have dealt with this already");
6051 // A non-expanded parameter pack before the end of the parameter list
6052 // only occurs for an ill-formed template parameter list, unless we've
6053 // got a partial argument list for a function template, so just bail out.
6054 if (Param + 1 != ParamEnd) {
6055 assert(
6056 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
6057 "Concept templates must have parameter packs at the end.");
6058 return true;
6061 SugaredConverted.push_back(
6062 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
6063 SugaredArgumentPack.clear();
6065 CanonicalConverted.push_back(
6066 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
6067 CanonicalArgumentPack.clear();
6069 ++Param;
6070 continue;
6073 // Check whether we have a default argument.
6074 TemplateArgumentLoc Arg;
6076 // Retrieve the default template argument from the template
6077 // parameter. For each kind of template parameter, we substitute the
6078 // template arguments provided thus far and any "outer" template arguments
6079 // (when the template parameter was part of a nested template) into
6080 // the default argument.
6081 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
6082 if (!hasReachableDefaultArgument(TTP))
6083 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
6084 NewArgs);
6086 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(
6087 *this, Template, TemplateLoc, RAngleLoc, TTP, SugaredConverted,
6088 CanonicalConverted);
6089 if (!ArgType)
6090 return true;
6092 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
6093 ArgType);
6094 } else if (NonTypeTemplateParmDecl *NTTP
6095 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
6096 if (!hasReachableDefaultArgument(NTTP))
6097 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
6098 NewArgs);
6100 ExprResult E = SubstDefaultTemplateArgument(
6101 *this, Template, TemplateLoc, RAngleLoc, NTTP, SugaredConverted,
6102 CanonicalConverted);
6103 if (E.isInvalid())
6104 return true;
6106 Expr *Ex = E.getAs<Expr>();
6107 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
6108 } else {
6109 TemplateTemplateParmDecl *TempParm
6110 = cast<TemplateTemplateParmDecl>(*Param);
6112 if (!hasReachableDefaultArgument(TempParm))
6113 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
6114 NewArgs);
6116 NestedNameSpecifierLoc QualifierLoc;
6117 TemplateName Name = SubstDefaultTemplateArgument(
6118 *this, Template, TemplateLoc, RAngleLoc, TempParm, SugaredConverted,
6119 CanonicalConverted, QualifierLoc);
6120 if (Name.isNull())
6121 return true;
6123 Arg = TemplateArgumentLoc(
6124 Context, TemplateArgument(Name), QualifierLoc,
6125 TempParm->getDefaultArgument().getTemplateNameLoc());
6128 // Introduce an instantiation record that describes where we are using
6129 // the default template argument. We're not actually instantiating a
6130 // template here, we just create this object to put a note into the
6131 // context stack.
6132 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
6133 SugaredConverted,
6134 SourceRange(TemplateLoc, RAngleLoc));
6135 if (Inst.isInvalid())
6136 return true;
6138 // Check the default template argument.
6139 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0,
6140 SugaredConverted, CanonicalConverted,
6141 CTAK_Specified))
6142 return true;
6144 CanonicalConverted.back().setIsDefaulted(true);
6146 // Core issue 150 (assumed resolution): if this is a template template
6147 // parameter, keep track of the default template arguments from the
6148 // template definition.
6149 if (isTemplateTemplateParameter)
6150 NewArgs.addArgument(Arg);
6152 // Move to the next template parameter and argument.
6153 ++Param;
6154 ++ArgIdx;
6157 // If we're performing a partial argument substitution, allow any trailing
6158 // pack expansions; they might be empty. This can happen even if
6159 // PartialTemplateArgs is false (the list of arguments is complete but
6160 // still dependent).
6161 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
6162 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
6163 while (ArgIdx < NumArgs &&
6164 NewArgs[ArgIdx].getArgument().isPackExpansion()) {
6165 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
6166 SugaredConverted.push_back(Arg);
6167 CanonicalConverted.push_back(Context.getCanonicalTemplateArgument(Arg));
6171 // If we have any leftover arguments, then there were too many arguments.
6172 // Complain and fail.
6173 if (ArgIdx < NumArgs) {
6174 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
6175 << /*too many args*/1
6176 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
6177 << Template
6178 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
6179 Diag(Template->getLocation(), diag::note_template_decl_here)
6180 << Params->getSourceRange();
6181 return true;
6184 // No problems found with the new argument list, propagate changes back
6185 // to caller.
6186 if (UpdateArgsWithConversions)
6187 TemplateArgs = std::move(NewArgs);
6189 if (!PartialTemplateArgs) {
6190 TemplateArgumentList StackTemplateArgs(TemplateArgumentList::OnStack,
6191 CanonicalConverted);
6192 // Setup the context/ThisScope for the case where we are needing to
6193 // re-instantiate constraints outside of normal instantiation.
6194 DeclContext *NewContext = Template->getDeclContext();
6196 // If this template is in a template, make sure we extract the templated
6197 // decl.
6198 if (auto *TD = dyn_cast<TemplateDecl>(NewContext))
6199 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
6200 auto *RD = dyn_cast<CXXRecordDecl>(NewContext);
6202 Qualifiers ThisQuals;
6203 if (const auto *Method =
6204 dyn_cast_or_null<CXXMethodDecl>(Template->getTemplatedDecl()))
6205 ThisQuals = Method->getMethodQualifiers();
6207 ContextRAII Context(*this, NewContext);
6208 CXXThisScopeRAII(*this, RD, ThisQuals, RD != nullptr);
6210 MultiLevelTemplateArgumentList MLTAL = getTemplateInstantiationArgs(
6211 Template, NewContext, /*Final=*/false, &StackTemplateArgs,
6212 /*RelativeToPrimary=*/true,
6213 /*Pattern=*/nullptr,
6214 /*ForConceptInstantiation=*/true);
6215 if (EnsureTemplateArgumentListConstraints(
6216 Template, MLTAL,
6217 SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
6218 if (ConstraintsNotSatisfied)
6219 *ConstraintsNotSatisfied = true;
6220 return true;
6224 return false;
6227 namespace {
6228 class UnnamedLocalNoLinkageFinder
6229 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
6231 Sema &S;
6232 SourceRange SR;
6234 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
6236 public:
6237 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
6239 bool Visit(QualType T) {
6240 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
6243 #define TYPE(Class, Parent) \
6244 bool Visit##Class##Type(const Class##Type *);
6245 #define ABSTRACT_TYPE(Class, Parent) \
6246 bool Visit##Class##Type(const Class##Type *) { return false; }
6247 #define NON_CANONICAL_TYPE(Class, Parent) \
6248 bool Visit##Class##Type(const Class##Type *) { return false; }
6249 #include "clang/AST/TypeNodes.inc"
6251 bool VisitTagDecl(const TagDecl *Tag);
6252 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
6254 } // end anonymous namespace
6256 bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
6257 return false;
6260 bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
6261 return Visit(T->getElementType());
6264 bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
6265 return Visit(T->getPointeeType());
6268 bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
6269 const BlockPointerType* T) {
6270 return Visit(T->getPointeeType());
6273 bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
6274 const LValueReferenceType* T) {
6275 return Visit(T->getPointeeType());
6278 bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
6279 const RValueReferenceType* T) {
6280 return Visit(T->getPointeeType());
6283 bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
6284 const MemberPointerType* T) {
6285 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
6288 bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
6289 const ConstantArrayType* T) {
6290 return Visit(T->getElementType());
6293 bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
6294 const IncompleteArrayType* T) {
6295 return Visit(T->getElementType());
6298 bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
6299 const VariableArrayType* T) {
6300 return Visit(T->getElementType());
6303 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
6304 const DependentSizedArrayType* T) {
6305 return Visit(T->getElementType());
6308 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
6309 const DependentSizedExtVectorType* T) {
6310 return Visit(T->getElementType());
6313 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
6314 const DependentSizedMatrixType *T) {
6315 return Visit(T->getElementType());
6318 bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
6319 const DependentAddressSpaceType *T) {
6320 return Visit(T->getPointeeType());
6323 bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
6324 return Visit(T->getElementType());
6327 bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
6328 const DependentVectorType *T) {
6329 return Visit(T->getElementType());
6332 bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
6333 return Visit(T->getElementType());
6336 bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
6337 const ConstantMatrixType *T) {
6338 return Visit(T->getElementType());
6341 bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
6342 const FunctionProtoType* T) {
6343 for (const auto &A : T->param_types()) {
6344 if (Visit(A))
6345 return true;
6348 return Visit(T->getReturnType());
6351 bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
6352 const FunctionNoProtoType* T) {
6353 return Visit(T->getReturnType());
6356 bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
6357 const UnresolvedUsingType*) {
6358 return false;
6361 bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
6362 return false;
6365 bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
6366 return Visit(T->getUnmodifiedType());
6369 bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
6370 return false;
6373 bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
6374 const UnaryTransformType*) {
6375 return false;
6378 bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
6379 return Visit(T->getDeducedType());
6382 bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
6383 const DeducedTemplateSpecializationType *T) {
6384 return Visit(T->getDeducedType());
6387 bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
6388 return VisitTagDecl(T->getDecl());
6391 bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
6392 return VisitTagDecl(T->getDecl());
6395 bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
6396 const TemplateTypeParmType*) {
6397 return false;
6400 bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
6401 const SubstTemplateTypeParmPackType *) {
6402 return false;
6405 bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
6406 const TemplateSpecializationType*) {
6407 return false;
6410 bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
6411 const InjectedClassNameType* T) {
6412 return VisitTagDecl(T->getDecl());
6415 bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6416 const DependentNameType* T) {
6417 return VisitNestedNameSpecifier(T->getQualifier());
6420 bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
6421 const DependentTemplateSpecializationType* T) {
6422 if (auto *Q = T->getQualifier())
6423 return VisitNestedNameSpecifier(Q);
6424 return false;
6427 bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6428 const PackExpansionType* T) {
6429 return Visit(T->getPattern());
6432 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
6433 return false;
6436 bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
6437 const ObjCInterfaceType *) {
6438 return false;
6441 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
6442 const ObjCObjectPointerType *) {
6443 return false;
6446 bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
6447 return Visit(T->getValueType());
6450 bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
6451 return false;
6454 bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
6455 return false;
6458 bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6459 const DependentBitIntType *T) {
6460 return false;
6463 bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
6464 if (Tag->getDeclContext()->isFunctionOrMethod()) {
6465 S.Diag(SR.getBegin(),
6466 S.getLangOpts().CPlusPlus11 ?
6467 diag::warn_cxx98_compat_template_arg_local_type :
6468 diag::ext_template_arg_local_type)
6469 << S.Context.getTypeDeclType(Tag) << SR;
6470 return true;
6473 if (!Tag->hasNameForLinkage()) {
6474 S.Diag(SR.getBegin(),
6475 S.getLangOpts().CPlusPlus11 ?
6476 diag::warn_cxx98_compat_template_arg_unnamed_type :
6477 diag::ext_template_arg_unnamed_type) << SR;
6478 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
6479 return true;
6482 return false;
6485 bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6486 NestedNameSpecifier *NNS) {
6487 assert(NNS);
6488 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
6489 return true;
6491 switch (NNS->getKind()) {
6492 case NestedNameSpecifier::Identifier:
6493 case NestedNameSpecifier::Namespace:
6494 case NestedNameSpecifier::NamespaceAlias:
6495 case NestedNameSpecifier::Global:
6496 case NestedNameSpecifier::Super:
6497 return false;
6499 case NestedNameSpecifier::TypeSpec:
6500 case NestedNameSpecifier::TypeSpecWithTemplate:
6501 return Visit(QualType(NNS->getAsType(), 0));
6503 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6506 /// Check a template argument against its corresponding
6507 /// template type parameter.
6509 /// This routine implements the semantics of C++ [temp.arg.type]. It
6510 /// returns true if an error occurred, and false otherwise.
6511 bool Sema::CheckTemplateArgument(TypeSourceInfo *ArgInfo) {
6512 assert(ArgInfo && "invalid TypeSourceInfo");
6513 QualType Arg = ArgInfo->getType();
6514 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
6515 QualType CanonArg = Context.getCanonicalType(Arg);
6517 if (CanonArg->isVariablyModifiedType()) {
6518 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
6519 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
6520 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
6523 // C++03 [temp.arg.type]p2:
6524 // A local type, a type with no linkage, an unnamed type or a type
6525 // compounded from any of these types shall not be used as a
6526 // template-argument for a template type-parameter.
6528 // C++11 allows these, and even in C++03 we allow them as an extension with
6529 // a warning.
6530 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
6531 UnnamedLocalNoLinkageFinder Finder(*this, SR);
6532 (void)Finder.Visit(CanonArg);
6535 return false;
6538 enum NullPointerValueKind {
6539 NPV_NotNullPointer,
6540 NPV_NullPointer,
6541 NPV_Error
6544 /// Determine whether the given template argument is a null pointer
6545 /// value of the appropriate type.
6546 static NullPointerValueKind
6547 isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
6548 QualType ParamType, Expr *Arg,
6549 Decl *Entity = nullptr) {
6550 if (Arg->isValueDependent() || Arg->isTypeDependent())
6551 return NPV_NotNullPointer;
6553 // dllimport'd entities aren't constant but are available inside of template
6554 // arguments.
6555 if (Entity && Entity->hasAttr<DLLImportAttr>())
6556 return NPV_NotNullPointer;
6558 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
6559 llvm_unreachable(
6560 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6562 if (!S.getLangOpts().CPlusPlus11)
6563 return NPV_NotNullPointer;
6565 // Determine whether we have a constant expression.
6566 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
6567 if (ArgRV.isInvalid())
6568 return NPV_Error;
6569 Arg = ArgRV.get();
6571 Expr::EvalResult EvalResult;
6572 SmallVector<PartialDiagnosticAt, 8> Notes;
6573 EvalResult.Diag = &Notes;
6574 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
6575 EvalResult.HasSideEffects) {
6576 SourceLocation DiagLoc = Arg->getExprLoc();
6578 // If our only note is the usual "invalid subexpression" note, just point
6579 // the caret at its location rather than producing an essentially
6580 // redundant note.
6581 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6582 diag::note_invalid_subexpr_in_const_expr) {
6583 DiagLoc = Notes[0].first;
6584 Notes.clear();
6587 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
6588 << Arg->getType() << Arg->getSourceRange();
6589 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6590 S.Diag(Notes[I].first, Notes[I].second);
6592 S.Diag(Param->getLocation(), diag::note_template_param_here);
6593 return NPV_Error;
6596 // C++11 [temp.arg.nontype]p1:
6597 // - an address constant expression of type std::nullptr_t
6598 if (Arg->getType()->isNullPtrType())
6599 return NPV_NullPointer;
6601 // - a constant expression that evaluates to a null pointer value (4.10); or
6602 // - a constant expression that evaluates to a null member pointer value
6603 // (4.11); or
6604 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
6605 (EvalResult.Val.isMemberPointer() &&
6606 !EvalResult.Val.getMemberPointerDecl())) {
6607 // If our expression has an appropriate type, we've succeeded.
6608 bool ObjCLifetimeConversion;
6609 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
6610 S.IsQualificationConversion(Arg->getType(), ParamType, false,
6611 ObjCLifetimeConversion))
6612 return NPV_NullPointer;
6614 // The types didn't match, but we know we got a null pointer; complain,
6615 // then recover as if the types were correct.
6616 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
6617 << Arg->getType() << ParamType << Arg->getSourceRange();
6618 S.Diag(Param->getLocation(), diag::note_template_param_here);
6619 return NPV_NullPointer;
6622 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6623 // We found a pointer that isn't null, but doesn't refer to an object.
6624 // We could just return NPV_NotNullPointer, but we can print a better
6625 // message with the information we have here.
6626 S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid)
6627 << EvalResult.Val.getAsString(S.Context, ParamType);
6628 S.Diag(Param->getLocation(), diag::note_template_param_here);
6629 return NPV_Error;
6632 // If we don't have a null pointer value, but we do have a NULL pointer
6633 // constant, suggest a cast to the appropriate type.
6634 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
6635 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6636 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
6637 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
6638 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getEndLoc()),
6639 ")");
6640 S.Diag(Param->getLocation(), diag::note_template_param_here);
6641 return NPV_NullPointer;
6644 // FIXME: If we ever want to support general, address-constant expressions
6645 // as non-type template arguments, we should return the ExprResult here to
6646 // be interpreted by the caller.
6647 return NPV_NotNullPointer;
6650 /// Checks whether the given template argument is compatible with its
6651 /// template parameter.
6652 static bool CheckTemplateArgumentIsCompatibleWithParameter(
6653 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
6654 Expr *Arg, QualType ArgType) {
6655 bool ObjCLifetimeConversion;
6656 if (ParamType->isPointerType() &&
6657 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6658 S.IsQualificationConversion(ArgType, ParamType, false,
6659 ObjCLifetimeConversion)) {
6660 // For pointer-to-object types, qualification conversions are
6661 // permitted.
6662 } else {
6663 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6664 if (!ParamRef->getPointeeType()->isFunctionType()) {
6665 // C++ [temp.arg.nontype]p5b3:
6666 // For a non-type template-parameter of type reference to
6667 // object, no conversions apply. The type referred to by the
6668 // reference may be more cv-qualified than the (otherwise
6669 // identical) type of the template- argument. The
6670 // template-parameter is bound directly to the
6671 // template-argument, which shall be an lvalue.
6673 // FIXME: Other qualifiers?
6674 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6675 unsigned ArgQuals = ArgType.getCVRQualifiers();
6677 if ((ParamQuals | ArgQuals) != ParamQuals) {
6678 S.Diag(Arg->getBeginLoc(),
6679 diag::err_template_arg_ref_bind_ignores_quals)
6680 << ParamType << Arg->getType() << Arg->getSourceRange();
6681 S.Diag(Param->getLocation(), diag::note_template_param_here);
6682 return true;
6687 // At this point, the template argument refers to an object or
6688 // function with external linkage. We now need to check whether the
6689 // argument and parameter types are compatible.
6690 if (!S.Context.hasSameUnqualifiedType(ArgType,
6691 ParamType.getNonReferenceType())) {
6692 // We can't perform this conversion or binding.
6693 if (ParamType->isReferenceType())
6694 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
6695 << ParamType << ArgIn->getType() << Arg->getSourceRange();
6696 else
6697 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6698 << ArgIn->getType() << ParamType << Arg->getSourceRange();
6699 S.Diag(Param->getLocation(), diag::note_template_param_here);
6700 return true;
6704 return false;
6707 /// Checks whether the given template argument is the address
6708 /// of an object or function according to C++ [temp.arg.nontype]p1.
6709 static bool CheckTemplateArgumentAddressOfObjectOrFunction(
6710 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
6711 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
6712 bool Invalid = false;
6713 Expr *Arg = ArgIn;
6714 QualType ArgType = Arg->getType();
6716 bool AddressTaken = false;
6717 SourceLocation AddrOpLoc;
6718 if (S.getLangOpts().MicrosoftExt) {
6719 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6720 // dereference and address-of operators.
6721 Arg = Arg->IgnoreParenCasts();
6723 bool ExtWarnMSTemplateArg = false;
6724 UnaryOperatorKind FirstOpKind;
6725 SourceLocation FirstOpLoc;
6726 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6727 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6728 if (UnOpKind == UO_Deref)
6729 ExtWarnMSTemplateArg = true;
6730 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6731 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6732 if (!AddrOpLoc.isValid()) {
6733 FirstOpKind = UnOpKind;
6734 FirstOpLoc = UnOp->getOperatorLoc();
6736 } else
6737 break;
6739 if (FirstOpLoc.isValid()) {
6740 if (ExtWarnMSTemplateArg)
6741 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
6742 << ArgIn->getSourceRange();
6744 if (FirstOpKind == UO_AddrOf)
6745 AddressTaken = true;
6746 else if (Arg->getType()->isPointerType()) {
6747 // We cannot let pointers get dereferenced here, that is obviously not a
6748 // constant expression.
6749 assert(FirstOpKind == UO_Deref);
6750 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6751 << Arg->getSourceRange();
6754 } else {
6755 // See through any implicit casts we added to fix the type.
6756 Arg = Arg->IgnoreImpCasts();
6758 // C++ [temp.arg.nontype]p1:
6760 // A template-argument for a non-type, non-template
6761 // template-parameter shall be one of: [...]
6763 // -- the address of an object or function with external
6764 // linkage, including function templates and function
6765 // template-ids but excluding non-static class members,
6766 // expressed as & id-expression where the & is optional if
6767 // the name refers to a function or array, or if the
6768 // corresponding template-parameter is a reference; or
6770 // In C++98/03 mode, give an extension warning on any extra parentheses.
6771 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6772 bool ExtraParens = false;
6773 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6774 if (!Invalid && !ExtraParens) {
6775 S.Diag(Arg->getBeginLoc(),
6776 S.getLangOpts().CPlusPlus11
6777 ? diag::warn_cxx98_compat_template_arg_extra_parens
6778 : diag::ext_template_arg_extra_parens)
6779 << Arg->getSourceRange();
6780 ExtraParens = true;
6783 Arg = Parens->getSubExpr();
6786 while (SubstNonTypeTemplateParmExpr *subst =
6787 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6788 Arg = subst->getReplacement()->IgnoreImpCasts();
6790 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6791 if (UnOp->getOpcode() == UO_AddrOf) {
6792 Arg = UnOp->getSubExpr();
6793 AddressTaken = true;
6794 AddrOpLoc = UnOp->getOperatorLoc();
6798 while (SubstNonTypeTemplateParmExpr *subst =
6799 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6800 Arg = subst->getReplacement()->IgnoreImpCasts();
6803 ValueDecl *Entity = nullptr;
6804 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg))
6805 Entity = DRE->getDecl();
6806 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Arg))
6807 Entity = CUE->getGuidDecl();
6809 // If our parameter has pointer type, check for a null template value.
6810 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6811 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
6812 Entity)) {
6813 case NPV_NullPointer:
6814 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6815 SugaredConverted = TemplateArgument(ParamType,
6816 /*isNullPtr=*/true);
6817 CanonicalConverted =
6818 TemplateArgument(S.Context.getCanonicalType(ParamType),
6819 /*isNullPtr=*/true);
6820 return false;
6822 case NPV_Error:
6823 return true;
6825 case NPV_NotNullPointer:
6826 break;
6830 // Stop checking the precise nature of the argument if it is value dependent,
6831 // it should be checked when instantiated.
6832 if (Arg->isValueDependent()) {
6833 SugaredConverted = TemplateArgument(ArgIn);
6834 CanonicalConverted =
6835 S.Context.getCanonicalTemplateArgument(SugaredConverted);
6836 return false;
6839 if (!Entity) {
6840 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6841 << Arg->getSourceRange();
6842 S.Diag(Param->getLocation(), diag::note_template_param_here);
6843 return true;
6846 // Cannot refer to non-static data members
6847 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
6848 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
6849 << Entity << Arg->getSourceRange();
6850 S.Diag(Param->getLocation(), diag::note_template_param_here);
6851 return true;
6854 // Cannot refer to non-static member functions
6855 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
6856 if (!Method->isStatic()) {
6857 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
6858 << Method << Arg->getSourceRange();
6859 S.Diag(Param->getLocation(), diag::note_template_param_here);
6860 return true;
6864 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
6865 VarDecl *Var = dyn_cast<VarDecl>(Entity);
6866 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Entity);
6868 // A non-type template argument must refer to an object or function.
6869 if (!Func && !Var && !Guid) {
6870 // We found something, but we don't know specifically what it is.
6871 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
6872 << Arg->getSourceRange();
6873 S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here);
6874 return true;
6877 // Address / reference template args must have external linkage in C++98.
6878 if (Entity->getFormalLinkage() == Linkage::Internal) {
6879 S.Diag(Arg->getBeginLoc(),
6880 S.getLangOpts().CPlusPlus11
6881 ? diag::warn_cxx98_compat_template_arg_object_internal
6882 : diag::ext_template_arg_object_internal)
6883 << !Func << Entity << Arg->getSourceRange();
6884 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6885 << !Func;
6886 } else if (!Entity->hasLinkage()) {
6887 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
6888 << !Func << Entity << Arg->getSourceRange();
6889 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6890 << !Func;
6891 return true;
6894 if (Var) {
6895 // A value of reference type is not an object.
6896 if (Var->getType()->isReferenceType()) {
6897 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
6898 << Var->getType() << Arg->getSourceRange();
6899 S.Diag(Param->getLocation(), diag::note_template_param_here);
6900 return true;
6903 // A template argument must have static storage duration.
6904 if (Var->getTLSKind()) {
6905 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
6906 << Arg->getSourceRange();
6907 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
6908 return true;
6912 if (AddressTaken && ParamType->isReferenceType()) {
6913 // If we originally had an address-of operator, but the
6914 // parameter has reference type, complain and (if things look
6915 // like they will work) drop the address-of operator.
6916 if (!S.Context.hasSameUnqualifiedType(Entity->getType(),
6917 ParamType.getNonReferenceType())) {
6918 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6919 << ParamType;
6920 S.Diag(Param->getLocation(), diag::note_template_param_here);
6921 return true;
6924 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6925 << ParamType
6926 << FixItHint::CreateRemoval(AddrOpLoc);
6927 S.Diag(Param->getLocation(), diag::note_template_param_here);
6929 ArgType = Entity->getType();
6932 // If the template parameter has pointer type, either we must have taken the
6933 // address or the argument must decay to a pointer.
6934 if (!AddressTaken && ParamType->isPointerType()) {
6935 if (Func) {
6936 // Function-to-pointer decay.
6937 ArgType = S.Context.getPointerType(Func->getType());
6938 } else if (Entity->getType()->isArrayType()) {
6939 // Array-to-pointer decay.
6940 ArgType = S.Context.getArrayDecayedType(Entity->getType());
6941 } else {
6942 // If the template parameter has pointer type but the address of
6943 // this object was not taken, complain and (possibly) recover by
6944 // taking the address of the entity.
6945 ArgType = S.Context.getPointerType(Entity->getType());
6946 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
6947 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6948 << ParamType;
6949 S.Diag(Param->getLocation(), diag::note_template_param_here);
6950 return true;
6953 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6954 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
6956 S.Diag(Param->getLocation(), diag::note_template_param_here);
6960 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6961 Arg, ArgType))
6962 return true;
6964 // Create the template argument.
6965 SugaredConverted = TemplateArgument(Entity, ParamType);
6966 CanonicalConverted =
6967 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()),
6968 S.Context.getCanonicalType(ParamType));
6969 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
6970 return false;
6973 /// Checks whether the given template argument is a pointer to
6974 /// member constant according to C++ [temp.arg.nontype]p1.
6975 static bool
6976 CheckTemplateArgumentPointerToMember(Sema &S, NonTypeTemplateParmDecl *Param,
6977 QualType ParamType, Expr *&ResultArg,
6978 TemplateArgument &SugaredConverted,
6979 TemplateArgument &CanonicalConverted) {
6980 bool Invalid = false;
6982 Expr *Arg = ResultArg;
6983 bool ObjCLifetimeConversion;
6985 // C++ [temp.arg.nontype]p1:
6987 // A template-argument for a non-type, non-template
6988 // template-parameter shall be one of: [...]
6990 // -- a pointer to member expressed as described in 5.3.1.
6991 DeclRefExpr *DRE = nullptr;
6993 // In C++98/03 mode, give an extension warning on any extra parentheses.
6994 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6995 bool ExtraParens = false;
6996 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6997 if (!Invalid && !ExtraParens) {
6998 S.Diag(Arg->getBeginLoc(),
6999 S.getLangOpts().CPlusPlus11
7000 ? diag::warn_cxx98_compat_template_arg_extra_parens
7001 : diag::ext_template_arg_extra_parens)
7002 << Arg->getSourceRange();
7003 ExtraParens = true;
7006 Arg = Parens->getSubExpr();
7009 while (SubstNonTypeTemplateParmExpr *subst =
7010 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
7011 Arg = subst->getReplacement()->IgnoreImpCasts();
7013 // A pointer-to-member constant written &Class::member.
7014 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
7015 if (UnOp->getOpcode() == UO_AddrOf) {
7016 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
7017 if (DRE && !DRE->getQualifier())
7018 DRE = nullptr;
7021 // A constant of pointer-to-member type.
7022 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
7023 ValueDecl *VD = DRE->getDecl();
7024 if (VD->getType()->isMemberPointerType()) {
7025 if (isa<NonTypeTemplateParmDecl>(VD)) {
7026 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7027 SugaredConverted = TemplateArgument(Arg);
7028 CanonicalConverted =
7029 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7030 } else {
7031 SugaredConverted = TemplateArgument(VD, ParamType);
7032 CanonicalConverted =
7033 TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()),
7034 S.Context.getCanonicalType(ParamType));
7036 return Invalid;
7040 DRE = nullptr;
7043 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
7045 // Check for a null pointer value.
7046 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
7047 Entity)) {
7048 case NPV_Error:
7049 return true;
7050 case NPV_NullPointer:
7051 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7052 SugaredConverted = TemplateArgument(ParamType,
7053 /*isNullPtr*/ true);
7054 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(ParamType),
7055 /*isNullPtr*/ true);
7056 return false;
7057 case NPV_NotNullPointer:
7058 break;
7061 if (S.IsQualificationConversion(ResultArg->getType(),
7062 ParamType.getNonReferenceType(), false,
7063 ObjCLifetimeConversion)) {
7064 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
7065 ResultArg->getValueKind())
7066 .get();
7067 } else if (!S.Context.hasSameUnqualifiedType(
7068 ResultArg->getType(), ParamType.getNonReferenceType())) {
7069 // We can't perform this conversion.
7070 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
7071 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
7072 S.Diag(Param->getLocation(), diag::note_template_param_here);
7073 return true;
7076 if (!DRE)
7077 return S.Diag(Arg->getBeginLoc(),
7078 diag::err_template_arg_not_pointer_to_member_form)
7079 << Arg->getSourceRange();
7081 if (isa<FieldDecl>(DRE->getDecl()) ||
7082 isa<IndirectFieldDecl>(DRE->getDecl()) ||
7083 isa<CXXMethodDecl>(DRE->getDecl())) {
7084 assert((isa<FieldDecl>(DRE->getDecl()) ||
7085 isa<IndirectFieldDecl>(DRE->getDecl()) ||
7086 cast<CXXMethodDecl>(DRE->getDecl())
7087 ->isImplicitObjectMemberFunction()) &&
7088 "Only non-static member pointers can make it here");
7090 // Okay: this is the address of a non-static member, and therefore
7091 // a member pointer constant.
7092 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7093 SugaredConverted = TemplateArgument(Arg);
7094 CanonicalConverted =
7095 S.Context.getCanonicalTemplateArgument(SugaredConverted);
7096 } else {
7097 ValueDecl *D = DRE->getDecl();
7098 SugaredConverted = TemplateArgument(D, ParamType);
7099 CanonicalConverted =
7100 TemplateArgument(cast<ValueDecl>(D->getCanonicalDecl()),
7101 S.Context.getCanonicalType(ParamType));
7103 return Invalid;
7106 // We found something else, but we don't know specifically what it is.
7107 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
7108 << Arg->getSourceRange();
7109 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
7110 return true;
7113 /// Check a template argument against its corresponding
7114 /// non-type template parameter.
7116 /// This routine implements the semantics of C++ [temp.arg.nontype].
7117 /// If an error occurred, it returns ExprError(); otherwise, it
7118 /// returns the converted template argument. \p ParamType is the
7119 /// type of the non-type template parameter after it has been instantiated.
7120 ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
7121 QualType ParamType, Expr *Arg,
7122 TemplateArgument &SugaredConverted,
7123 TemplateArgument &CanonicalConverted,
7124 CheckTemplateArgumentKind CTAK) {
7125 SourceLocation StartLoc = Arg->getBeginLoc();
7127 // If the parameter type somehow involves auto, deduce the type now.
7128 DeducedType *DeducedT = ParamType->getContainedDeducedType();
7129 if (getLangOpts().CPlusPlus17 && DeducedT && !DeducedT->isDeduced()) {
7130 // During template argument deduction, we allow 'decltype(auto)' to
7131 // match an arbitrary dependent argument.
7132 // FIXME: The language rules don't say what happens in this case.
7133 // FIXME: We get an opaque dependent type out of decltype(auto) if the
7134 // expression is merely instantiation-dependent; is this enough?
7135 if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) {
7136 auto *AT = dyn_cast<AutoType>(DeducedT);
7137 if (AT && AT->isDecltypeAuto()) {
7138 SugaredConverted = TemplateArgument(Arg);
7139 CanonicalConverted = TemplateArgument(
7140 Context.getCanonicalTemplateArgument(SugaredConverted));
7141 return Arg;
7145 // When checking a deduced template argument, deduce from its type even if
7146 // the type is dependent, in order to check the types of non-type template
7147 // arguments line up properly in partial ordering.
7148 Expr *DeductionArg = Arg;
7149 if (auto *PE = dyn_cast<PackExpansionExpr>(DeductionArg))
7150 DeductionArg = PE->getPattern();
7151 TypeSourceInfo *TSI =
7152 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation());
7153 if (isa<DeducedTemplateSpecializationType>(DeducedT)) {
7154 InitializedEntity Entity =
7155 InitializedEntity::InitializeTemplateParameter(ParamType, Param);
7156 InitializationKind Kind = InitializationKind::CreateForInit(
7157 DeductionArg->getBeginLoc(), /*DirectInit*/false, DeductionArg);
7158 Expr *Inits[1] = {DeductionArg};
7159 ParamType =
7160 DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, Inits);
7161 if (ParamType.isNull())
7162 return ExprError();
7163 } else {
7164 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
7165 Param->getDepth() + 1);
7166 ParamType = QualType();
7167 TemplateDeductionResult Result =
7168 DeduceAutoType(TSI->getTypeLoc(), DeductionArg, ParamType, Info,
7169 /*DependentDeduction=*/true,
7170 // We do not check constraints right now because the
7171 // immediately-declared constraint of the auto type is
7172 // also an associated constraint, and will be checked
7173 // along with the other associated constraints after
7174 // checking the template argument list.
7175 /*IgnoreConstraints=*/true);
7176 if (Result == TDK_AlreadyDiagnosed) {
7177 if (ParamType.isNull())
7178 return ExprError();
7179 } else if (Result != TDK_Success) {
7180 Diag(Arg->getExprLoc(),
7181 diag::err_non_type_template_parm_type_deduction_failure)
7182 << Param->getDeclName() << Param->getType() << Arg->getType()
7183 << Arg->getSourceRange();
7184 Diag(Param->getLocation(), diag::note_template_param_here);
7185 return ExprError();
7188 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
7189 // an error. The error message normally references the parameter
7190 // declaration, but here we'll pass the argument location because that's
7191 // where the parameter type is deduced.
7192 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
7193 if (ParamType.isNull()) {
7194 Diag(Param->getLocation(), diag::note_template_param_here);
7195 return ExprError();
7199 // We should have already dropped all cv-qualifiers by now.
7200 assert(!ParamType.hasQualifiers() &&
7201 "non-type template parameter type cannot be qualified");
7203 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
7204 if (CTAK == CTAK_Deduced &&
7205 (ParamType->isReferenceType()
7206 ? !Context.hasSameType(ParamType.getNonReferenceType(),
7207 Arg->getType())
7208 : !Context.hasSameUnqualifiedType(ParamType, Arg->getType()))) {
7209 // FIXME: If either type is dependent, we skip the check. This isn't
7210 // correct, since during deduction we're supposed to have replaced each
7211 // template parameter with some unique (non-dependent) placeholder.
7212 // FIXME: If the argument type contains 'auto', we carry on and fail the
7213 // type check in order to force specific types to be more specialized than
7214 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
7215 // work. Similarly for CTAD, when comparing 'A<x>' against 'A'.
7216 if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
7217 !Arg->getType()->getContainedDeducedType()) {
7218 SugaredConverted = TemplateArgument(Arg);
7219 CanonicalConverted = TemplateArgument(
7220 Context.getCanonicalTemplateArgument(SugaredConverted));
7221 return Arg;
7223 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
7224 // we should actually be checking the type of the template argument in P,
7225 // not the type of the template argument deduced from A, against the
7226 // template parameter type.
7227 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
7228 << Arg->getType()
7229 << ParamType.getUnqualifiedType();
7230 Diag(Param->getLocation(), diag::note_template_param_here);
7231 return ExprError();
7234 // If either the parameter has a dependent type or the argument is
7235 // type-dependent, there's nothing we can check now.
7236 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
7237 // Force the argument to the type of the parameter to maintain invariants.
7238 auto *PE = dyn_cast<PackExpansionExpr>(Arg);
7239 if (PE)
7240 Arg = PE->getPattern();
7241 ExprResult E = ImpCastExprToType(
7242 Arg, ParamType.getNonLValueExprType(Context), CK_Dependent,
7243 ParamType->isLValueReferenceType() ? VK_LValue
7244 : ParamType->isRValueReferenceType() ? VK_XValue
7245 : VK_PRValue);
7246 if (E.isInvalid())
7247 return ExprError();
7248 if (PE) {
7249 // Recreate a pack expansion if we unwrapped one.
7250 E = new (Context)
7251 PackExpansionExpr(E.get()->getType(), E.get(), PE->getEllipsisLoc(),
7252 PE->getNumExpansions());
7254 SugaredConverted = TemplateArgument(E.get());
7255 CanonicalConverted = TemplateArgument(
7256 Context.getCanonicalTemplateArgument(SugaredConverted));
7257 return E;
7260 // The initialization of the parameter from the argument is
7261 // a constant-evaluated context.
7262 EnterExpressionEvaluationContext ConstantEvaluated(
7263 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
7265 if (getLangOpts().CPlusPlus17) {
7266 QualType CanonParamType = Context.getCanonicalType(ParamType);
7268 // Avoid making a copy when initializing a template parameter of class type
7269 // from a template parameter object of the same type. This is going beyond
7270 // the standard, but is required for soundness: in
7271 // template<A a> struct X { X *p; X<a> *q; };
7272 // ... we need p and q to have the same type.
7274 // Similarly, don't inject a call to a copy constructor when initializing
7275 // from a template parameter of the same type.
7276 Expr *InnerArg = Arg->IgnoreParenImpCasts();
7277 if (ParamType->isRecordType() && isa<DeclRefExpr>(InnerArg) &&
7278 Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) {
7279 NamedDecl *ND = cast<DeclRefExpr>(InnerArg)->getDecl();
7280 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
7282 SugaredConverted = TemplateArgument(TPO, ParamType);
7283 CanonicalConverted =
7284 TemplateArgument(TPO->getCanonicalDecl(), CanonParamType);
7285 return Arg;
7287 if (isa<NonTypeTemplateParmDecl>(ND)) {
7288 SugaredConverted = TemplateArgument(Arg);
7289 CanonicalConverted =
7290 Context.getCanonicalTemplateArgument(SugaredConverted);
7291 return Arg;
7295 // C++17 [temp.arg.nontype]p1:
7296 // A template-argument for a non-type template parameter shall be
7297 // a converted constant expression of the type of the template-parameter.
7298 APValue Value;
7299 ExprResult ArgResult = CheckConvertedConstantExpression(
7300 Arg, ParamType, Value, CCEK_TemplateArg, Param);
7301 if (ArgResult.isInvalid())
7302 return ExprError();
7304 // For a value-dependent argument, CheckConvertedConstantExpression is
7305 // permitted (and expected) to be unable to determine a value.
7306 if (ArgResult.get()->isValueDependent()) {
7307 SugaredConverted = TemplateArgument(ArgResult.get());
7308 CanonicalConverted =
7309 Context.getCanonicalTemplateArgument(SugaredConverted);
7310 return ArgResult;
7313 // Convert the APValue to a TemplateArgument.
7314 switch (Value.getKind()) {
7315 case APValue::None:
7316 assert(ParamType->isNullPtrType());
7317 SugaredConverted = TemplateArgument(ParamType, /*isNullPtr=*/true);
7318 CanonicalConverted = TemplateArgument(CanonParamType, /*isNullPtr=*/true);
7319 break;
7320 case APValue::Indeterminate:
7321 llvm_unreachable("result of constant evaluation should be initialized");
7322 break;
7323 case APValue::Int:
7324 assert(ParamType->isIntegralOrEnumerationType());
7325 SugaredConverted = TemplateArgument(Context, Value.getInt(), ParamType);
7326 CanonicalConverted =
7327 TemplateArgument(Context, Value.getInt(), CanonParamType);
7328 break;
7329 case APValue::MemberPointer: {
7330 assert(ParamType->isMemberPointerType());
7332 // FIXME: We need TemplateArgument representation and mangling for these.
7333 if (!Value.getMemberPointerPath().empty()) {
7334 Diag(Arg->getBeginLoc(),
7335 diag::err_template_arg_member_ptr_base_derived_not_supported)
7336 << Value.getMemberPointerDecl() << ParamType
7337 << Arg->getSourceRange();
7338 return ExprError();
7341 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
7342 SugaredConverted = VD ? TemplateArgument(VD, ParamType)
7343 : TemplateArgument(ParamType, /*isNullPtr=*/true);
7344 CanonicalConverted =
7345 VD ? TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()),
7346 CanonParamType)
7347 : TemplateArgument(CanonParamType, /*isNullPtr=*/true);
7348 break;
7350 case APValue::LValue: {
7351 // For a non-type template-parameter of pointer or reference type,
7352 // the value of the constant expression shall not refer to
7353 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
7354 ParamType->isNullPtrType());
7355 // -- a temporary object
7356 // -- a string literal
7357 // -- the result of a typeid expression, or
7358 // -- a predefined __func__ variable
7359 APValue::LValueBase Base = Value.getLValueBase();
7360 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
7361 if (Base &&
7362 (!VD ||
7363 isa<LifetimeExtendedTemporaryDecl, UnnamedGlobalConstantDecl>(VD))) {
7364 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
7365 << Arg->getSourceRange();
7366 return ExprError();
7368 // -- a subobject
7369 // FIXME: Until C++20
7370 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
7371 VD && VD->getType()->isArrayType() &&
7372 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
7373 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
7374 // Per defect report (no number yet):
7375 // ... other than a pointer to the first element of a complete array
7376 // object.
7377 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
7378 Value.isLValueOnePastTheEnd()) {
7379 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
7380 << Value.getAsString(Context, ParamType);
7381 return ExprError();
7383 assert((VD || !ParamType->isReferenceType()) &&
7384 "null reference should not be a constant expression");
7385 assert((!VD || !ParamType->isNullPtrType()) &&
7386 "non-null value of type nullptr_t?");
7388 SugaredConverted = VD ? TemplateArgument(VD, ParamType)
7389 : TemplateArgument(ParamType, /*isNullPtr=*/true);
7390 CanonicalConverted =
7391 VD ? TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()),
7392 CanonParamType)
7393 : TemplateArgument(CanonParamType, /*isNullPtr=*/true);
7394 break;
7396 case APValue::Struct:
7397 case APValue::Union: {
7398 // Get or create the corresponding template parameter object.
7399 TemplateParamObjectDecl *D =
7400 Context.getTemplateParamObjectDecl(ParamType, Value);
7401 SugaredConverted = TemplateArgument(D, ParamType);
7402 CanonicalConverted =
7403 TemplateArgument(D->getCanonicalDecl(), CanonParamType);
7404 break;
7406 case APValue::AddrLabelDiff:
7407 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
7408 case APValue::FixedPoint:
7409 case APValue::Float:
7410 case APValue::ComplexInt:
7411 case APValue::ComplexFloat:
7412 case APValue::Vector:
7413 case APValue::Array:
7414 return Diag(StartLoc, diag::err_non_type_template_arg_unsupported)
7415 << ParamType;
7418 return ArgResult.get();
7421 // C++ [temp.arg.nontype]p5:
7422 // The following conversions are performed on each expression used
7423 // as a non-type template-argument. If a non-type
7424 // template-argument cannot be converted to the type of the
7425 // corresponding template-parameter then the program is
7426 // ill-formed.
7427 if (ParamType->isIntegralOrEnumerationType()) {
7428 // C++11:
7429 // -- for a non-type template-parameter of integral or
7430 // enumeration type, conversions permitted in a converted
7431 // constant expression are applied.
7433 // C++98:
7434 // -- for a non-type template-parameter of integral or
7435 // enumeration type, integral promotions (4.5) and integral
7436 // conversions (4.7) are applied.
7438 if (getLangOpts().CPlusPlus11) {
7439 // C++ [temp.arg.nontype]p1:
7440 // A template-argument for a non-type, non-template template-parameter
7441 // shall be one of:
7443 // -- for a non-type template-parameter of integral or enumeration
7444 // type, a converted constant expression of the type of the
7445 // template-parameter; or
7446 llvm::APSInt Value;
7447 ExprResult ArgResult =
7448 CheckConvertedConstantExpression(Arg, ParamType, Value,
7449 CCEK_TemplateArg);
7450 if (ArgResult.isInvalid())
7451 return ExprError();
7453 // We can't check arbitrary value-dependent arguments.
7454 if (ArgResult.get()->isValueDependent()) {
7455 SugaredConverted = TemplateArgument(ArgResult.get());
7456 CanonicalConverted =
7457 Context.getCanonicalTemplateArgument(SugaredConverted);
7458 return ArgResult;
7461 // Widen the argument value to sizeof(parameter type). This is almost
7462 // always a no-op, except when the parameter type is bool. In
7463 // that case, this may extend the argument from 1 bit to 8 bits.
7464 QualType IntegerType = ParamType;
7465 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
7466 IntegerType = Enum->getDecl()->getIntegerType();
7467 Value = Value.extOrTrunc(IntegerType->isBitIntType()
7468 ? Context.getIntWidth(IntegerType)
7469 : Context.getTypeSize(IntegerType));
7471 SugaredConverted = TemplateArgument(Context, Value, ParamType);
7472 CanonicalConverted =
7473 TemplateArgument(Context, Value, Context.getCanonicalType(ParamType));
7474 return ArgResult;
7477 ExprResult ArgResult = DefaultLvalueConversion(Arg);
7478 if (ArgResult.isInvalid())
7479 return ExprError();
7480 Arg = ArgResult.get();
7482 QualType ArgType = Arg->getType();
7484 // C++ [temp.arg.nontype]p1:
7485 // A template-argument for a non-type, non-template
7486 // template-parameter shall be one of:
7488 // -- an integral constant-expression of integral or enumeration
7489 // type; or
7490 // -- the name of a non-type template-parameter; or
7491 llvm::APSInt Value;
7492 if (!ArgType->isIntegralOrEnumerationType()) {
7493 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
7494 << ArgType << Arg->getSourceRange();
7495 Diag(Param->getLocation(), diag::note_template_param_here);
7496 return ExprError();
7497 } else if (!Arg->isValueDependent()) {
7498 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
7499 QualType T;
7501 public:
7502 TmplArgICEDiagnoser(QualType T) : T(T) { }
7504 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7505 SourceLocation Loc) override {
7506 return S.Diag(Loc, diag::err_template_arg_not_ice) << T;
7508 } Diagnoser(ArgType);
7510 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser).get();
7511 if (!Arg)
7512 return ExprError();
7515 // From here on out, all we care about is the unqualified form
7516 // of the argument type.
7517 ArgType = ArgType.getUnqualifiedType();
7519 // Try to convert the argument to the parameter's type.
7520 if (Context.hasSameType(ParamType, ArgType)) {
7521 // Okay: no conversion necessary
7522 } else if (ParamType->isBooleanType()) {
7523 // This is an integral-to-boolean conversion.
7524 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
7525 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
7526 !ParamType->isEnumeralType()) {
7527 // This is an integral promotion or conversion.
7528 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
7529 } else {
7530 // We can't perform this conversion.
7531 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
7532 << Arg->getType() << ParamType << Arg->getSourceRange();
7533 Diag(Param->getLocation(), diag::note_template_param_here);
7534 return ExprError();
7537 // Add the value of this argument to the list of converted
7538 // arguments. We use the bitwidth and signedness of the template
7539 // parameter.
7540 if (Arg->isValueDependent()) {
7541 // The argument is value-dependent. Create a new
7542 // TemplateArgument with the converted expression.
7543 SugaredConverted = TemplateArgument(Arg);
7544 CanonicalConverted =
7545 Context.getCanonicalTemplateArgument(SugaredConverted);
7546 return Arg;
7549 QualType IntegerType = ParamType;
7550 if (const EnumType *Enum = IntegerType->getAs<EnumType>()) {
7551 IntegerType = Enum->getDecl()->getIntegerType();
7554 if (ParamType->isBooleanType()) {
7555 // Value must be zero or one.
7556 Value = Value != 0;
7557 unsigned AllowedBits = Context.getTypeSize(IntegerType);
7558 if (Value.getBitWidth() != AllowedBits)
7559 Value = Value.extOrTrunc(AllowedBits);
7560 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7561 } else {
7562 llvm::APSInt OldValue = Value;
7564 // Coerce the template argument's value to the value it will have
7565 // based on the template parameter's type.
7566 unsigned AllowedBits = IntegerType->isBitIntType()
7567 ? Context.getIntWidth(IntegerType)
7568 : Context.getTypeSize(IntegerType);
7569 if (Value.getBitWidth() != AllowedBits)
7570 Value = Value.extOrTrunc(AllowedBits);
7571 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7573 // Complain if an unsigned parameter received a negative value.
7574 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
7575 (OldValue.isSigned() && OldValue.isNegative())) {
7576 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
7577 << toString(OldValue, 10) << toString(Value, 10) << Param->getType()
7578 << Arg->getSourceRange();
7579 Diag(Param->getLocation(), diag::note_template_param_here);
7582 // Complain if we overflowed the template parameter's type.
7583 unsigned RequiredBits;
7584 if (IntegerType->isUnsignedIntegerOrEnumerationType())
7585 RequiredBits = OldValue.getActiveBits();
7586 else if (OldValue.isUnsigned())
7587 RequiredBits = OldValue.getActiveBits() + 1;
7588 else
7589 RequiredBits = OldValue.getSignificantBits();
7590 if (RequiredBits > AllowedBits) {
7591 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
7592 << toString(OldValue, 10) << toString(Value, 10) << Param->getType()
7593 << Arg->getSourceRange();
7594 Diag(Param->getLocation(), diag::note_template_param_here);
7598 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
7599 SugaredConverted = TemplateArgument(Context, Value, T);
7600 CanonicalConverted =
7601 TemplateArgument(Context, Value, Context.getCanonicalType(T));
7602 return Arg;
7605 QualType ArgType = Arg->getType();
7606 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
7608 // Handle pointer-to-function, reference-to-function, and
7609 // pointer-to-member-function all in (roughly) the same way.
7610 if (// -- For a non-type template-parameter of type pointer to
7611 // function, only the function-to-pointer conversion (4.3) is
7612 // applied. If the template-argument represents a set of
7613 // overloaded functions (or a pointer to such), the matching
7614 // function is selected from the set (13.4).
7615 (ParamType->isPointerType() &&
7616 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
7617 // -- For a non-type template-parameter of type reference to
7618 // function, no conversions apply. If the template-argument
7619 // represents a set of overloaded functions, the matching
7620 // function is selected from the set (13.4).
7621 (ParamType->isReferenceType() &&
7622 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
7623 // -- For a non-type template-parameter of type pointer to
7624 // member function, no conversions apply. If the
7625 // template-argument represents a set of overloaded member
7626 // functions, the matching member function is selected from
7627 // the set (13.4).
7628 (ParamType->isMemberPointerType() &&
7629 ParamType->castAs<MemberPointerType>()->getPointeeType()
7630 ->isFunctionType())) {
7632 if (Arg->getType() == Context.OverloadTy) {
7633 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
7634 true,
7635 FoundResult)) {
7636 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7637 return ExprError();
7639 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7640 if (Res.isInvalid())
7641 return ExprError();
7642 Arg = Res.get();
7643 ArgType = Arg->getType();
7644 } else
7645 return ExprError();
7648 if (!ParamType->isMemberPointerType()) {
7649 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7650 *this, Param, ParamType, Arg, SugaredConverted,
7651 CanonicalConverted))
7652 return ExprError();
7653 return Arg;
7656 if (CheckTemplateArgumentPointerToMember(
7657 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7658 return ExprError();
7659 return Arg;
7662 if (ParamType->isPointerType()) {
7663 // -- for a non-type template-parameter of type pointer to
7664 // object, qualification conversions (4.4) and the
7665 // array-to-pointer conversion (4.2) are applied.
7666 // C++0x also allows a value of std::nullptr_t.
7667 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7668 "Only object pointers allowed here");
7670 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7671 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7672 return ExprError();
7673 return Arg;
7676 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7677 // -- For a non-type template-parameter of type reference to
7678 // object, no conversions apply. The type referred to by the
7679 // reference may be more cv-qualified than the (otherwise
7680 // identical) type of the template-argument. The
7681 // template-parameter is bound directly to the
7682 // template-argument, which must be an lvalue.
7683 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7684 "Only object references allowed here");
7686 if (Arg->getType() == Context.OverloadTy) {
7687 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
7688 ParamRefType->getPointeeType(),
7689 true,
7690 FoundResult)) {
7691 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7692 return ExprError();
7693 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7694 if (Res.isInvalid())
7695 return ExprError();
7696 Arg = Res.get();
7697 ArgType = Arg->getType();
7698 } else
7699 return ExprError();
7702 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7703 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7704 return ExprError();
7705 return Arg;
7708 // Deal with parameters of type std::nullptr_t.
7709 if (ParamType->isNullPtrType()) {
7710 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7711 SugaredConverted = TemplateArgument(Arg);
7712 CanonicalConverted =
7713 Context.getCanonicalTemplateArgument(SugaredConverted);
7714 return Arg;
7717 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
7718 case NPV_NotNullPointer:
7719 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
7720 << Arg->getType() << ParamType;
7721 Diag(Param->getLocation(), diag::note_template_param_here);
7722 return ExprError();
7724 case NPV_Error:
7725 return ExprError();
7727 case NPV_NullPointer:
7728 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7729 SugaredConverted = TemplateArgument(ParamType,
7730 /*isNullPtr=*/true);
7731 CanonicalConverted = TemplateArgument(Context.getCanonicalType(ParamType),
7732 /*isNullPtr=*/true);
7733 return Arg;
7737 // -- For a non-type template-parameter of type pointer to data
7738 // member, qualification conversions (4.4) are applied.
7739 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7741 if (CheckTemplateArgumentPointerToMember(
7742 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7743 return ExprError();
7744 return Arg;
7747 static void DiagnoseTemplateParameterListArityMismatch(
7748 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
7749 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
7751 /// Check a template argument against its corresponding
7752 /// template template parameter.
7754 /// This routine implements the semantics of C++ [temp.arg.template].
7755 /// It returns true if an error occurred, and false otherwise.
7756 bool Sema::CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
7757 TemplateParameterList *Params,
7758 TemplateArgumentLoc &Arg) {
7759 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
7760 TemplateDecl *Template = Name.getAsTemplateDecl();
7761 if (!Template) {
7762 // Any dependent template name is fine.
7763 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7764 return false;
7767 if (Template->isInvalidDecl())
7768 return true;
7770 // C++0x [temp.arg.template]p1:
7771 // A template-argument for a template template-parameter shall be
7772 // the name of a class template or an alias template, expressed as an
7773 // id-expression. When the template-argument names a class template, only
7774 // primary class templates are considered when matching the
7775 // template template argument with the corresponding parameter;
7776 // partial specializations are not considered even if their
7777 // parameter lists match that of the template template parameter.
7779 // Note that we also allow template template parameters here, which
7780 // will happen when we are dealing with, e.g., class template
7781 // partial specializations.
7782 if (!isa<ClassTemplateDecl>(Template) &&
7783 !isa<TemplateTemplateParmDecl>(Template) &&
7784 !isa<TypeAliasTemplateDecl>(Template) &&
7785 !isa<BuiltinTemplateDecl>(Template)) {
7786 assert(isa<FunctionTemplateDecl>(Template) &&
7787 "Only function templates are possible here");
7788 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
7789 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
7790 << Template;
7793 // C++1z [temp.arg.template]p3: (DR 150)
7794 // A template-argument matches a template template-parameter P when P
7795 // is at least as specialized as the template-argument A.
7796 // FIXME: We should enable RelaxedTemplateTemplateArgs by default as it is a
7797 // defect report resolution from C++17 and shouldn't be introduced by
7798 // concepts.
7799 if (getLangOpts().RelaxedTemplateTemplateArgs) {
7800 // Quick check for the common case:
7801 // If P contains a parameter pack, then A [...] matches P if each of A's
7802 // template parameters matches the corresponding template parameter in
7803 // the template-parameter-list of P.
7804 if (TemplateParameterListsAreEqual(
7805 Template->getTemplateParameters(), Params, false,
7806 TPL_TemplateTemplateArgumentMatch, Arg.getLocation()) &&
7807 // If the argument has no associated constraints, then the parameter is
7808 // definitely at least as specialized as the argument.
7809 // Otherwise - we need a more thorough check.
7810 !Template->hasAssociatedConstraints())
7811 return false;
7813 if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
7814 Arg.getLocation())) {
7815 // P2113
7816 // C++20[temp.func.order]p2
7817 // [...] If both deductions succeed, the partial ordering selects the
7818 // more constrained template (if one exists) as determined below.
7819 SmallVector<const Expr *, 3> ParamsAC, TemplateAC;
7820 Params->getAssociatedConstraints(ParamsAC);
7821 // C++2a[temp.arg.template]p3
7822 // [...] In this comparison, if P is unconstrained, the constraints on A
7823 // are not considered.
7824 if (ParamsAC.empty())
7825 return false;
7827 Template->getAssociatedConstraints(TemplateAC);
7829 bool IsParamAtLeastAsConstrained;
7830 if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,
7831 IsParamAtLeastAsConstrained))
7832 return true;
7833 if (!IsParamAtLeastAsConstrained) {
7834 Diag(Arg.getLocation(),
7835 diag::err_template_template_parameter_not_at_least_as_constrained)
7836 << Template << Param << Arg.getSourceRange();
7837 Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;
7838 Diag(Template->getLocation(), diag::note_entity_declared_at)
7839 << Template;
7840 MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Param, ParamsAC, Template,
7841 TemplateAC);
7842 return true;
7844 return false;
7846 // FIXME: Produce better diagnostics for deduction failures.
7849 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
7850 Params,
7851 true,
7852 TPL_TemplateTemplateArgumentMatch,
7853 Arg.getLocation());
7856 /// Given a non-type template argument that refers to a
7857 /// declaration and the type of its corresponding non-type template
7858 /// parameter, produce an expression that properly refers to that
7859 /// declaration.
7860 ExprResult
7861 Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
7862 QualType ParamType,
7863 SourceLocation Loc) {
7864 // C++ [temp.param]p8:
7866 // A non-type template-parameter of type "array of T" or
7867 // "function returning T" is adjusted to be of type "pointer to
7868 // T" or "pointer to function returning T", respectively.
7869 if (ParamType->isArrayType())
7870 ParamType = Context.getArrayDecayedType(ParamType);
7871 else if (ParamType->isFunctionType())
7872 ParamType = Context.getPointerType(ParamType);
7874 // For a NULL non-type template argument, return nullptr casted to the
7875 // parameter's type.
7876 if (Arg.getKind() == TemplateArgument::NullPtr) {
7877 return ImpCastExprToType(
7878 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
7879 ParamType,
7880 ParamType->getAs<MemberPointerType>()
7881 ? CK_NullToMemberPointer
7882 : CK_NullToPointer);
7884 assert(Arg.getKind() == TemplateArgument::Declaration &&
7885 "Only declaration template arguments permitted here");
7887 ValueDecl *VD = Arg.getAsDecl();
7889 CXXScopeSpec SS;
7890 if (ParamType->isMemberPointerType()) {
7891 // If this is a pointer to member, we need to use a qualified name to
7892 // form a suitable pointer-to-member constant.
7893 assert(VD->getDeclContext()->isRecord() &&
7894 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
7895 isa<IndirectFieldDecl>(VD)));
7896 QualType ClassType
7897 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
7898 NestedNameSpecifier *Qualifier
7899 = NestedNameSpecifier::Create(Context, nullptr, false,
7900 ClassType.getTypePtr());
7901 SS.MakeTrivial(Context, Qualifier, Loc);
7904 ExprResult RefExpr = BuildDeclarationNameExpr(
7905 SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);
7906 if (RefExpr.isInvalid())
7907 return ExprError();
7909 // For a pointer, the argument declaration is the pointee. Take its address.
7910 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
7911 if (ParamType->isPointerType() && !ElemT.isNull() &&
7912 Context.hasSimilarType(ElemT, ParamType->getPointeeType())) {
7913 // Decay an array argument if we want a pointer to its first element.
7914 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
7915 if (RefExpr.isInvalid())
7916 return ExprError();
7917 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
7918 // For any other pointer, take the address (or form a pointer-to-member).
7919 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
7920 if (RefExpr.isInvalid())
7921 return ExprError();
7922 } else if (ParamType->isRecordType()) {
7923 assert(isa<TemplateParamObjectDecl>(VD) &&
7924 "arg for class template param not a template parameter object");
7925 // No conversions apply in this case.
7926 return RefExpr;
7927 } else {
7928 assert(ParamType->isReferenceType() &&
7929 "unexpected type for decl template argument");
7932 // At this point we should have the right value category.
7933 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
7934 "value kind mismatch for non-type template argument");
7936 // The type of the template parameter can differ from the type of the
7937 // argument in various ways; convert it now if necessary.
7938 QualType DestExprType = ParamType.getNonLValueExprType(Context);
7939 if (!Context.hasSameType(RefExpr.get()->getType(), DestExprType)) {
7940 CastKind CK;
7941 QualType Ignored;
7942 if (Context.hasSimilarType(RefExpr.get()->getType(), DestExprType) ||
7943 IsFunctionConversion(RefExpr.get()->getType(), DestExprType, Ignored)) {
7944 CK = CK_NoOp;
7945 } else if (ParamType->isVoidPointerType() &&
7946 RefExpr.get()->getType()->isPointerType()) {
7947 CK = CK_BitCast;
7948 } else {
7949 // FIXME: Pointers to members can need conversion derived-to-base or
7950 // base-to-derived conversions. We currently don't retain enough
7951 // information to convert properly (we need to track a cast path or
7952 // subobject number in the template argument).
7953 llvm_unreachable(
7954 "unexpected conversion required for non-type template argument");
7956 RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK,
7957 RefExpr.get()->getValueKind());
7960 return RefExpr;
7963 /// Construct a new expression that refers to the given
7964 /// integral template argument with the given source-location
7965 /// information.
7967 /// This routine takes care of the mapping from an integral template
7968 /// argument (which may have any integral type) to the appropriate
7969 /// literal value.
7970 ExprResult
7971 Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
7972 SourceLocation Loc) {
7973 assert(Arg.getKind() == TemplateArgument::Integral &&
7974 "Operation is only valid for integral template arguments");
7975 QualType OrigT = Arg.getIntegralType();
7977 // If this is an enum type that we're instantiating, we need to use an integer
7978 // type the same size as the enumerator. We don't want to build an
7979 // IntegerLiteral with enum type. The integer type of an enum type can be of
7980 // any integral type with C++11 enum classes, make sure we create the right
7981 // type of literal for it.
7982 QualType T = OrigT;
7983 if (const EnumType *ET = OrigT->getAs<EnumType>())
7984 T = ET->getDecl()->getIntegerType();
7986 Expr *E;
7987 if (T->isAnyCharacterType()) {
7988 CharacterLiteral::CharacterKind Kind;
7989 if (T->isWideCharType())
7990 Kind = CharacterLiteral::Wide;
7991 else if (T->isChar8Type() && getLangOpts().Char8)
7992 Kind = CharacterLiteral::UTF8;
7993 else if (T->isChar16Type())
7994 Kind = CharacterLiteral::UTF16;
7995 else if (T->isChar32Type())
7996 Kind = CharacterLiteral::UTF32;
7997 else
7998 Kind = CharacterLiteral::Ascii;
8000 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
8001 Kind, T, Loc);
8002 } else if (T->isBooleanType()) {
8003 E = CXXBoolLiteralExpr::Create(Context, Arg.getAsIntegral().getBoolValue(),
8004 T, Loc);
8005 } else if (T->isNullPtrType()) {
8006 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
8007 } else {
8008 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
8011 if (OrigT->isEnumeralType()) {
8012 // FIXME: This is a hack. We need a better way to handle substituted
8013 // non-type template parameters.
8014 E = CStyleCastExpr::Create(Context, OrigT, VK_PRValue, CK_IntegralCast, E,
8015 nullptr, CurFPFeatureOverrides(),
8016 Context.getTrivialTypeSourceInfo(OrigT, Loc),
8017 Loc, Loc);
8020 return E;
8023 /// Match two template parameters within template parameter lists.
8024 static bool MatchTemplateParameterKind(
8025 Sema &S, NamedDecl *New,
8026 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
8027 const NamedDecl *OldInstFrom, bool Complain,
8028 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8029 // Check the actual kind (type, non-type, template).
8030 if (Old->getKind() != New->getKind()) {
8031 if (Complain) {
8032 unsigned NextDiag = diag::err_template_param_different_kind;
8033 if (TemplateArgLoc.isValid()) {
8034 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8035 NextDiag = diag::note_template_param_different_kind;
8037 S.Diag(New->getLocation(), NextDiag)
8038 << (Kind != Sema::TPL_TemplateMatch);
8039 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
8040 << (Kind != Sema::TPL_TemplateMatch);
8043 return false;
8046 // Check that both are parameter packs or neither are parameter packs.
8047 // However, if we are matching a template template argument to a
8048 // template template parameter, the template template parameter can have
8049 // a parameter pack where the template template argument does not.
8050 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
8051 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
8052 Old->isTemplateParameterPack())) {
8053 if (Complain) {
8054 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
8055 if (TemplateArgLoc.isValid()) {
8056 S.Diag(TemplateArgLoc,
8057 diag::err_template_arg_template_params_mismatch);
8058 NextDiag = diag::note_template_parameter_pack_non_pack;
8061 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
8062 : isa<NonTypeTemplateParmDecl>(New)? 1
8063 : 2;
8064 S.Diag(New->getLocation(), NextDiag)
8065 << ParamKind << New->isParameterPack();
8066 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
8067 << ParamKind << Old->isParameterPack();
8070 return false;
8073 // For non-type template parameters, check the type of the parameter.
8074 if (NonTypeTemplateParmDecl *OldNTTP
8075 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
8076 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
8078 // If we are matching a template template argument to a template
8079 // template parameter and one of the non-type template parameter types
8080 // is dependent, then we must wait until template instantiation time
8081 // to actually compare the arguments.
8082 if (Kind != Sema::TPL_TemplateTemplateArgumentMatch ||
8083 (!OldNTTP->getType()->isDependentType() &&
8084 !NewNTTP->getType()->isDependentType())) {
8085 // C++20 [temp.over.link]p6:
8086 // Two [non-type] template-parameters are equivalent [if] they have
8087 // equivalent types ignoring the use of type-constraints for
8088 // placeholder types
8089 QualType OldType = S.Context.getUnconstrainedType(OldNTTP->getType());
8090 QualType NewType = S.Context.getUnconstrainedType(NewNTTP->getType());
8091 if (!S.Context.hasSameType(OldType, NewType)) {
8092 if (Complain) {
8093 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
8094 if (TemplateArgLoc.isValid()) {
8095 S.Diag(TemplateArgLoc,
8096 diag::err_template_arg_template_params_mismatch);
8097 NextDiag = diag::note_template_nontype_parm_different_type;
8099 S.Diag(NewNTTP->getLocation(), NextDiag)
8100 << NewNTTP->getType()
8101 << (Kind != Sema::TPL_TemplateMatch);
8102 S.Diag(OldNTTP->getLocation(),
8103 diag::note_template_nontype_parm_prev_declaration)
8104 << OldNTTP->getType();
8107 return false;
8111 // For template template parameters, check the template parameter types.
8112 // The template parameter lists of template template
8113 // parameters must agree.
8114 else if (TemplateTemplateParmDecl *OldTTP =
8115 dyn_cast<TemplateTemplateParmDecl>(Old)) {
8116 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
8117 if (!S.TemplateParameterListsAreEqual(
8118 NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom,
8119 OldTTP->getTemplateParameters(), Complain,
8120 (Kind == Sema::TPL_TemplateMatch
8121 ? Sema::TPL_TemplateTemplateParmMatch
8122 : Kind),
8123 TemplateArgLoc))
8124 return false;
8127 if (Kind != Sema::TPL_TemplateParamsEquivalent &&
8128 Kind != Sema::TPL_TemplateTemplateArgumentMatch &&
8129 !isa<TemplateTemplateParmDecl>(Old)) {
8130 const Expr *NewC = nullptr, *OldC = nullptr;
8132 if (isa<TemplateTypeParmDecl>(New)) {
8133 if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint())
8134 NewC = TC->getImmediatelyDeclaredConstraint();
8135 if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint())
8136 OldC = TC->getImmediatelyDeclaredConstraint();
8137 } else if (isa<NonTypeTemplateParmDecl>(New)) {
8138 if (const Expr *E = cast<NonTypeTemplateParmDecl>(New)
8139 ->getPlaceholderTypeConstraint())
8140 NewC = E;
8141 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Old)
8142 ->getPlaceholderTypeConstraint())
8143 OldC = E;
8144 } else
8145 llvm_unreachable("unexpected template parameter type");
8147 auto Diagnose = [&] {
8148 S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
8149 diag::err_template_different_type_constraint);
8150 S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
8151 diag::note_template_prev_declaration) << /*declaration*/0;
8154 if (!NewC != !OldC) {
8155 if (Complain)
8156 Diagnose();
8157 return false;
8160 if (NewC) {
8161 if (!S.AreConstraintExpressionsEqual(OldInstFrom, OldC, NewInstFrom,
8162 NewC)) {
8163 if (Complain)
8164 Diagnose();
8165 return false;
8170 return true;
8173 /// Diagnose a known arity mismatch when comparing template argument
8174 /// lists.
8175 static
8176 void DiagnoseTemplateParameterListArityMismatch(Sema &S,
8177 TemplateParameterList *New,
8178 TemplateParameterList *Old,
8179 Sema::TemplateParameterListEqualKind Kind,
8180 SourceLocation TemplateArgLoc) {
8181 unsigned NextDiag = diag::err_template_param_list_different_arity;
8182 if (TemplateArgLoc.isValid()) {
8183 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8184 NextDiag = diag::note_template_param_list_different_arity;
8186 S.Diag(New->getTemplateLoc(), NextDiag)
8187 << (New->size() > Old->size())
8188 << (Kind != Sema::TPL_TemplateMatch)
8189 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
8190 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
8191 << (Kind != Sema::TPL_TemplateMatch)
8192 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
8195 /// Determine whether the given template parameter lists are
8196 /// equivalent.
8198 /// \param New The new template parameter list, typically written in the
8199 /// source code as part of a new template declaration.
8201 /// \param Old The old template parameter list, typically found via
8202 /// name lookup of the template declared with this template parameter
8203 /// list.
8205 /// \param Complain If true, this routine will produce a diagnostic if
8206 /// the template parameter lists are not equivalent.
8208 /// \param Kind describes how we are to match the template parameter lists.
8210 /// \param TemplateArgLoc If this source location is valid, then we
8211 /// are actually checking the template parameter list of a template
8212 /// argument (New) against the template parameter list of its
8213 /// corresponding template template parameter (Old). We produce
8214 /// slightly different diagnostics in this scenario.
8216 /// \returns True if the template parameter lists are equal, false
8217 /// otherwise.
8218 bool Sema::TemplateParameterListsAreEqual(
8219 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
8220 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
8221 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8222 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
8223 if (Complain)
8224 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
8225 TemplateArgLoc);
8227 return false;
8230 // C++0x [temp.arg.template]p3:
8231 // A template-argument matches a template template-parameter (call it P)
8232 // when each of the template parameters in the template-parameter-list of
8233 // the template-argument's corresponding class template or alias template
8234 // (call it A) matches the corresponding template parameter in the
8235 // template-parameter-list of P. [...]
8236 TemplateParameterList::iterator NewParm = New->begin();
8237 TemplateParameterList::iterator NewParmEnd = New->end();
8238 for (TemplateParameterList::iterator OldParm = Old->begin(),
8239 OldParmEnd = Old->end();
8240 OldParm != OldParmEnd; ++OldParm) {
8241 if (Kind != TPL_TemplateTemplateArgumentMatch ||
8242 !(*OldParm)->isTemplateParameterPack()) {
8243 if (NewParm == NewParmEnd) {
8244 if (Complain)
8245 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
8246 TemplateArgLoc);
8248 return false;
8251 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
8252 OldInstFrom, Complain, Kind,
8253 TemplateArgLoc))
8254 return false;
8256 ++NewParm;
8257 continue;
8260 // C++0x [temp.arg.template]p3:
8261 // [...] When P's template- parameter-list contains a template parameter
8262 // pack (14.5.3), the template parameter pack will match zero or more
8263 // template parameters or template parameter packs in the
8264 // template-parameter-list of A with the same type and form as the
8265 // template parameter pack in P (ignoring whether those template
8266 // parameters are template parameter packs).
8267 for (; NewParm != NewParmEnd; ++NewParm) {
8268 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
8269 OldInstFrom, Complain, Kind,
8270 TemplateArgLoc))
8271 return false;
8275 // Make sure we exhausted all of the arguments.
8276 if (NewParm != NewParmEnd) {
8277 if (Complain)
8278 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
8279 TemplateArgLoc);
8281 return false;
8284 if (Kind != TPL_TemplateTemplateArgumentMatch &&
8285 Kind != TPL_TemplateParamsEquivalent) {
8286 const Expr *NewRC = New->getRequiresClause();
8287 const Expr *OldRC = Old->getRequiresClause();
8289 auto Diagnose = [&] {
8290 Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
8291 diag::err_template_different_requires_clause);
8292 Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
8293 diag::note_template_prev_declaration) << /*declaration*/0;
8296 if (!NewRC != !OldRC) {
8297 if (Complain)
8298 Diagnose();
8299 return false;
8302 if (NewRC) {
8303 if (!AreConstraintExpressionsEqual(OldInstFrom, OldRC, NewInstFrom,
8304 NewRC)) {
8305 if (Complain)
8306 Diagnose();
8307 return false;
8312 return true;
8315 /// Check whether a template can be declared within this scope.
8317 /// If the template declaration is valid in this scope, returns
8318 /// false. Otherwise, issues a diagnostic and returns true.
8319 bool
8320 Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
8321 if (!S)
8322 return false;
8324 // Find the nearest enclosing declaration scope.
8325 while ((S->getFlags() & Scope::DeclScope) == 0 ||
8326 (S->getFlags() & Scope::TemplateParamScope) != 0)
8327 S = S->getParent();
8329 // C++ [temp.pre]p6: [P2096]
8330 // A template, explicit specialization, or partial specialization shall not
8331 // have C linkage.
8332 DeclContext *Ctx = S->getEntity();
8333 if (Ctx && Ctx->isExternCContext()) {
8334 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
8335 << TemplateParams->getSourceRange();
8336 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
8337 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
8338 return true;
8340 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
8342 // C++ [temp]p2:
8343 // A template-declaration can appear only as a namespace scope or
8344 // class scope declaration.
8345 // C++ [temp.expl.spec]p3:
8346 // An explicit specialization may be declared in any scope in which the
8347 // corresponding primary template may be defined.
8348 // C++ [temp.class.spec]p6: [P2096]
8349 // A partial specialization may be declared in any scope in which the
8350 // corresponding primary template may be defined.
8351 if (Ctx) {
8352 if (Ctx->isFileContext())
8353 return false;
8354 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
8355 // C++ [temp.mem]p2:
8356 // A local class shall not have member templates.
8357 if (RD->isLocalClass())
8358 return Diag(TemplateParams->getTemplateLoc(),
8359 diag::err_template_inside_local_class)
8360 << TemplateParams->getSourceRange();
8361 else
8362 return false;
8366 return Diag(TemplateParams->getTemplateLoc(),
8367 diag::err_template_outside_namespace_or_class_scope)
8368 << TemplateParams->getSourceRange();
8371 /// Determine what kind of template specialization the given declaration
8372 /// is.
8373 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
8374 if (!D)
8375 return TSK_Undeclared;
8377 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
8378 return Record->getTemplateSpecializationKind();
8379 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
8380 return Function->getTemplateSpecializationKind();
8381 if (VarDecl *Var = dyn_cast<VarDecl>(D))
8382 return Var->getTemplateSpecializationKind();
8384 return TSK_Undeclared;
8387 /// Check whether a specialization is well-formed in the current
8388 /// context.
8390 /// This routine determines whether a template specialization can be declared
8391 /// in the current context (C++ [temp.expl.spec]p2).
8393 /// \param S the semantic analysis object for which this check is being
8394 /// performed.
8396 /// \param Specialized the entity being specialized or instantiated, which
8397 /// may be a kind of template (class template, function template, etc.) or
8398 /// a member of a class template (member function, static data member,
8399 /// member class).
8401 /// \param PrevDecl the previous declaration of this entity, if any.
8403 /// \param Loc the location of the explicit specialization or instantiation of
8404 /// this entity.
8406 /// \param IsPartialSpecialization whether this is a partial specialization of
8407 /// a class template.
8409 /// \returns true if there was an error that we cannot recover from, false
8410 /// otherwise.
8411 static bool CheckTemplateSpecializationScope(Sema &S,
8412 NamedDecl *Specialized,
8413 NamedDecl *PrevDecl,
8414 SourceLocation Loc,
8415 bool IsPartialSpecialization) {
8416 // Keep these "kind" numbers in sync with the %select statements in the
8417 // various diagnostics emitted by this routine.
8418 int EntityKind = 0;
8419 if (isa<ClassTemplateDecl>(Specialized))
8420 EntityKind = IsPartialSpecialization? 1 : 0;
8421 else if (isa<VarTemplateDecl>(Specialized))
8422 EntityKind = IsPartialSpecialization ? 3 : 2;
8423 else if (isa<FunctionTemplateDecl>(Specialized))
8424 EntityKind = 4;
8425 else if (isa<CXXMethodDecl>(Specialized))
8426 EntityKind = 5;
8427 else if (isa<VarDecl>(Specialized))
8428 EntityKind = 6;
8429 else if (isa<RecordDecl>(Specialized))
8430 EntityKind = 7;
8431 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
8432 EntityKind = 8;
8433 else {
8434 S.Diag(Loc, diag::err_template_spec_unknown_kind)
8435 << S.getLangOpts().CPlusPlus11;
8436 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8437 return true;
8440 // C++ [temp.expl.spec]p2:
8441 // An explicit specialization may be declared in any scope in which
8442 // the corresponding primary template may be defined.
8443 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8444 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
8445 << Specialized;
8446 return true;
8449 // C++ [temp.class.spec]p6:
8450 // A class template partial specialization may be declared in any
8451 // scope in which the primary template may be defined.
8452 DeclContext *SpecializedContext =
8453 Specialized->getDeclContext()->getRedeclContext();
8454 DeclContext *DC = S.CurContext->getRedeclContext();
8456 // Make sure that this redeclaration (or definition) occurs in the same
8457 // scope or an enclosing namespace.
8458 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
8459 : DC->Equals(SpecializedContext))) {
8460 if (isa<TranslationUnitDecl>(SpecializedContext))
8461 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
8462 << EntityKind << Specialized;
8463 else {
8464 auto *ND = cast<NamedDecl>(SpecializedContext);
8465 int Diag = diag::err_template_spec_redecl_out_of_scope;
8466 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
8467 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
8468 S.Diag(Loc, Diag) << EntityKind << Specialized
8469 << ND << isa<CXXRecordDecl>(ND);
8472 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8474 // Don't allow specializing in the wrong class during error recovery.
8475 // Otherwise, things can go horribly wrong.
8476 if (DC->isRecord())
8477 return true;
8480 return false;
8483 static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
8484 if (!E->isTypeDependent())
8485 return SourceLocation();
8486 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8487 Checker.TraverseStmt(E);
8488 if (Checker.MatchLoc.isInvalid())
8489 return E->getSourceRange();
8490 return Checker.MatchLoc;
8493 static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
8494 if (!TL.getType()->isDependentType())
8495 return SourceLocation();
8496 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8497 Checker.TraverseTypeLoc(TL);
8498 if (Checker.MatchLoc.isInvalid())
8499 return TL.getSourceRange();
8500 return Checker.MatchLoc;
8503 /// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
8504 /// that checks non-type template partial specialization arguments.
8505 static bool CheckNonTypeTemplatePartialSpecializationArgs(
8506 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
8507 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
8508 for (unsigned I = 0; I != NumArgs; ++I) {
8509 if (Args[I].getKind() == TemplateArgument::Pack) {
8510 if (CheckNonTypeTemplatePartialSpecializationArgs(
8511 S, TemplateNameLoc, Param, Args[I].pack_begin(),
8512 Args[I].pack_size(), IsDefaultArgument))
8513 return true;
8515 continue;
8518 if (Args[I].getKind() != TemplateArgument::Expression)
8519 continue;
8521 Expr *ArgExpr = Args[I].getAsExpr();
8523 // We can have a pack expansion of any of the bullets below.
8524 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
8525 ArgExpr = Expansion->getPattern();
8527 // Strip off any implicit casts we added as part of type checking.
8528 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8529 ArgExpr = ICE->getSubExpr();
8531 // C++ [temp.class.spec]p8:
8532 // A non-type argument is non-specialized if it is the name of a
8533 // non-type parameter. All other non-type arguments are
8534 // specialized.
8536 // Below, we check the two conditions that only apply to
8537 // specialized non-type arguments, so skip any non-specialized
8538 // arguments.
8539 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
8540 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
8541 continue;
8543 // C++ [temp.class.spec]p9:
8544 // Within the argument list of a class template partial
8545 // specialization, the following restrictions apply:
8546 // -- A partially specialized non-type argument expression
8547 // shall not involve a template parameter of the partial
8548 // specialization except when the argument expression is a
8549 // simple identifier.
8550 // -- The type of a template parameter corresponding to a
8551 // specialized non-type argument shall not be dependent on a
8552 // parameter of the specialization.
8553 // DR1315 removes the first bullet, leaving an incoherent set of rules.
8554 // We implement a compromise between the original rules and DR1315:
8555 // -- A specialized non-type template argument shall not be
8556 // type-dependent and the corresponding template parameter
8557 // shall have a non-dependent type.
8558 SourceRange ParamUseRange =
8559 findTemplateParameterInType(Param->getDepth(), ArgExpr);
8560 if (ParamUseRange.isValid()) {
8561 if (IsDefaultArgument) {
8562 S.Diag(TemplateNameLoc,
8563 diag::err_dependent_non_type_arg_in_partial_spec);
8564 S.Diag(ParamUseRange.getBegin(),
8565 diag::note_dependent_non_type_default_arg_in_partial_spec)
8566 << ParamUseRange;
8567 } else {
8568 S.Diag(ParamUseRange.getBegin(),
8569 diag::err_dependent_non_type_arg_in_partial_spec)
8570 << ParamUseRange;
8572 return true;
8575 ParamUseRange = findTemplateParameter(
8576 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
8577 if (ParamUseRange.isValid()) {
8578 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8579 diag::err_dependent_typed_non_type_arg_in_partial_spec)
8580 << Param->getType();
8581 S.Diag(Param->getLocation(), diag::note_template_param_here)
8582 << (IsDefaultArgument ? ParamUseRange : SourceRange())
8583 << ParamUseRange;
8584 return true;
8588 return false;
8591 /// Check the non-type template arguments of a class template
8592 /// partial specialization according to C++ [temp.class.spec]p9.
8594 /// \param TemplateNameLoc the location of the template name.
8595 /// \param PrimaryTemplate the template parameters of the primary class
8596 /// template.
8597 /// \param NumExplicit the number of explicitly-specified template arguments.
8598 /// \param TemplateArgs the template arguments of the class template
8599 /// partial specialization.
8601 /// \returns \c true if there was an error, \c false otherwise.
8602 bool Sema::CheckTemplatePartialSpecializationArgs(
8603 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8604 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8605 // We have to be conservative when checking a template in a dependent
8606 // context.
8607 if (PrimaryTemplate->getDeclContext()->isDependentContext())
8608 return false;
8610 TemplateParameterList *TemplateParams =
8611 PrimaryTemplate->getTemplateParameters();
8612 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8613 NonTypeTemplateParmDecl *Param
8614 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
8615 if (!Param)
8616 continue;
8618 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
8619 Param, &TemplateArgs[I],
8620 1, I >= NumExplicit))
8621 return true;
8624 return false;
8627 DeclResult Sema::ActOnClassTemplateSpecialization(
8628 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8629 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8630 TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
8631 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8632 assert(TUK != TUK_Reference && "References are not specializations");
8634 // NOTE: KWLoc is the location of the tag keyword. This will instead
8635 // store the location of the outermost template keyword in the declaration.
8636 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
8637 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
8638 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8639 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8640 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8642 // Find the class template we're specializing
8643 TemplateName Name = TemplateId.Template.get();
8644 ClassTemplateDecl *ClassTemplate
8645 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
8647 if (!ClassTemplate) {
8648 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
8649 << (Name.getAsTemplateDecl() &&
8650 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
8651 return true;
8654 bool isMemberSpecialization = false;
8655 bool isPartialSpecialization = false;
8657 // Check the validity of the template headers that introduce this
8658 // template.
8659 // FIXME: We probably shouldn't complain about these headers for
8660 // friend declarations.
8661 bool Invalid = false;
8662 TemplateParameterList *TemplateParams =
8663 MatchTemplateParametersToScopeSpecifier(
8664 KWLoc, TemplateNameLoc, SS, &TemplateId,
8665 TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
8666 Invalid);
8667 if (Invalid)
8668 return true;
8670 // Check that we can declare a template specialization here.
8671 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8672 return true;
8674 if (TemplateParams && TemplateParams->size() > 0) {
8675 isPartialSpecialization = true;
8677 if (TUK == TUK_Friend) {
8678 Diag(KWLoc, diag::err_partial_specialization_friend)
8679 << SourceRange(LAngleLoc, RAngleLoc);
8680 return true;
8683 // C++ [temp.class.spec]p10:
8684 // The template parameter list of a specialization shall not
8685 // contain default template argument values.
8686 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8687 Decl *Param = TemplateParams->getParam(I);
8688 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
8689 if (TTP->hasDefaultArgument()) {
8690 Diag(TTP->getDefaultArgumentLoc(),
8691 diag::err_default_arg_in_partial_spec);
8692 TTP->removeDefaultArgument();
8694 } else if (NonTypeTemplateParmDecl *NTTP
8695 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
8696 if (Expr *DefArg = NTTP->getDefaultArgument()) {
8697 Diag(NTTP->getDefaultArgumentLoc(),
8698 diag::err_default_arg_in_partial_spec)
8699 << DefArg->getSourceRange();
8700 NTTP->removeDefaultArgument();
8702 } else {
8703 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
8704 if (TTP->hasDefaultArgument()) {
8705 Diag(TTP->getDefaultArgument().getLocation(),
8706 diag::err_default_arg_in_partial_spec)
8707 << TTP->getDefaultArgument().getSourceRange();
8708 TTP->removeDefaultArgument();
8712 } else if (TemplateParams) {
8713 if (TUK == TUK_Friend)
8714 Diag(KWLoc, diag::err_template_spec_friend)
8715 << FixItHint::CreateRemoval(
8716 SourceRange(TemplateParams->getTemplateLoc(),
8717 TemplateParams->getRAngleLoc()))
8718 << SourceRange(LAngleLoc, RAngleLoc);
8719 } else {
8720 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
8723 // Check that the specialization uses the same tag kind as the
8724 // original template.
8725 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8726 assert(Kind != TagTypeKind::Enum &&
8727 "Invalid enum tag in class template spec!");
8728 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
8729 Kind, TUK == TUK_Definition, KWLoc,
8730 ClassTemplate->getIdentifier())) {
8731 Diag(KWLoc, diag::err_use_with_wrong_tag)
8732 << ClassTemplate
8733 << FixItHint::CreateReplacement(KWLoc,
8734 ClassTemplate->getTemplatedDecl()->getKindName());
8735 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8736 diag::note_previous_use);
8737 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8740 // Translate the parser's template argument list in our AST format.
8741 TemplateArgumentListInfo TemplateArgs =
8742 makeTemplateArgumentListInfo(*this, TemplateId);
8744 // Check for unexpanded parameter packs in any of the template arguments.
8745 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8746 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
8747 UPPC_PartialSpecialization))
8748 return true;
8750 // Check that the template argument list is well-formed for this
8751 // template.
8752 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
8753 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
8754 false, SugaredConverted, CanonicalConverted,
8755 /*UpdateArgsWithConversions=*/true))
8756 return true;
8758 // Find the class template (partial) specialization declaration that
8759 // corresponds to these arguments.
8760 if (isPartialSpecialization) {
8761 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
8762 TemplateArgs.size(),
8763 CanonicalConverted))
8764 return true;
8766 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8767 // also do it during instantiation.
8768 if (!Name.isDependent() &&
8769 !TemplateSpecializationType::anyDependentTemplateArguments(
8770 TemplateArgs, CanonicalConverted)) {
8771 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
8772 << ClassTemplate->getDeclName();
8773 isPartialSpecialization = false;
8777 void *InsertPos = nullptr;
8778 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8780 if (isPartialSpecialization)
8781 PrevDecl = ClassTemplate->findPartialSpecialization(
8782 CanonicalConverted, TemplateParams, InsertPos);
8783 else
8784 PrevDecl = ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
8786 ClassTemplateSpecializationDecl *Specialization = nullptr;
8788 // Check whether we can declare a class template specialization in
8789 // the current scope.
8790 if (TUK != TUK_Friend &&
8791 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
8792 TemplateNameLoc,
8793 isPartialSpecialization))
8794 return true;
8796 // The canonical type
8797 QualType CanonType;
8798 if (isPartialSpecialization) {
8799 // Build the canonical type that describes the converted template
8800 // arguments of the class template partial specialization.
8801 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
8802 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
8803 CanonicalConverted);
8805 if (Context.hasSameType(CanonType,
8806 ClassTemplate->getInjectedClassNameSpecialization()) &&
8807 (!Context.getLangOpts().CPlusPlus20 ||
8808 !TemplateParams->hasAssociatedConstraints())) {
8809 // C++ [temp.class.spec]p9b3:
8811 // -- The argument list of the specialization shall not be identical
8812 // to the implicit argument list of the primary template.
8814 // This rule has since been removed, because it's redundant given DR1495,
8815 // but we keep it because it produces better diagnostics and recovery.
8816 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
8817 << /*class template*/0 << (TUK == TUK_Definition)
8818 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
8819 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
8820 ClassTemplate->getIdentifier(),
8821 TemplateNameLoc,
8822 Attr,
8823 TemplateParams,
8824 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
8825 /*FriendLoc*/SourceLocation(),
8826 TemplateParameterLists.size() - 1,
8827 TemplateParameterLists.data());
8830 // Create a new class template partial specialization declaration node.
8831 ClassTemplatePartialSpecializationDecl *PrevPartial
8832 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
8833 ClassTemplatePartialSpecializationDecl *Partial =
8834 ClassTemplatePartialSpecializationDecl::Create(
8835 Context, Kind, ClassTemplate->getDeclContext(), KWLoc,
8836 TemplateNameLoc, TemplateParams, ClassTemplate, CanonicalConverted,
8837 TemplateArgs, CanonType, PrevPartial);
8838 SetNestedNameSpecifier(*this, Partial, SS);
8839 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
8840 Partial->setTemplateParameterListsInfo(
8841 Context, TemplateParameterLists.drop_back(1));
8844 if (!PrevPartial)
8845 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
8846 Specialization = Partial;
8848 // If we are providing an explicit specialization of a member class
8849 // template specialization, make a note of that.
8850 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
8851 PrevPartial->setMemberSpecialization();
8853 CheckTemplatePartialSpecialization(Partial);
8854 } else {
8855 // Create a new class template specialization declaration node for
8856 // this explicit specialization or friend declaration.
8857 Specialization = ClassTemplateSpecializationDecl::Create(
8858 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
8859 ClassTemplate, CanonicalConverted, PrevDecl);
8860 SetNestedNameSpecifier(*this, Specialization, SS);
8861 if (TemplateParameterLists.size() > 0) {
8862 Specialization->setTemplateParameterListsInfo(Context,
8863 TemplateParameterLists);
8866 if (!PrevDecl)
8867 ClassTemplate->AddSpecialization(Specialization, InsertPos);
8869 if (CurContext->isDependentContext()) {
8870 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
8871 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
8872 CanonicalConverted);
8873 } else {
8874 CanonType = Context.getTypeDeclType(Specialization);
8878 // C++ [temp.expl.spec]p6:
8879 // If a template, a member template or the member of a class template is
8880 // explicitly specialized then that specialization shall be declared
8881 // before the first use of that specialization that would cause an implicit
8882 // instantiation to take place, in every translation unit in which such a
8883 // use occurs; no diagnostic is required.
8884 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
8885 bool Okay = false;
8886 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8887 // Is there any previous explicit specialization declaration?
8888 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
8889 Okay = true;
8890 break;
8894 if (!Okay) {
8895 SourceRange Range(TemplateNameLoc, RAngleLoc);
8896 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
8897 << Context.getTypeDeclType(Specialization) << Range;
8899 Diag(PrevDecl->getPointOfInstantiation(),
8900 diag::note_instantiation_required_here)
8901 << (PrevDecl->getTemplateSpecializationKind()
8902 != TSK_ImplicitInstantiation);
8903 return true;
8907 // If this is not a friend, note that this is an explicit specialization.
8908 if (TUK != TUK_Friend)
8909 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
8911 // Check that this isn't a redefinition of this specialization.
8912 if (TUK == TUK_Definition) {
8913 RecordDecl *Def = Specialization->getDefinition();
8914 NamedDecl *Hidden = nullptr;
8915 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
8916 SkipBody->ShouldSkip = true;
8917 SkipBody->Previous = Def;
8918 makeMergedDefinitionVisible(Hidden);
8919 } else if (Def) {
8920 SourceRange Range(TemplateNameLoc, RAngleLoc);
8921 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
8922 Diag(Def->getLocation(), diag::note_previous_definition);
8923 Specialization->setInvalidDecl();
8924 return true;
8928 ProcessDeclAttributeList(S, Specialization, Attr);
8930 // Add alignment attributes if necessary; these attributes are checked when
8931 // the ASTContext lays out the structure.
8932 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
8933 AddAlignmentAttributesForRecord(Specialization);
8934 AddMsStructLayoutForRecord(Specialization);
8937 if (ModulePrivateLoc.isValid())
8938 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
8939 << (isPartialSpecialization? 1 : 0)
8940 << FixItHint::CreateRemoval(ModulePrivateLoc);
8942 // Build the fully-sugared type for this class template
8943 // specialization as the user wrote in the specialization
8944 // itself. This means that we'll pretty-print the type retrieved
8945 // from the specialization's declaration the way that the user
8946 // actually wrote the specialization, rather than formatting the
8947 // name based on the "canonical" representation used to store the
8948 // template arguments in the specialization.
8949 TypeSourceInfo *WrittenTy
8950 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
8951 TemplateArgs, CanonType);
8952 if (TUK != TUK_Friend) {
8953 Specialization->setTypeAsWritten(WrittenTy);
8954 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
8957 // C++ [temp.expl.spec]p9:
8958 // A template explicit specialization is in the scope of the
8959 // namespace in which the template was defined.
8961 // We actually implement this paragraph where we set the semantic
8962 // context (in the creation of the ClassTemplateSpecializationDecl),
8963 // but we also maintain the lexical context where the actual
8964 // definition occurs.
8965 Specialization->setLexicalDeclContext(CurContext);
8967 // We may be starting the definition of this specialization.
8968 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
8969 Specialization->startDefinition();
8971 if (TUK == TUK_Friend) {
8972 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
8973 TemplateNameLoc,
8974 WrittenTy,
8975 /*FIXME:*/KWLoc);
8976 Friend->setAccess(AS_public);
8977 CurContext->addDecl(Friend);
8978 } else {
8979 // Add the specialization into its lexical context, so that it can
8980 // be seen when iterating through the list of declarations in that
8981 // context. However, specializations are not found by name lookup.
8982 CurContext->addDecl(Specialization);
8985 if (SkipBody && SkipBody->ShouldSkip)
8986 return SkipBody->Previous;
8988 return Specialization;
8991 Decl *Sema::ActOnTemplateDeclarator(Scope *S,
8992 MultiTemplateParamsArg TemplateParameterLists,
8993 Declarator &D) {
8994 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
8995 ActOnDocumentableDecl(NewDecl);
8996 return NewDecl;
8999 Decl *Sema::ActOnConceptDefinition(Scope *S,
9000 MultiTemplateParamsArg TemplateParameterLists,
9001 IdentifierInfo *Name, SourceLocation NameLoc,
9002 Expr *ConstraintExpr) {
9003 DeclContext *DC = CurContext;
9005 if (!DC->getRedeclContext()->isFileContext()) {
9006 Diag(NameLoc,
9007 diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
9008 return nullptr;
9011 if (TemplateParameterLists.size() > 1) {
9012 Diag(NameLoc, diag::err_concept_extra_headers);
9013 return nullptr;
9016 TemplateParameterList *Params = TemplateParameterLists.front();
9018 if (Params->size() == 0) {
9019 Diag(NameLoc, diag::err_concept_no_parameters);
9020 return nullptr;
9023 // Ensure that the parameter pack, if present, is the last parameter in the
9024 // template.
9025 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
9026 ParamEnd = Params->end();
9027 ParamIt != ParamEnd; ++ParamIt) {
9028 Decl const *Param = *ParamIt;
9029 if (Param->isParameterPack()) {
9030 if (++ParamIt == ParamEnd)
9031 break;
9032 Diag(Param->getLocation(),
9033 diag::err_template_param_pack_must_be_last_template_parameter);
9034 return nullptr;
9038 if (DiagnoseUnexpandedParameterPack(ConstraintExpr))
9039 return nullptr;
9041 ConceptDecl *NewDecl =
9042 ConceptDecl::Create(Context, DC, NameLoc, Name, Params, ConstraintExpr);
9044 if (NewDecl->hasAssociatedConstraints()) {
9045 // C++2a [temp.concept]p4:
9046 // A concept shall not have associated constraints.
9047 Diag(NameLoc, diag::err_concept_no_associated_constraints);
9048 NewDecl->setInvalidDecl();
9051 // Check for conflicting previous declaration.
9052 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NameLoc);
9053 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9054 forRedeclarationInCurContext());
9055 LookupName(Previous, S);
9056 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage=*/false,
9057 /*AllowInlineNamespace*/false);
9058 bool AddToScope = true;
9059 CheckConceptRedefinition(NewDecl, Previous, AddToScope);
9061 ActOnDocumentableDecl(NewDecl);
9062 if (AddToScope)
9063 PushOnScopeChains(NewDecl, S);
9064 return NewDecl;
9067 void Sema::CheckConceptRedefinition(ConceptDecl *NewDecl,
9068 LookupResult &Previous, bool &AddToScope) {
9069 AddToScope = true;
9071 if (Previous.empty())
9072 return;
9074 auto *OldConcept = dyn_cast<ConceptDecl>(Previous.getRepresentativeDecl()->getUnderlyingDecl());
9075 if (!OldConcept) {
9076 auto *Old = Previous.getRepresentativeDecl();
9077 Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind)
9078 << NewDecl->getDeclName();
9079 notePreviousDefinition(Old, NewDecl->getLocation());
9080 AddToScope = false;
9081 return;
9083 // Check if we can merge with a concept declaration.
9084 bool IsSame = Context.isSameEntity(NewDecl, OldConcept);
9085 if (!IsSame) {
9086 Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept)
9087 << NewDecl->getDeclName();
9088 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9089 AddToScope = false;
9090 return;
9092 if (hasReachableDefinition(OldConcept) &&
9093 IsRedefinitionInModule(NewDecl, OldConcept)) {
9094 Diag(NewDecl->getLocation(), diag::err_redefinition)
9095 << NewDecl->getDeclName();
9096 notePreviousDefinition(OldConcept, NewDecl->getLocation());
9097 AddToScope = false;
9098 return;
9100 if (!Previous.isSingleResult()) {
9101 // FIXME: we should produce an error in case of ambig and failed lookups.
9102 // Other decls (e.g. namespaces) also have this shortcoming.
9103 return;
9105 // We unwrap canonical decl late to check for module visibility.
9106 Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl());
9109 /// \brief Strips various properties off an implicit instantiation
9110 /// that has just been explicitly specialized.
9111 static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
9112 if (MinGW || (isa<FunctionDecl>(D) &&
9113 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())) {
9114 D->dropAttr<DLLImportAttr>();
9115 D->dropAttr<DLLExportAttr>();
9118 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
9119 FD->setInlineSpecified(false);
9122 /// Compute the diagnostic location for an explicit instantiation
9123 // declaration or definition.
9124 static SourceLocation DiagLocForExplicitInstantiation(
9125 NamedDecl* D, SourceLocation PointOfInstantiation) {
9126 // Explicit instantiations following a specialization have no effect and
9127 // hence no PointOfInstantiation. In that case, walk decl backwards
9128 // until a valid name loc is found.
9129 SourceLocation PrevDiagLoc = PointOfInstantiation;
9130 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
9131 Prev = Prev->getPreviousDecl()) {
9132 PrevDiagLoc = Prev->getLocation();
9134 assert(PrevDiagLoc.isValid() &&
9135 "Explicit instantiation without point of instantiation?");
9136 return PrevDiagLoc;
9139 /// Diagnose cases where we have an explicit template specialization
9140 /// before/after an explicit template instantiation, producing diagnostics
9141 /// for those cases where they are required and determining whether the
9142 /// new specialization/instantiation will have any effect.
9144 /// \param NewLoc the location of the new explicit specialization or
9145 /// instantiation.
9147 /// \param NewTSK the kind of the new explicit specialization or instantiation.
9149 /// \param PrevDecl the previous declaration of the entity.
9151 /// \param PrevTSK the kind of the old explicit specialization or instantiatin.
9153 /// \param PrevPointOfInstantiation if valid, indicates where the previous
9154 /// declaration was instantiated (either implicitly or explicitly).
9156 /// \param HasNoEffect will be set to true to indicate that the new
9157 /// specialization or instantiation has no effect and should be ignored.
9159 /// \returns true if there was an error that should prevent the introduction of
9160 /// the new declaration into the AST, false otherwise.
9161 bool
9162 Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
9163 TemplateSpecializationKind NewTSK,
9164 NamedDecl *PrevDecl,
9165 TemplateSpecializationKind PrevTSK,
9166 SourceLocation PrevPointOfInstantiation,
9167 bool &HasNoEffect) {
9168 HasNoEffect = false;
9170 switch (NewTSK) {
9171 case TSK_Undeclared:
9172 case TSK_ImplicitInstantiation:
9173 assert(
9174 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
9175 "previous declaration must be implicit!");
9176 return false;
9178 case TSK_ExplicitSpecialization:
9179 switch (PrevTSK) {
9180 case TSK_Undeclared:
9181 case TSK_ExplicitSpecialization:
9182 // Okay, we're just specializing something that is either already
9183 // explicitly specialized or has merely been mentioned without any
9184 // instantiation.
9185 return false;
9187 case TSK_ImplicitInstantiation:
9188 if (PrevPointOfInstantiation.isInvalid()) {
9189 // The declaration itself has not actually been instantiated, so it is
9190 // still okay to specialize it.
9191 StripImplicitInstantiation(
9192 PrevDecl,
9193 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment());
9194 return false;
9196 // Fall through
9197 [[fallthrough]];
9199 case TSK_ExplicitInstantiationDeclaration:
9200 case TSK_ExplicitInstantiationDefinition:
9201 assert((PrevTSK == TSK_ImplicitInstantiation ||
9202 PrevPointOfInstantiation.isValid()) &&
9203 "Explicit instantiation without point of instantiation?");
9205 // C++ [temp.expl.spec]p6:
9206 // If a template, a member template or the member of a class template
9207 // is explicitly specialized then that specialization shall be declared
9208 // before the first use of that specialization that would cause an
9209 // implicit instantiation to take place, in every translation unit in
9210 // which such a use occurs; no diagnostic is required.
9211 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9212 // Is there any previous explicit specialization declaration?
9213 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
9214 return false;
9217 Diag(NewLoc, diag::err_specialization_after_instantiation)
9218 << PrevDecl;
9219 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
9220 << (PrevTSK != TSK_ImplicitInstantiation);
9222 return true;
9224 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
9226 case TSK_ExplicitInstantiationDeclaration:
9227 switch (PrevTSK) {
9228 case TSK_ExplicitInstantiationDeclaration:
9229 // This explicit instantiation declaration is redundant (that's okay).
9230 HasNoEffect = true;
9231 return false;
9233 case TSK_Undeclared:
9234 case TSK_ImplicitInstantiation:
9235 // We're explicitly instantiating something that may have already been
9236 // implicitly instantiated; that's fine.
9237 return false;
9239 case TSK_ExplicitSpecialization:
9240 // C++0x [temp.explicit]p4:
9241 // For a given set of template parameters, if an explicit instantiation
9242 // of a template appears after a declaration of an explicit
9243 // specialization for that template, the explicit instantiation has no
9244 // effect.
9245 HasNoEffect = true;
9246 return false;
9248 case TSK_ExplicitInstantiationDefinition:
9249 // C++0x [temp.explicit]p10:
9250 // If an entity is the subject of both an explicit instantiation
9251 // declaration and an explicit instantiation definition in the same
9252 // translation unit, the definition shall follow the declaration.
9253 Diag(NewLoc,
9254 diag::err_explicit_instantiation_declaration_after_definition);
9256 // Explicit instantiations following a specialization have no effect and
9257 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
9258 // until a valid name loc is found.
9259 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9260 diag::note_explicit_instantiation_definition_here);
9261 HasNoEffect = true;
9262 return false;
9264 llvm_unreachable("Unexpected TemplateSpecializationKind!");
9266 case TSK_ExplicitInstantiationDefinition:
9267 switch (PrevTSK) {
9268 case TSK_Undeclared:
9269 case TSK_ImplicitInstantiation:
9270 // We're explicitly instantiating something that may have already been
9271 // implicitly instantiated; that's fine.
9272 return false;
9274 case TSK_ExplicitSpecialization:
9275 // C++ DR 259, C++0x [temp.explicit]p4:
9276 // For a given set of template parameters, if an explicit
9277 // instantiation of a template appears after a declaration of
9278 // an explicit specialization for that template, the explicit
9279 // instantiation has no effect.
9280 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
9281 << PrevDecl;
9282 Diag(PrevDecl->getLocation(),
9283 diag::note_previous_template_specialization);
9284 HasNoEffect = true;
9285 return false;
9287 case TSK_ExplicitInstantiationDeclaration:
9288 // We're explicitly instantiating a definition for something for which we
9289 // were previously asked to suppress instantiations. That's fine.
9291 // C++0x [temp.explicit]p4:
9292 // For a given set of template parameters, if an explicit instantiation
9293 // of a template appears after a declaration of an explicit
9294 // specialization for that template, the explicit instantiation has no
9295 // effect.
9296 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9297 // Is there any previous explicit specialization declaration?
9298 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
9299 HasNoEffect = true;
9300 break;
9304 return false;
9306 case TSK_ExplicitInstantiationDefinition:
9307 // C++0x [temp.spec]p5:
9308 // For a given template and a given set of template-arguments,
9309 // - an explicit instantiation definition shall appear at most once
9310 // in a program,
9312 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
9313 Diag(NewLoc, (getLangOpts().MSVCCompat)
9314 ? diag::ext_explicit_instantiation_duplicate
9315 : diag::err_explicit_instantiation_duplicate)
9316 << PrevDecl;
9317 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9318 diag::note_previous_explicit_instantiation);
9319 HasNoEffect = true;
9320 return false;
9324 llvm_unreachable("Missing specialization/instantiation case?");
9327 /// Perform semantic analysis for the given dependent function
9328 /// template specialization.
9330 /// The only possible way to get a dependent function template specialization
9331 /// is with a friend declaration, like so:
9333 /// \code
9334 /// template \<class T> void foo(T);
9335 /// template \<class T> class A {
9336 /// friend void foo<>(T);
9337 /// };
9338 /// \endcode
9340 /// There really isn't any useful analysis we can do here, so we
9341 /// just store the information.
9342 bool Sema::CheckDependentFunctionTemplateSpecialization(
9343 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
9344 LookupResult &Previous) {
9345 // Remove anything from Previous that isn't a function template in
9346 // the correct context.
9347 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9348 LookupResult::Filter F = Previous.makeFilter();
9349 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
9350 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
9351 while (F.hasNext()) {
9352 NamedDecl *D = F.next()->getUnderlyingDecl();
9353 if (!isa<FunctionTemplateDecl>(D)) {
9354 F.erase();
9355 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
9356 continue;
9359 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9360 D->getDeclContext()->getRedeclContext())) {
9361 F.erase();
9362 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
9363 continue;
9366 F.done();
9368 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
9369 if (Previous.empty()) {
9370 Diag(FD->getLocation(), diag::err_dependent_function_template_spec_no_match)
9371 << IsFriend;
9372 for (auto &P : DiscardedCandidates)
9373 Diag(P.second->getLocation(),
9374 diag::note_dependent_function_template_spec_discard_reason)
9375 << P.first << IsFriend;
9376 return true;
9379 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
9380 ExplicitTemplateArgs);
9381 return false;
9384 /// Perform semantic analysis for the given function template
9385 /// specialization.
9387 /// This routine performs all of the semantic analysis required for an
9388 /// explicit function template specialization. On successful completion,
9389 /// the function declaration \p FD will become a function template
9390 /// specialization.
9392 /// \param FD the function declaration, which will be updated to become a
9393 /// function template specialization.
9395 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
9396 /// if any. Note that this may be valid info even when 0 arguments are
9397 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
9398 /// as it anyway contains info on the angle brackets locations.
9400 /// \param Previous the set of declarations that may be specialized by
9401 /// this function specialization.
9403 /// \param QualifiedFriend whether this is a lookup for a qualified friend
9404 /// declaration with no explicit template argument list that might be
9405 /// befriending a function template specialization.
9406 bool Sema::CheckFunctionTemplateSpecialization(
9407 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
9408 LookupResult &Previous, bool QualifiedFriend) {
9409 // The set of function template specializations that could match this
9410 // explicit function template specialization.
9411 UnresolvedSet<8> Candidates;
9412 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
9413 /*ForTakingAddress=*/false);
9415 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
9416 ConvertedTemplateArgs;
9418 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9419 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9420 I != E; ++I) {
9421 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
9422 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
9423 // Only consider templates found within the same semantic lookup scope as
9424 // FD.
9425 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9426 Ovl->getDeclContext()->getRedeclContext()))
9427 continue;
9429 // When matching a constexpr member function template specialization
9430 // against the primary template, we don't yet know whether the
9431 // specialization has an implicit 'const' (because we don't know whether
9432 // it will be a static member function until we know which template it
9433 // specializes), so adjust it now assuming it specializes this template.
9434 QualType FT = FD->getType();
9435 if (FD->isConstexpr()) {
9436 CXXMethodDecl *OldMD =
9437 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
9438 if (OldMD && OldMD->isConst()) {
9439 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
9440 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9441 EPI.TypeQuals.addConst();
9442 FT = Context.getFunctionType(FPT->getReturnType(),
9443 FPT->getParamTypes(), EPI);
9447 TemplateArgumentListInfo Args;
9448 if (ExplicitTemplateArgs)
9449 Args = *ExplicitTemplateArgs;
9451 // C++ [temp.expl.spec]p11:
9452 // A trailing template-argument can be left unspecified in the
9453 // template-id naming an explicit function template specialization
9454 // provided it can be deduced from the function argument type.
9455 // Perform template argument deduction to determine whether we may be
9456 // specializing this template.
9457 // FIXME: It is somewhat wasteful to build
9458 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9459 FunctionDecl *Specialization = nullptr;
9460 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
9461 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
9462 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
9463 Info)) {
9464 // Template argument deduction failed; record why it failed, so
9465 // that we can provide nifty diagnostics.
9466 FailedCandidates.addCandidate().set(
9467 I.getPair(), FunTmpl->getTemplatedDecl(),
9468 MakeDeductionFailureInfo(Context, TDK, Info));
9469 (void)TDK;
9470 continue;
9473 // Target attributes are part of the cuda function signature, so
9474 // the deduced template's cuda target must match that of the
9475 // specialization. Given that C++ template deduction does not
9476 // take target attributes into account, we reject candidates
9477 // here that have a different target.
9478 if (LangOpts.CUDA &&
9479 IdentifyCUDATarget(Specialization,
9480 /* IgnoreImplicitHDAttr = */ true) !=
9481 IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
9482 FailedCandidates.addCandidate().set(
9483 I.getPair(), FunTmpl->getTemplatedDecl(),
9484 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
9485 continue;
9488 // Record this candidate.
9489 if (ExplicitTemplateArgs)
9490 ConvertedTemplateArgs[Specialization] = std::move(Args);
9491 Candidates.addDecl(Specialization, I.getAccess());
9495 // For a qualified friend declaration (with no explicit marker to indicate
9496 // that a template specialization was intended), note all (template and
9497 // non-template) candidates.
9498 if (QualifiedFriend && Candidates.empty()) {
9499 Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
9500 << FD->getDeclName() << FDLookupContext;
9501 // FIXME: We should form a single candidate list and diagnose all
9502 // candidates at once, to get proper sorting and limiting.
9503 for (auto *OldND : Previous) {
9504 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
9505 NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false);
9507 FailedCandidates.NoteCandidates(*this, FD->getLocation());
9508 return true;
9511 // Find the most specialized function template.
9512 UnresolvedSetIterator Result = getMostSpecialized(
9513 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
9514 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
9515 PDiag(diag::err_function_template_spec_ambiguous)
9516 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
9517 PDiag(diag::note_function_template_spec_matched));
9519 if (Result == Candidates.end())
9520 return true;
9522 // Ignore access information; it doesn't figure into redeclaration checking.
9523 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
9525 FunctionTemplateSpecializationInfo *SpecInfo
9526 = Specialization->getTemplateSpecializationInfo();
9527 assert(SpecInfo && "Function template specialization info missing?");
9529 // Note: do not overwrite location info if previous template
9530 // specialization kind was explicit.
9531 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
9532 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
9533 Specialization->setLocation(FD->getLocation());
9534 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
9535 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9536 // function can differ from the template declaration with respect to
9537 // the constexpr specifier.
9538 // FIXME: We need an update record for this AST mutation.
9539 // FIXME: What if there are multiple such prior declarations (for instance,
9540 // from different modules)?
9541 Specialization->setConstexprKind(FD->getConstexprKind());
9544 // FIXME: Check if the prior specialization has a point of instantiation.
9545 // If so, we have run afoul of .
9547 // If this is a friend declaration, then we're not really declaring
9548 // an explicit specialization.
9549 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
9551 // Check the scope of this explicit specialization.
9552 if (!isFriend &&
9553 CheckTemplateSpecializationScope(*this,
9554 Specialization->getPrimaryTemplate(),
9555 Specialization, FD->getLocation(),
9556 false))
9557 return true;
9559 // C++ [temp.expl.spec]p6:
9560 // If a template, a member template or the member of a class template is
9561 // explicitly specialized then that specialization shall be declared
9562 // before the first use of that specialization that would cause an implicit
9563 // instantiation to take place, in every translation unit in which such a
9564 // use occurs; no diagnostic is required.
9565 bool HasNoEffect = false;
9566 if (!isFriend &&
9567 CheckSpecializationInstantiationRedecl(FD->getLocation(),
9568 TSK_ExplicitSpecialization,
9569 Specialization,
9570 SpecInfo->getTemplateSpecializationKind(),
9571 SpecInfo->getPointOfInstantiation(),
9572 HasNoEffect))
9573 return true;
9575 // Mark the prior declaration as an explicit specialization, so that later
9576 // clients know that this is an explicit specialization.
9577 if (!isFriend) {
9578 // Since explicit specializations do not inherit '=delete' from their
9579 // primary function template - check if the 'specialization' that was
9580 // implicitly generated (during template argument deduction for partial
9581 // ordering) from the most specialized of all the function templates that
9582 // 'FD' could have been specializing, has a 'deleted' definition. If so,
9583 // first check that it was implicitly generated during template argument
9584 // deduction by making sure it wasn't referenced, and then reset the deleted
9585 // flag to not-deleted, so that we can inherit that information from 'FD'.
9586 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9587 !Specialization->getCanonicalDecl()->isReferenced()) {
9588 // FIXME: This assert will not hold in the presence of modules.
9589 assert(
9590 Specialization->getCanonicalDecl() == Specialization &&
9591 "This must be the only existing declaration of this specialization");
9592 // FIXME: We need an update record for this AST mutation.
9593 Specialization->setDeletedAsWritten(false);
9595 // FIXME: We need an update record for this AST mutation.
9596 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
9597 MarkUnusedFileScopedDecl(Specialization);
9600 // Turn the given function declaration into a function template
9601 // specialization, with the template arguments from the previous
9602 // specialization.
9603 // Take copies of (semantic and syntactic) template argument lists.
9604 const TemplateArgumentList* TemplArgs = new (Context)
9605 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
9606 FD->setFunctionTemplateSpecialization(
9607 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
9608 SpecInfo->getTemplateSpecializationKind(),
9609 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9611 // A function template specialization inherits the target attributes
9612 // of its template. (We require the attributes explicitly in the
9613 // code to match, but a template may have implicit attributes by
9614 // virtue e.g. of being constexpr, and it passes these implicit
9615 // attributes on to its specializations.)
9616 if (LangOpts.CUDA)
9617 inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
9619 // The "previous declaration" for this function template specialization is
9620 // the prior function template specialization.
9621 Previous.clear();
9622 Previous.addDecl(Specialization);
9623 return false;
9626 /// Perform semantic analysis for the given non-template member
9627 /// specialization.
9629 /// This routine performs all of the semantic analysis required for an
9630 /// explicit member function specialization. On successful completion,
9631 /// the function declaration \p FD will become a member function
9632 /// specialization.
9634 /// \param Member the member declaration, which will be updated to become a
9635 /// specialization.
9637 /// \param Previous the set of declarations, one of which may be specialized
9638 /// by this function specialization; the set will be modified to contain the
9639 /// redeclared member.
9640 bool
9641 Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
9642 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
9644 // Try to find the member we are instantiating.
9645 NamedDecl *FoundInstantiation = nullptr;
9646 NamedDecl *Instantiation = nullptr;
9647 NamedDecl *InstantiatedFrom = nullptr;
9648 MemberSpecializationInfo *MSInfo = nullptr;
9650 if (Previous.empty()) {
9651 // Nowhere to look anyway.
9652 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
9653 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9654 I != E; ++I) {
9655 NamedDecl *D = (*I)->getUnderlyingDecl();
9656 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
9657 QualType Adjusted = Function->getType();
9658 if (!hasExplicitCallingConv(Adjusted))
9659 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
9660 // This doesn't handle deduced return types, but both function
9661 // declarations should be undeduced at this point.
9662 if (Context.hasSameType(Adjusted, Method->getType())) {
9663 FoundInstantiation = *I;
9664 Instantiation = Method;
9665 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
9666 MSInfo = Method->getMemberSpecializationInfo();
9667 break;
9671 } else if (isa<VarDecl>(Member)) {
9672 VarDecl *PrevVar;
9673 if (Previous.isSingleResult() &&
9674 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
9675 if (PrevVar->isStaticDataMember()) {
9676 FoundInstantiation = Previous.getRepresentativeDecl();
9677 Instantiation = PrevVar;
9678 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
9679 MSInfo = PrevVar->getMemberSpecializationInfo();
9681 } else if (isa<RecordDecl>(Member)) {
9682 CXXRecordDecl *PrevRecord;
9683 if (Previous.isSingleResult() &&
9684 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
9685 FoundInstantiation = Previous.getRepresentativeDecl();
9686 Instantiation = PrevRecord;
9687 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
9688 MSInfo = PrevRecord->getMemberSpecializationInfo();
9690 } else if (isa<EnumDecl>(Member)) {
9691 EnumDecl *PrevEnum;
9692 if (Previous.isSingleResult() &&
9693 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
9694 FoundInstantiation = Previous.getRepresentativeDecl();
9695 Instantiation = PrevEnum;
9696 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
9697 MSInfo = PrevEnum->getMemberSpecializationInfo();
9701 if (!Instantiation) {
9702 // There is no previous declaration that matches. Since member
9703 // specializations are always out-of-line, the caller will complain about
9704 // this mismatch later.
9705 return false;
9708 // A member specialization in a friend declaration isn't really declaring
9709 // an explicit specialization, just identifying a specific (possibly implicit)
9710 // specialization. Don't change the template specialization kind.
9712 // FIXME: Is this really valid? Other compilers reject.
9713 if (Member->getFriendObjectKind() != Decl::FOK_None) {
9714 // Preserve instantiation information.
9715 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
9716 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
9717 cast<CXXMethodDecl>(InstantiatedFrom),
9718 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
9719 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
9720 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
9721 cast<CXXRecordDecl>(InstantiatedFrom),
9722 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
9725 Previous.clear();
9726 Previous.addDecl(FoundInstantiation);
9727 return false;
9730 // Make sure that this is a specialization of a member.
9731 if (!InstantiatedFrom) {
9732 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
9733 << Member;
9734 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
9735 return true;
9738 // C++ [temp.expl.spec]p6:
9739 // If a template, a member template or the member of a class template is
9740 // explicitly specialized then that specialization shall be declared
9741 // before the first use of that specialization that would cause an implicit
9742 // instantiation to take place, in every translation unit in which such a
9743 // use occurs; no diagnostic is required.
9744 assert(MSInfo && "Member specialization info missing?");
9746 bool HasNoEffect = false;
9747 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
9748 TSK_ExplicitSpecialization,
9749 Instantiation,
9750 MSInfo->getTemplateSpecializationKind(),
9751 MSInfo->getPointOfInstantiation(),
9752 HasNoEffect))
9753 return true;
9755 // Check the scope of this explicit specialization.
9756 if (CheckTemplateSpecializationScope(*this,
9757 InstantiatedFrom,
9758 Instantiation, Member->getLocation(),
9759 false))
9760 return true;
9762 // Note that this member specialization is an "instantiation of" the
9763 // corresponding member of the original template.
9764 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
9765 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
9766 if (InstantiationFunction->getTemplateSpecializationKind() ==
9767 TSK_ImplicitInstantiation) {
9768 // Explicit specializations of member functions of class templates do not
9769 // inherit '=delete' from the member function they are specializing.
9770 if (InstantiationFunction->isDeleted()) {
9771 // FIXME: This assert will not hold in the presence of modules.
9772 assert(InstantiationFunction->getCanonicalDecl() ==
9773 InstantiationFunction);
9774 // FIXME: We need an update record for this AST mutation.
9775 InstantiationFunction->setDeletedAsWritten(false);
9779 MemberFunction->setInstantiationOfMemberFunction(
9780 cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9781 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
9782 MemberVar->setInstantiationOfStaticDataMember(
9783 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9784 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
9785 MemberClass->setInstantiationOfMemberClass(
9786 cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9787 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
9788 MemberEnum->setInstantiationOfMemberEnum(
9789 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9790 } else {
9791 llvm_unreachable("unknown member specialization kind");
9794 // Save the caller the trouble of having to figure out which declaration
9795 // this specialization matches.
9796 Previous.clear();
9797 Previous.addDecl(FoundInstantiation);
9798 return false;
9801 /// Complete the explicit specialization of a member of a class template by
9802 /// updating the instantiated member to be marked as an explicit specialization.
9804 /// \param OrigD The member declaration instantiated from the template.
9805 /// \param Loc The location of the explicit specialization of the member.
9806 template<typename DeclT>
9807 static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
9808 SourceLocation Loc) {
9809 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
9810 return;
9812 // FIXME: Inform AST mutation listeners of this AST mutation.
9813 // FIXME: If there are multiple in-class declarations of the member (from
9814 // multiple modules, or a declaration and later definition of a member type),
9815 // should we update all of them?
9816 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
9817 OrigD->setLocation(Loc);
9820 void Sema::CompleteMemberSpecialization(NamedDecl *Member,
9821 LookupResult &Previous) {
9822 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
9823 if (Instantiation == Member)
9824 return;
9826 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
9827 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
9828 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
9829 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
9830 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
9831 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
9832 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
9833 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
9834 else
9835 llvm_unreachable("unknown member specialization kind");
9838 /// Check the scope of an explicit instantiation.
9840 /// \returns true if a serious error occurs, false otherwise.
9841 static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
9842 SourceLocation InstLoc,
9843 bool WasQualifiedName) {
9844 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
9845 DeclContext *CurContext = S.CurContext->getRedeclContext();
9847 if (CurContext->isRecord()) {
9848 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
9849 << D;
9850 return true;
9853 // C++11 [temp.explicit]p3:
9854 // An explicit instantiation shall appear in an enclosing namespace of its
9855 // template. If the name declared in the explicit instantiation is an
9856 // unqualified name, the explicit instantiation shall appear in the
9857 // namespace where its template is declared or, if that namespace is inline
9858 // (7.3.1), any namespace from its enclosing namespace set.
9860 // This is DR275, which we do not retroactively apply to C++98/03.
9861 if (WasQualifiedName) {
9862 if (CurContext->Encloses(OrigContext))
9863 return false;
9864 } else {
9865 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
9866 return false;
9869 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
9870 if (WasQualifiedName)
9871 S.Diag(InstLoc,
9872 S.getLangOpts().CPlusPlus11?
9873 diag::err_explicit_instantiation_out_of_scope :
9874 diag::warn_explicit_instantiation_out_of_scope_0x)
9875 << D << NS;
9876 else
9877 S.Diag(InstLoc,
9878 S.getLangOpts().CPlusPlus11?
9879 diag::err_explicit_instantiation_unqualified_wrong_namespace :
9880 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
9881 << D << NS;
9882 } else
9883 S.Diag(InstLoc,
9884 S.getLangOpts().CPlusPlus11?
9885 diag::err_explicit_instantiation_must_be_global :
9886 diag::warn_explicit_instantiation_must_be_global_0x)
9887 << D;
9888 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
9889 return false;
9892 /// Common checks for whether an explicit instantiation of \p D is valid.
9893 static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D,
9894 SourceLocation InstLoc,
9895 bool WasQualifiedName,
9896 TemplateSpecializationKind TSK) {
9897 // C++ [temp.explicit]p13:
9898 // An explicit instantiation declaration shall not name a specialization of
9899 // a template with internal linkage.
9900 if (TSK == TSK_ExplicitInstantiationDeclaration &&
9901 D->getFormalLinkage() == Linkage::Internal) {
9902 S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
9903 return true;
9906 // C++11 [temp.explicit]p3: [DR 275]
9907 // An explicit instantiation shall appear in an enclosing namespace of its
9908 // template.
9909 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
9910 return true;
9912 return false;
9915 /// Determine whether the given scope specifier has a template-id in it.
9916 static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
9917 if (!SS.isSet())
9918 return false;
9920 // C++11 [temp.explicit]p3:
9921 // If the explicit instantiation is for a member function, a member class
9922 // or a static data member of a class template specialization, the name of
9923 // the class template specialization in the qualified-id for the member
9924 // name shall be a simple-template-id.
9926 // C++98 has the same restriction, just worded differently.
9927 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
9928 NNS = NNS->getPrefix())
9929 if (const Type *T = NNS->getAsType())
9930 if (isa<TemplateSpecializationType>(T))
9931 return true;
9933 return false;
9936 /// Make a dllexport or dllimport attr on a class template specialization take
9937 /// effect.
9938 static void dllExportImportClassTemplateSpecialization(
9939 Sema &S, ClassTemplateSpecializationDecl *Def) {
9940 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
9941 assert(A && "dllExportImportClassTemplateSpecialization called "
9942 "on Def without dllexport or dllimport");
9944 // We reject explicit instantiations in class scope, so there should
9945 // never be any delayed exported classes to worry about.
9946 assert(S.DelayedDllExportClasses.empty() &&
9947 "delayed exports present at explicit instantiation");
9948 S.checkClassLevelDLLAttribute(Def);
9950 // Propagate attribute to base class templates.
9951 for (auto &B : Def->bases()) {
9952 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
9953 B.getType()->getAsCXXRecordDecl()))
9954 S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getBeginLoc());
9957 S.referenceDLLExportedClassMethods();
9960 // Explicit instantiation of a class template specialization
9961 DeclResult Sema::ActOnExplicitInstantiation(
9962 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
9963 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
9964 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
9965 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
9966 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
9967 // Find the class template we're specializing
9968 TemplateName Name = TemplateD.get();
9969 TemplateDecl *TD = Name.getAsTemplateDecl();
9970 // Check that the specialization uses the same tag kind as the
9971 // original template.
9972 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9973 assert(Kind != TagTypeKind::Enum &&
9974 "Invalid enum tag in class template explicit instantiation!");
9976 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
9978 if (!ClassTemplate) {
9979 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
9980 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag)
9981 << TD << NTK << llvm::to_underlying(Kind);
9982 Diag(TD->getLocation(), diag::note_previous_use);
9983 return true;
9986 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
9987 Kind, /*isDefinition*/false, KWLoc,
9988 ClassTemplate->getIdentifier())) {
9989 Diag(KWLoc, diag::err_use_with_wrong_tag)
9990 << ClassTemplate
9991 << FixItHint::CreateReplacement(KWLoc,
9992 ClassTemplate->getTemplatedDecl()->getKindName());
9993 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
9994 diag::note_previous_use);
9995 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
9998 // C++0x [temp.explicit]p2:
9999 // There are two forms of explicit instantiation: an explicit instantiation
10000 // definition and an explicit instantiation declaration. An explicit
10001 // instantiation declaration begins with the extern keyword. [...]
10002 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
10003 ? TSK_ExplicitInstantiationDefinition
10004 : TSK_ExplicitInstantiationDeclaration;
10006 if (TSK == TSK_ExplicitInstantiationDeclaration &&
10007 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
10008 // Check for dllexport class template instantiation declarations,
10009 // except for MinGW mode.
10010 for (const ParsedAttr &AL : Attr) {
10011 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10012 Diag(ExternLoc,
10013 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10014 Diag(AL.getLoc(), diag::note_attribute);
10015 break;
10019 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
10020 Diag(ExternLoc,
10021 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10022 Diag(A->getLocation(), diag::note_attribute);
10026 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10027 // instantiation declarations for most purposes.
10028 bool DLLImportExplicitInstantiationDef = false;
10029 if (TSK == TSK_ExplicitInstantiationDefinition &&
10030 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
10031 // Check for dllimport class template instantiation definitions.
10032 bool DLLImport =
10033 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
10034 for (const ParsedAttr &AL : Attr) {
10035 if (AL.getKind() == ParsedAttr::AT_DLLImport)
10036 DLLImport = true;
10037 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10038 // dllexport trumps dllimport here.
10039 DLLImport = false;
10040 break;
10043 if (DLLImport) {
10044 TSK = TSK_ExplicitInstantiationDeclaration;
10045 DLLImportExplicitInstantiationDef = true;
10049 // Translate the parser's template argument list in our AST format.
10050 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10051 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10053 // Check that the template argument list is well-formed for this
10054 // template.
10055 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
10056 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
10057 false, SugaredConverted, CanonicalConverted,
10058 /*UpdateArgsWithConversions=*/true))
10059 return true;
10061 // Find the class template specialization declaration that
10062 // corresponds to these arguments.
10063 void *InsertPos = nullptr;
10064 ClassTemplateSpecializationDecl *PrevDecl =
10065 ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
10067 TemplateSpecializationKind PrevDecl_TSK
10068 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
10070 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
10071 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
10072 // Check for dllexport class template instantiation definitions in MinGW
10073 // mode, if a previous declaration of the instantiation was seen.
10074 for (const ParsedAttr &AL : Attr) {
10075 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10076 Diag(AL.getLoc(),
10077 diag::warn_attribute_dllexport_explicit_instantiation_def);
10078 break;
10083 if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
10084 SS.isSet(), TSK))
10085 return true;
10087 ClassTemplateSpecializationDecl *Specialization = nullptr;
10089 bool HasNoEffect = false;
10090 if (PrevDecl) {
10091 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
10092 PrevDecl, PrevDecl_TSK,
10093 PrevDecl->getPointOfInstantiation(),
10094 HasNoEffect))
10095 return PrevDecl;
10097 // Even though HasNoEffect == true means that this explicit instantiation
10098 // has no effect on semantics, we go on to put its syntax in the AST.
10100 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
10101 PrevDecl_TSK == TSK_Undeclared) {
10102 // Since the only prior class template specialization with these
10103 // arguments was referenced but not declared, reuse that
10104 // declaration node as our own, updating the source location
10105 // for the template name to reflect our new declaration.
10106 // (Other source locations will be updated later.)
10107 Specialization = PrevDecl;
10108 Specialization->setLocation(TemplateNameLoc);
10109 PrevDecl = nullptr;
10112 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10113 DLLImportExplicitInstantiationDef) {
10114 // The new specialization might add a dllimport attribute.
10115 HasNoEffect = false;
10119 if (!Specialization) {
10120 // Create a new class template specialization declaration node for
10121 // this explicit specialization.
10122 Specialization = ClassTemplateSpecializationDecl::Create(
10123 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
10124 ClassTemplate, CanonicalConverted, PrevDecl);
10125 SetNestedNameSpecifier(*this, Specialization, SS);
10127 // A MSInheritanceAttr attached to the previous declaration must be
10128 // propagated to the new node prior to instantiation.
10129 if (PrevDecl) {
10130 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
10131 auto *Clone = A->clone(getASTContext());
10132 Clone->setInherited(true);
10133 Specialization->addAttr(Clone);
10134 Consumer.AssignInheritanceModel(Specialization);
10138 if (!HasNoEffect && !PrevDecl) {
10139 // Insert the new specialization.
10140 ClassTemplate->AddSpecialization(Specialization, InsertPos);
10144 // Build the fully-sugared type for this explicit instantiation as
10145 // the user wrote in the explicit instantiation itself. This means
10146 // that we'll pretty-print the type retrieved from the
10147 // specialization's declaration the way that the user actually wrote
10148 // the explicit instantiation, rather than formatting the name based
10149 // on the "canonical" representation used to store the template
10150 // arguments in the specialization.
10151 TypeSourceInfo *WrittenTy
10152 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
10153 TemplateArgs,
10154 Context.getTypeDeclType(Specialization));
10155 Specialization->setTypeAsWritten(WrittenTy);
10157 // Set source locations for keywords.
10158 Specialization->setExternLoc(ExternLoc);
10159 Specialization->setTemplateKeywordLoc(TemplateLoc);
10160 Specialization->setBraceRange(SourceRange());
10162 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
10163 ProcessDeclAttributeList(S, Specialization, Attr);
10165 // Add the explicit instantiation into its lexical context. However,
10166 // since explicit instantiations are never found by name lookup, we
10167 // just put it into the declaration context directly.
10168 Specialization->setLexicalDeclContext(CurContext);
10169 CurContext->addDecl(Specialization);
10171 // Syntax is now OK, so return if it has no other effect on semantics.
10172 if (HasNoEffect) {
10173 // Set the template specialization kind.
10174 Specialization->setTemplateSpecializationKind(TSK);
10175 return Specialization;
10178 // C++ [temp.explicit]p3:
10179 // A definition of a class template or class member template
10180 // shall be in scope at the point of the explicit instantiation of
10181 // the class template or class member template.
10183 // This check comes when we actually try to perform the
10184 // instantiation.
10185 ClassTemplateSpecializationDecl *Def
10186 = cast_or_null<ClassTemplateSpecializationDecl>(
10187 Specialization->getDefinition());
10188 if (!Def)
10189 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
10190 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10191 MarkVTableUsed(TemplateNameLoc, Specialization, true);
10192 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
10195 // Instantiate the members of this class template specialization.
10196 Def = cast_or_null<ClassTemplateSpecializationDecl>(
10197 Specialization->getDefinition());
10198 if (Def) {
10199 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
10200 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
10201 // TSK_ExplicitInstantiationDefinition
10202 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
10203 (TSK == TSK_ExplicitInstantiationDefinition ||
10204 DLLImportExplicitInstantiationDef)) {
10205 // FIXME: Need to notify the ASTMutationListener that we did this.
10206 Def->setTemplateSpecializationKind(TSK);
10208 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
10209 (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
10210 !Context.getTargetInfo().getTriple().isPS())) {
10211 // An explicit instantiation definition can add a dll attribute to a
10212 // template with a previous instantiation declaration. MinGW doesn't
10213 // allow this.
10214 auto *A = cast<InheritableAttr>(
10215 getDLLAttr(Specialization)->clone(getASTContext()));
10216 A->setInherited(true);
10217 Def->addAttr(A);
10218 dllExportImportClassTemplateSpecialization(*this, Def);
10222 // Fix a TSK_ImplicitInstantiation followed by a
10223 // TSK_ExplicitInstantiationDefinition
10224 bool NewlyDLLExported =
10225 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
10226 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
10227 (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
10228 !Context.getTargetInfo().getTriple().isPS())) {
10229 // An explicit instantiation definition can add a dll attribute to a
10230 // template with a previous implicit instantiation. MinGW doesn't allow
10231 // this. We limit clang to only adding dllexport, to avoid potentially
10232 // strange codegen behavior. For example, if we extend this conditional
10233 // to dllimport, and we have a source file calling a method on an
10234 // implicitly instantiated template class instance and then declaring a
10235 // dllimport explicit instantiation definition for the same template
10236 // class, the codegen for the method call will not respect the dllimport,
10237 // while it will with cl. The Def will already have the DLL attribute,
10238 // since the Def and Specialization will be the same in the case of
10239 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
10240 // attribute to the Specialization; we just need to make it take effect.
10241 assert(Def == Specialization &&
10242 "Def and Specialization should match for implicit instantiation");
10243 dllExportImportClassTemplateSpecialization(*this, Def);
10246 // In MinGW mode, export the template instantiation if the declaration
10247 // was marked dllexport.
10248 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10249 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
10250 PrevDecl->hasAttr<DLLExportAttr>()) {
10251 dllExportImportClassTemplateSpecialization(*this, Def);
10254 // Set the template specialization kind. Make sure it is set before
10255 // instantiating the members which will trigger ASTConsumer callbacks.
10256 Specialization->setTemplateSpecializationKind(TSK);
10257 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
10258 } else {
10260 // Set the template specialization kind.
10261 Specialization->setTemplateSpecializationKind(TSK);
10264 return Specialization;
10267 // Explicit instantiation of a member class of a class template.
10268 DeclResult
10269 Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
10270 SourceLocation TemplateLoc, unsigned TagSpec,
10271 SourceLocation KWLoc, CXXScopeSpec &SS,
10272 IdentifierInfo *Name, SourceLocation NameLoc,
10273 const ParsedAttributesView &Attr) {
10275 bool Owned = false;
10276 bool IsDependent = false;
10277 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference, KWLoc, SS, Name,
10278 NameLoc, Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(),
10279 MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(),
10280 false, TypeResult(), /*IsTypeSpecifier*/ false,
10281 /*IsTemplateParamOrArg*/ false, /*OOK=*/OOK_Outside).get();
10282 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
10284 if (!TagD)
10285 return true;
10287 TagDecl *Tag = cast<TagDecl>(TagD);
10288 assert(!Tag->isEnum() && "shouldn't see enumerations here");
10290 if (Tag->isInvalidDecl())
10291 return true;
10293 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
10294 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
10295 if (!Pattern) {
10296 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
10297 << Context.getTypeDeclType(Record);
10298 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
10299 return true;
10302 // C++0x [temp.explicit]p2:
10303 // If the explicit instantiation is for a class or member class, the
10304 // elaborated-type-specifier in the declaration shall include a
10305 // simple-template-id.
10307 // C++98 has the same restriction, just worded differently.
10308 if (!ScopeSpecifierHasTemplateId(SS))
10309 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
10310 << Record << SS.getRange();
10312 // C++0x [temp.explicit]p2:
10313 // There are two forms of explicit instantiation: an explicit instantiation
10314 // definition and an explicit instantiation declaration. An explicit
10315 // instantiation declaration begins with the extern keyword. [...]
10316 TemplateSpecializationKind TSK
10317 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
10318 : TSK_ExplicitInstantiationDeclaration;
10320 CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
10322 // Verify that it is okay to explicitly instantiate here.
10323 CXXRecordDecl *PrevDecl
10324 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
10325 if (!PrevDecl && Record->getDefinition())
10326 PrevDecl = Record;
10327 if (PrevDecl) {
10328 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
10329 bool HasNoEffect = false;
10330 assert(MSInfo && "No member specialization information?");
10331 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
10332 PrevDecl,
10333 MSInfo->getTemplateSpecializationKind(),
10334 MSInfo->getPointOfInstantiation(),
10335 HasNoEffect))
10336 return true;
10337 if (HasNoEffect)
10338 return TagD;
10341 CXXRecordDecl *RecordDef
10342 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10343 if (!RecordDef) {
10344 // C++ [temp.explicit]p3:
10345 // A definition of a member class of a class template shall be in scope
10346 // at the point of an explicit instantiation of the member class.
10347 CXXRecordDecl *Def
10348 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
10349 if (!Def) {
10350 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
10351 << 0 << Record->getDeclName() << Record->getDeclContext();
10352 Diag(Pattern->getLocation(), diag::note_forward_declaration)
10353 << Pattern;
10354 return true;
10355 } else {
10356 if (InstantiateClass(NameLoc, Record, Def,
10357 getTemplateInstantiationArgs(Record),
10358 TSK))
10359 return true;
10361 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10362 if (!RecordDef)
10363 return true;
10367 // Instantiate all of the members of the class.
10368 InstantiateClassMembers(NameLoc, RecordDef,
10369 getTemplateInstantiationArgs(Record), TSK);
10371 if (TSK == TSK_ExplicitInstantiationDefinition)
10372 MarkVTableUsed(NameLoc, RecordDef, true);
10374 // FIXME: We don't have any representation for explicit instantiations of
10375 // member classes. Such a representation is not needed for compilation, but it
10376 // should be available for clients that want to see all of the declarations in
10377 // the source code.
10378 return TagD;
10381 DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
10382 SourceLocation ExternLoc,
10383 SourceLocation TemplateLoc,
10384 Declarator &D) {
10385 // Explicit instantiations always require a name.
10386 // TODO: check if/when DNInfo should replace Name.
10387 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10388 DeclarationName Name = NameInfo.getName();
10389 if (!Name) {
10390 if (!D.isInvalidType())
10391 Diag(D.getDeclSpec().getBeginLoc(),
10392 diag::err_explicit_instantiation_requires_name)
10393 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
10395 return true;
10398 // The scope passed in may not be a decl scope. Zip up the scope tree until
10399 // we find one that is.
10400 while ((S->getFlags() & Scope::DeclScope) == 0 ||
10401 (S->getFlags() & Scope::TemplateParamScope) != 0)
10402 S = S->getParent();
10404 // Determine the type of the declaration.
10405 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
10406 QualType R = T->getType();
10407 if (R.isNull())
10408 return true;
10410 // C++ [dcl.stc]p1:
10411 // A storage-class-specifier shall not be specified in [...] an explicit
10412 // instantiation (14.7.2) directive.
10413 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
10414 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
10415 << Name;
10416 return true;
10417 } else if (D.getDeclSpec().getStorageClassSpec()
10418 != DeclSpec::SCS_unspecified) {
10419 // Complain about then remove the storage class specifier.
10420 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
10421 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10423 D.getMutableDeclSpec().ClearStorageClassSpecs();
10426 // C++0x [temp.explicit]p1:
10427 // [...] An explicit instantiation of a function template shall not use the
10428 // inline or constexpr specifiers.
10429 // Presumably, this also applies to member functions of class templates as
10430 // well.
10431 if (D.getDeclSpec().isInlineSpecified())
10432 Diag(D.getDeclSpec().getInlineSpecLoc(),
10433 getLangOpts().CPlusPlus11 ?
10434 diag::err_explicit_instantiation_inline :
10435 diag::warn_explicit_instantiation_inline_0x)
10436 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
10437 if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
10438 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
10439 // not already specified.
10440 Diag(D.getDeclSpec().getConstexprSpecLoc(),
10441 diag::err_explicit_instantiation_constexpr);
10443 // A deduction guide is not on the list of entities that can be explicitly
10444 // instantiated.
10445 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
10446 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
10447 << /*explicit instantiation*/ 0;
10448 return true;
10451 // C++0x [temp.explicit]p2:
10452 // There are two forms of explicit instantiation: an explicit instantiation
10453 // definition and an explicit instantiation declaration. An explicit
10454 // instantiation declaration begins with the extern keyword. [...]
10455 TemplateSpecializationKind TSK
10456 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
10457 : TSK_ExplicitInstantiationDeclaration;
10459 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
10460 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
10462 if (!R->isFunctionType()) {
10463 // C++ [temp.explicit]p1:
10464 // A [...] static data member of a class template can be explicitly
10465 // instantiated from the member definition associated with its class
10466 // template.
10467 // C++1y [temp.explicit]p1:
10468 // A [...] variable [...] template specialization can be explicitly
10469 // instantiated from its template.
10470 if (Previous.isAmbiguous())
10471 return true;
10473 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
10474 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
10476 if (!PrevTemplate) {
10477 if (!Prev || !Prev->isStaticDataMember()) {
10478 // We expect to see a static data member here.
10479 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
10480 << Name;
10481 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10482 P != PEnd; ++P)
10483 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
10484 return true;
10487 if (!Prev->getInstantiatedFromStaticDataMember()) {
10488 // FIXME: Check for explicit specialization?
10489 Diag(D.getIdentifierLoc(),
10490 diag::err_explicit_instantiation_data_member_not_instantiated)
10491 << Prev;
10492 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
10493 // FIXME: Can we provide a note showing where this was declared?
10494 return true;
10496 } else {
10497 // Explicitly instantiate a variable template.
10499 // C++1y [dcl.spec.auto]p6:
10500 // ... A program that uses auto or decltype(auto) in a context not
10501 // explicitly allowed in this section is ill-formed.
10503 // This includes auto-typed variable template instantiations.
10504 if (R->isUndeducedType()) {
10505 Diag(T->getTypeLoc().getBeginLoc(),
10506 diag::err_auto_not_allowed_var_inst);
10507 return true;
10510 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10511 // C++1y [temp.explicit]p3:
10512 // If the explicit instantiation is for a variable, the unqualified-id
10513 // in the declaration shall be a template-id.
10514 Diag(D.getIdentifierLoc(),
10515 diag::err_explicit_instantiation_without_template_id)
10516 << PrevTemplate;
10517 Diag(PrevTemplate->getLocation(),
10518 diag::note_explicit_instantiation_here);
10519 return true;
10522 // Translate the parser's template argument list into our AST format.
10523 TemplateArgumentListInfo TemplateArgs =
10524 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
10526 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
10527 D.getIdentifierLoc(), TemplateArgs);
10528 if (Res.isInvalid())
10529 return true;
10531 if (!Res.isUsable()) {
10532 // We somehow specified dependent template arguments in an explicit
10533 // instantiation. This should probably only happen during error
10534 // recovery.
10535 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent);
10536 return true;
10539 // Ignore access control bits, we don't need them for redeclaration
10540 // checking.
10541 Prev = cast<VarDecl>(Res.get());
10544 // C++0x [temp.explicit]p2:
10545 // If the explicit instantiation is for a member function, a member class
10546 // or a static data member of a class template specialization, the name of
10547 // the class template specialization in the qualified-id for the member
10548 // name shall be a simple-template-id.
10550 // C++98 has the same restriction, just worded differently.
10552 // This does not apply to variable template specializations, where the
10553 // template-id is in the unqualified-id instead.
10554 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
10555 Diag(D.getIdentifierLoc(),
10556 diag::ext_explicit_instantiation_without_qualified_id)
10557 << Prev << D.getCXXScopeSpec().getRange();
10559 CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
10561 // Verify that it is okay to explicitly instantiate here.
10562 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
10563 SourceLocation POI = Prev->getPointOfInstantiation();
10564 bool HasNoEffect = false;
10565 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
10566 PrevTSK, POI, HasNoEffect))
10567 return true;
10569 if (!HasNoEffect) {
10570 // Instantiate static data member or variable template.
10571 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
10572 // Merge attributes.
10573 ProcessDeclAttributeList(S, Prev, D.getDeclSpec().getAttributes());
10574 if (TSK == TSK_ExplicitInstantiationDefinition)
10575 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
10578 // Check the new variable specialization against the parsed input.
10579 if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) {
10580 Diag(T->getTypeLoc().getBeginLoc(),
10581 diag::err_invalid_var_template_spec_type)
10582 << 0 << PrevTemplate << R << Prev->getType();
10583 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
10584 << 2 << PrevTemplate->getDeclName();
10585 return true;
10588 // FIXME: Create an ExplicitInstantiation node?
10589 return (Decl*) nullptr;
10592 // If the declarator is a template-id, translate the parser's template
10593 // argument list into our AST format.
10594 bool HasExplicitTemplateArgs = false;
10595 TemplateArgumentListInfo TemplateArgs;
10596 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
10597 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
10598 HasExplicitTemplateArgs = true;
10601 // C++ [temp.explicit]p1:
10602 // A [...] function [...] can be explicitly instantiated from its template.
10603 // A member function [...] of a class template can be explicitly
10604 // instantiated from the member definition associated with its class
10605 // template.
10606 UnresolvedSet<8> TemplateMatches;
10607 FunctionDecl *NonTemplateMatch = nullptr;
10608 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
10609 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10610 P != PEnd; ++P) {
10611 NamedDecl *Prev = *P;
10612 if (!HasExplicitTemplateArgs) {
10613 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
10614 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
10615 /*AdjustExceptionSpec*/true);
10616 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
10617 if (Method->getPrimaryTemplate()) {
10618 TemplateMatches.addDecl(Method, P.getAccess());
10619 } else {
10620 // FIXME: Can this assert ever happen? Needs a test.
10621 assert(!NonTemplateMatch && "Multiple NonTemplateMatches");
10622 NonTemplateMatch = Method;
10628 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
10629 if (!FunTmpl)
10630 continue;
10632 TemplateDeductionInfo Info(FailedCandidates.getLocation());
10633 FunctionDecl *Specialization = nullptr;
10634 if (TemplateDeductionResult TDK
10635 = DeduceTemplateArguments(FunTmpl,
10636 (HasExplicitTemplateArgs ? &TemplateArgs
10637 : nullptr),
10638 R, Specialization, Info)) {
10639 // Keep track of almost-matches.
10640 FailedCandidates.addCandidate()
10641 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
10642 MakeDeductionFailureInfo(Context, TDK, Info));
10643 (void)TDK;
10644 continue;
10647 // Target attributes are part of the cuda function signature, so
10648 // the cuda target of the instantiated function must match that of its
10649 // template. Given that C++ template deduction does not take
10650 // target attributes into account, we reject candidates here that
10651 // have a different target.
10652 if (LangOpts.CUDA &&
10653 IdentifyCUDATarget(Specialization,
10654 /* IgnoreImplicitHDAttr = */ true) !=
10655 IdentifyCUDATarget(D.getDeclSpec().getAttributes())) {
10656 FailedCandidates.addCandidate().set(
10657 P.getPair(), FunTmpl->getTemplatedDecl(),
10658 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
10659 continue;
10662 TemplateMatches.addDecl(Specialization, P.getAccess());
10665 FunctionDecl *Specialization = NonTemplateMatch;
10666 if (!Specialization) {
10667 // Find the most specialized function template specialization.
10668 UnresolvedSetIterator Result = getMostSpecialized(
10669 TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates,
10670 D.getIdentifierLoc(),
10671 PDiag(diag::err_explicit_instantiation_not_known) << Name,
10672 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
10673 PDiag(diag::note_explicit_instantiation_candidate));
10675 if (Result == TemplateMatches.end())
10676 return true;
10678 // Ignore access control bits, we don't need them for redeclaration checking.
10679 Specialization = cast<FunctionDecl>(*Result);
10682 // C++11 [except.spec]p4
10683 // In an explicit instantiation an exception-specification may be specified,
10684 // but is not required.
10685 // If an exception-specification is specified in an explicit instantiation
10686 // directive, it shall be compatible with the exception-specifications of
10687 // other declarations of that function.
10688 if (auto *FPT = R->getAs<FunctionProtoType>())
10689 if (FPT->hasExceptionSpec()) {
10690 unsigned DiagID =
10691 diag::err_mismatched_exception_spec_explicit_instantiation;
10692 if (getLangOpts().MicrosoftExt)
10693 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
10694 bool Result = CheckEquivalentExceptionSpec(
10695 PDiag(DiagID) << Specialization->getType(),
10696 PDiag(diag::note_explicit_instantiation_here),
10697 Specialization->getType()->getAs<FunctionProtoType>(),
10698 Specialization->getLocation(), FPT, D.getBeginLoc());
10699 // In Microsoft mode, mismatching exception specifications just cause a
10700 // warning.
10701 if (!getLangOpts().MicrosoftExt && Result)
10702 return true;
10705 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
10706 Diag(D.getIdentifierLoc(),
10707 diag::err_explicit_instantiation_member_function_not_instantiated)
10708 << Specialization
10709 << (Specialization->getTemplateSpecializationKind() ==
10710 TSK_ExplicitSpecialization);
10711 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
10712 return true;
10715 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
10716 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
10717 PrevDecl = Specialization;
10719 if (PrevDecl) {
10720 bool HasNoEffect = false;
10721 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
10722 PrevDecl,
10723 PrevDecl->getTemplateSpecializationKind(),
10724 PrevDecl->getPointOfInstantiation(),
10725 HasNoEffect))
10726 return true;
10728 // FIXME: We may still want to build some representation of this
10729 // explicit specialization.
10730 if (HasNoEffect)
10731 return (Decl*) nullptr;
10734 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
10735 // functions
10736 // valarray<size_t>::valarray(size_t) and
10737 // valarray<size_t>::~valarray()
10738 // that it declared to have internal linkage with the internal_linkage
10739 // attribute. Ignore the explicit instantiation declaration in this case.
10740 if (Specialization->hasAttr<InternalLinkageAttr>() &&
10741 TSK == TSK_ExplicitInstantiationDeclaration) {
10742 if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
10743 if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
10744 RD->isInStdNamespace())
10745 return (Decl*) nullptr;
10748 ProcessDeclAttributeList(S, Specialization, D.getDeclSpec().getAttributes());
10750 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10751 // instantiation declarations.
10752 if (TSK == TSK_ExplicitInstantiationDefinition &&
10753 Specialization->hasAttr<DLLImportAttr>() &&
10754 Context.getTargetInfo().getCXXABI().isMicrosoft())
10755 TSK = TSK_ExplicitInstantiationDeclaration;
10757 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
10759 if (Specialization->isDefined()) {
10760 // Let the ASTConsumer know that this function has been explicitly
10761 // instantiated now, and its linkage might have changed.
10762 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
10763 } else if (TSK == TSK_ExplicitInstantiationDefinition)
10764 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
10766 // C++0x [temp.explicit]p2:
10767 // If the explicit instantiation is for a member function, a member class
10768 // or a static data member of a class template specialization, the name of
10769 // the class template specialization in the qualified-id for the member
10770 // name shall be a simple-template-id.
10772 // C++98 has the same restriction, just worded differently.
10773 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
10774 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
10775 D.getCXXScopeSpec().isSet() &&
10776 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
10777 Diag(D.getIdentifierLoc(),
10778 diag::ext_explicit_instantiation_without_qualified_id)
10779 << Specialization << D.getCXXScopeSpec().getRange();
10781 CheckExplicitInstantiation(
10782 *this,
10783 FunTmpl ? (NamedDecl *)FunTmpl
10784 : Specialization->getInstantiatedFromMemberFunction(),
10785 D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
10787 // FIXME: Create some kind of ExplicitInstantiationDecl here.
10788 return (Decl*) nullptr;
10791 TypeResult
10792 Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
10793 const CXXScopeSpec &SS, IdentifierInfo *Name,
10794 SourceLocation TagLoc, SourceLocation NameLoc) {
10795 // This has to hold, because SS is expected to be defined.
10796 assert(Name && "Expected a name in a dependent tag");
10798 NestedNameSpecifier *NNS = SS.getScopeRep();
10799 if (!NNS)
10800 return true;
10802 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10804 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
10805 Diag(NameLoc, diag::err_dependent_tag_decl)
10806 << (TUK == TUK_Definition) << llvm::to_underlying(Kind)
10807 << SS.getRange();
10808 return true;
10811 // Create the resulting type.
10812 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10813 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
10815 // Create type-source location information for this type.
10816 TypeLocBuilder TLB;
10817 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
10818 TL.setElaboratedKeywordLoc(TagLoc);
10819 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10820 TL.setNameLoc(NameLoc);
10821 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
10824 TypeResult Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
10825 const CXXScopeSpec &SS,
10826 const IdentifierInfo &II,
10827 SourceLocation IdLoc,
10828 ImplicitTypenameContext IsImplicitTypename) {
10829 if (SS.isInvalid())
10830 return true;
10832 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
10833 Diag(TypenameLoc,
10834 getLangOpts().CPlusPlus11 ?
10835 diag::warn_cxx98_compat_typename_outside_of_template :
10836 diag::ext_typename_outside_of_template)
10837 << FixItHint::CreateRemoval(TypenameLoc);
10839 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10840 TypeSourceInfo *TSI = nullptr;
10841 QualType T =
10842 CheckTypenameType((TypenameLoc.isValid() ||
10843 IsImplicitTypename == ImplicitTypenameContext::Yes)
10844 ? ElaboratedTypeKeyword::Typename
10845 : ElaboratedTypeKeyword::None,
10846 TypenameLoc, QualifierLoc, II, IdLoc, &TSI,
10847 /*DeducedTSTContext=*/true);
10848 if (T.isNull())
10849 return true;
10850 return CreateParsedType(T, TSI);
10853 TypeResult
10854 Sema::ActOnTypenameType(Scope *S,
10855 SourceLocation TypenameLoc,
10856 const CXXScopeSpec &SS,
10857 SourceLocation TemplateKWLoc,
10858 TemplateTy TemplateIn,
10859 IdentifierInfo *TemplateII,
10860 SourceLocation TemplateIILoc,
10861 SourceLocation LAngleLoc,
10862 ASTTemplateArgsPtr TemplateArgsIn,
10863 SourceLocation RAngleLoc) {
10864 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
10865 Diag(TypenameLoc,
10866 getLangOpts().CPlusPlus11 ?
10867 diag::warn_cxx98_compat_typename_outside_of_template :
10868 diag::ext_typename_outside_of_template)
10869 << FixItHint::CreateRemoval(TypenameLoc);
10871 // Strangely, non-type results are not ignored by this lookup, so the
10872 // program is ill-formed if it finds an injected-class-name.
10873 if (TypenameLoc.isValid()) {
10874 auto *LookupRD =
10875 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
10876 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
10877 Diag(TemplateIILoc,
10878 diag::ext_out_of_line_qualified_id_type_names_constructor)
10879 << TemplateII << 0 /*injected-class-name used as template name*/
10880 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
10884 // Translate the parser's template argument list in our AST format.
10885 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10886 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10888 TemplateName Template = TemplateIn.get();
10889 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
10890 // Construct a dependent template specialization type.
10891 assert(DTN && "dependent template has non-dependent name?");
10892 assert(DTN->getQualifier() == SS.getScopeRep());
10893 QualType T = Context.getDependentTemplateSpecializationType(
10894 ElaboratedTypeKeyword::Typename, DTN->getQualifier(),
10895 DTN->getIdentifier(), TemplateArgs.arguments());
10897 // Create source-location information for this type.
10898 TypeLocBuilder Builder;
10899 DependentTemplateSpecializationTypeLoc SpecTL
10900 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
10901 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
10902 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
10903 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
10904 SpecTL.setTemplateNameLoc(TemplateIILoc);
10905 SpecTL.setLAngleLoc(LAngleLoc);
10906 SpecTL.setRAngleLoc(RAngleLoc);
10907 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
10908 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
10909 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
10912 QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
10913 if (T.isNull())
10914 return true;
10916 // Provide source-location information for the template specialization type.
10917 TypeLocBuilder Builder;
10918 TemplateSpecializationTypeLoc SpecTL
10919 = Builder.push<TemplateSpecializationTypeLoc>(T);
10920 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
10921 SpecTL.setTemplateNameLoc(TemplateIILoc);
10922 SpecTL.setLAngleLoc(LAngleLoc);
10923 SpecTL.setRAngleLoc(RAngleLoc);
10924 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
10925 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
10927 T = Context.getElaboratedType(ElaboratedTypeKeyword::Typename,
10928 SS.getScopeRep(), T);
10929 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
10930 TL.setElaboratedKeywordLoc(TypenameLoc);
10931 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10933 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
10934 return CreateParsedType(T, TSI);
10938 /// Determine whether this failed name lookup should be treated as being
10939 /// disabled by a usage of std::enable_if.
10940 static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
10941 SourceRange &CondRange, Expr *&Cond) {
10942 // We must be looking for a ::type...
10943 if (!II.isStr("type"))
10944 return false;
10946 // ... within an explicitly-written template specialization...
10947 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
10948 return false;
10949 TypeLoc EnableIfTy = NNS.getTypeLoc();
10950 TemplateSpecializationTypeLoc EnableIfTSTLoc =
10951 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
10952 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
10953 return false;
10954 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
10956 // ... which names a complete class template declaration...
10957 const TemplateDecl *EnableIfDecl =
10958 EnableIfTST->getTemplateName().getAsTemplateDecl();
10959 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
10960 return false;
10962 // ... called "enable_if".
10963 const IdentifierInfo *EnableIfII =
10964 EnableIfDecl->getDeclName().getAsIdentifierInfo();
10965 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
10966 return false;
10968 // Assume the first template argument is the condition.
10969 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
10971 // Dig out the condition.
10972 Cond = nullptr;
10973 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
10974 != TemplateArgument::Expression)
10975 return true;
10977 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
10979 // Ignore Boolean literals; they add no value.
10980 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
10981 Cond = nullptr;
10983 return true;
10986 QualType
10987 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
10988 SourceLocation KeywordLoc,
10989 NestedNameSpecifierLoc QualifierLoc,
10990 const IdentifierInfo &II,
10991 SourceLocation IILoc,
10992 TypeSourceInfo **TSI,
10993 bool DeducedTSTContext) {
10994 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
10995 DeducedTSTContext);
10996 if (T.isNull())
10997 return QualType();
10999 *TSI = Context.CreateTypeSourceInfo(T);
11000 if (isa<DependentNameType>(T)) {
11001 DependentNameTypeLoc TL =
11002 (*TSI)->getTypeLoc().castAs<DependentNameTypeLoc>();
11003 TL.setElaboratedKeywordLoc(KeywordLoc);
11004 TL.setQualifierLoc(QualifierLoc);
11005 TL.setNameLoc(IILoc);
11006 } else {
11007 ElaboratedTypeLoc TL = (*TSI)->getTypeLoc().castAs<ElaboratedTypeLoc>();
11008 TL.setElaboratedKeywordLoc(KeywordLoc);
11009 TL.setQualifierLoc(QualifierLoc);
11010 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IILoc);
11012 return T;
11015 /// Build the type that describes a C++ typename specifier,
11016 /// e.g., "typename T::type".
11017 QualType
11018 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
11019 SourceLocation KeywordLoc,
11020 NestedNameSpecifierLoc QualifierLoc,
11021 const IdentifierInfo &II,
11022 SourceLocation IILoc, bool DeducedTSTContext) {
11023 CXXScopeSpec SS;
11024 SS.Adopt(QualifierLoc);
11026 DeclContext *Ctx = nullptr;
11027 if (QualifierLoc) {
11028 Ctx = computeDeclContext(SS);
11029 if (!Ctx) {
11030 // If the nested-name-specifier is dependent and couldn't be
11031 // resolved to a type, build a typename type.
11032 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
11033 return Context.getDependentNameType(Keyword,
11034 QualifierLoc.getNestedNameSpecifier(),
11035 &II);
11038 // If the nested-name-specifier refers to the current instantiation,
11039 // the "typename" keyword itself is superfluous. In C++03, the
11040 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
11041 // allows such extraneous "typename" keywords, and we retroactively
11042 // apply this DR to C++03 code with only a warning. In any case we continue.
11044 if (RequireCompleteDeclContext(SS, Ctx))
11045 return QualType();
11048 DeclarationName Name(&II);
11049 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
11050 if (Ctx)
11051 LookupQualifiedName(Result, Ctx, SS);
11052 else
11053 LookupName(Result, CurScope);
11054 unsigned DiagID = 0;
11055 Decl *Referenced = nullptr;
11056 switch (Result.getResultKind()) {
11057 case LookupResult::NotFound: {
11058 // If we're looking up 'type' within a template named 'enable_if', produce
11059 // a more specific diagnostic.
11060 SourceRange CondRange;
11061 Expr *Cond = nullptr;
11062 if (Ctx && isEnableIf(QualifierLoc, II, CondRange, Cond)) {
11063 // If we have a condition, narrow it down to the specific failed
11064 // condition.
11065 if (Cond) {
11066 Expr *FailedCond;
11067 std::string FailedDescription;
11068 std::tie(FailedCond, FailedDescription) =
11069 findFailedBooleanCondition(Cond);
11071 Diag(FailedCond->getExprLoc(),
11072 diag::err_typename_nested_not_found_requirement)
11073 << FailedDescription
11074 << FailedCond->getSourceRange();
11075 return QualType();
11078 Diag(CondRange.getBegin(),
11079 diag::err_typename_nested_not_found_enable_if)
11080 << Ctx << CondRange;
11081 return QualType();
11084 DiagID = Ctx ? diag::err_typename_nested_not_found
11085 : diag::err_unknown_typename;
11086 break;
11089 case LookupResult::FoundUnresolvedValue: {
11090 // We found a using declaration that is a value. Most likely, the using
11091 // declaration itself is meant to have the 'typename' keyword.
11092 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11093 IILoc);
11094 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
11095 << Name << Ctx << FullRange;
11096 if (UnresolvedUsingValueDecl *Using
11097 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
11098 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
11099 Diag(Loc, diag::note_using_value_decl_missing_typename)
11100 << FixItHint::CreateInsertion(Loc, "typename ");
11103 // Fall through to create a dependent typename type, from which we can recover
11104 // better.
11105 [[fallthrough]];
11107 case LookupResult::NotFoundInCurrentInstantiation:
11108 // Okay, it's a member of an unknown instantiation.
11109 return Context.getDependentNameType(Keyword,
11110 QualifierLoc.getNestedNameSpecifier(),
11111 &II);
11113 case LookupResult::Found:
11114 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
11115 // C++ [class.qual]p2:
11116 // In a lookup in which function names are not ignored and the
11117 // nested-name-specifier nominates a class C, if the name specified
11118 // after the nested-name-specifier, when looked up in C, is the
11119 // injected-class-name of C [...] then the name is instead considered
11120 // to name the constructor of class C.
11122 // Unlike in an elaborated-type-specifier, function names are not ignored
11123 // in typename-specifier lookup. However, they are ignored in all the
11124 // contexts where we form a typename type with no keyword (that is, in
11125 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
11127 // FIXME: That's not strictly true: mem-initializer-id lookup does not
11128 // ignore functions, but that appears to be an oversight.
11129 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
11130 auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
11131 if (Keyword == ElaboratedTypeKeyword::Typename && LookupRD && FoundRD &&
11132 FoundRD->isInjectedClassName() &&
11133 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
11134 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
11135 << &II << 1 << 0 /*'typename' keyword used*/;
11137 // We found a type. Build an ElaboratedType, since the
11138 // typename-specifier was just sugar.
11139 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
11140 return Context.getElaboratedType(Keyword,
11141 QualifierLoc.getNestedNameSpecifier(),
11142 Context.getTypeDeclType(Type));
11145 // C++ [dcl.type.simple]p2:
11146 // A type-specifier of the form
11147 // typename[opt] nested-name-specifier[opt] template-name
11148 // is a placeholder for a deduced class type [...].
11149 if (getLangOpts().CPlusPlus17) {
11150 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
11151 if (!DeducedTSTContext) {
11152 QualType T(QualifierLoc
11153 ? QualifierLoc.getNestedNameSpecifier()->getAsType()
11154 : nullptr, 0);
11155 if (!T.isNull())
11156 Diag(IILoc, diag::err_dependent_deduced_tst)
11157 << (int)getTemplateNameKindForDiagnostics(TemplateName(TD)) << T;
11158 else
11159 Diag(IILoc, diag::err_deduced_tst)
11160 << (int)getTemplateNameKindForDiagnostics(TemplateName(TD));
11161 Diag(TD->getLocation(), diag::note_template_decl_here);
11162 return QualType();
11164 return Context.getElaboratedType(
11165 Keyword, QualifierLoc.getNestedNameSpecifier(),
11166 Context.getDeducedTemplateSpecializationType(TemplateName(TD),
11167 QualType(), false));
11171 DiagID = Ctx ? diag::err_typename_nested_not_type
11172 : diag::err_typename_not_type;
11173 Referenced = Result.getFoundDecl();
11174 break;
11176 case LookupResult::FoundOverloaded:
11177 DiagID = Ctx ? diag::err_typename_nested_not_type
11178 : diag::err_typename_not_type;
11179 Referenced = *Result.begin();
11180 break;
11182 case LookupResult::Ambiguous:
11183 return QualType();
11186 // If we get here, it's because name lookup did not find a
11187 // type. Emit an appropriate diagnostic and return an error.
11188 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11189 IILoc);
11190 if (Ctx)
11191 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
11192 else
11193 Diag(IILoc, DiagID) << FullRange << Name;
11194 if (Referenced)
11195 Diag(Referenced->getLocation(),
11196 Ctx ? diag::note_typename_member_refers_here
11197 : diag::note_typename_refers_here)
11198 << Name;
11199 return QualType();
11202 namespace {
11203 // See Sema::RebuildTypeInCurrentInstantiation
11204 class CurrentInstantiationRebuilder
11205 : public TreeTransform<CurrentInstantiationRebuilder> {
11206 SourceLocation Loc;
11207 DeclarationName Entity;
11209 public:
11210 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
11212 CurrentInstantiationRebuilder(Sema &SemaRef,
11213 SourceLocation Loc,
11214 DeclarationName Entity)
11215 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11216 Loc(Loc), Entity(Entity) { }
11218 /// Determine whether the given type \p T has already been
11219 /// transformed.
11221 /// For the purposes of type reconstruction, a type has already been
11222 /// transformed if it is NULL or if it is not dependent.
11223 bool AlreadyTransformed(QualType T) {
11224 return T.isNull() || !T->isInstantiationDependentType();
11227 /// Returns the location of the entity whose type is being
11228 /// rebuilt.
11229 SourceLocation getBaseLocation() { return Loc; }
11231 /// Returns the name of the entity whose type is being rebuilt.
11232 DeclarationName getBaseEntity() { return Entity; }
11234 /// Sets the "base" location and entity when that
11235 /// information is known based on another transformation.
11236 void setBase(SourceLocation Loc, DeclarationName Entity) {
11237 this->Loc = Loc;
11238 this->Entity = Entity;
11241 ExprResult TransformLambdaExpr(LambdaExpr *E) {
11242 // Lambdas never need to be transformed.
11243 return E;
11246 } // end anonymous namespace
11248 /// Rebuilds a type within the context of the current instantiation.
11250 /// The type \p T is part of the type of an out-of-line member definition of
11251 /// a class template (or class template partial specialization) that was parsed
11252 /// and constructed before we entered the scope of the class template (or
11253 /// partial specialization thereof). This routine will rebuild that type now
11254 /// that we have entered the declarator's scope, which may produce different
11255 /// canonical types, e.g.,
11257 /// \code
11258 /// template<typename T>
11259 /// struct X {
11260 /// typedef T* pointer;
11261 /// pointer data();
11262 /// };
11264 /// template<typename T>
11265 /// typename X<T>::pointer X<T>::data() { ... }
11266 /// \endcode
11268 /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
11269 /// since we do not know that we can look into X<T> when we parsed the type.
11270 /// This function will rebuild the type, performing the lookup of "pointer"
11271 /// in X<T> and returning an ElaboratedType whose canonical type is the same
11272 /// as the canonical type of T*, allowing the return types of the out-of-line
11273 /// definition and the declaration to match.
11274 TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
11275 SourceLocation Loc,
11276 DeclarationName Name) {
11277 if (!T || !T->getType()->isInstantiationDependentType())
11278 return T;
11280 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
11281 return Rebuilder.TransformType(T);
11284 ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
11285 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
11286 DeclarationName());
11287 return Rebuilder.TransformExpr(E);
11290 bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
11291 if (SS.isInvalid())
11292 return true;
11294 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11295 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
11296 DeclarationName());
11297 NestedNameSpecifierLoc Rebuilt
11298 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
11299 if (!Rebuilt)
11300 return true;
11302 SS.Adopt(Rebuilt);
11303 return false;
11306 /// Rebuild the template parameters now that we know we're in a current
11307 /// instantiation.
11308 bool Sema::RebuildTemplateParamsInCurrentInstantiation(
11309 TemplateParameterList *Params) {
11310 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11311 Decl *Param = Params->getParam(I);
11313 // There is nothing to rebuild in a type parameter.
11314 if (isa<TemplateTypeParmDecl>(Param))
11315 continue;
11317 // Rebuild the template parameter list of a template template parameter.
11318 if (TemplateTemplateParmDecl *TTP
11319 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
11320 if (RebuildTemplateParamsInCurrentInstantiation(
11321 TTP->getTemplateParameters()))
11322 return true;
11324 continue;
11327 // Rebuild the type of a non-type template parameter.
11328 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
11329 TypeSourceInfo *NewTSI
11330 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
11331 NTTP->getLocation(),
11332 NTTP->getDeclName());
11333 if (!NewTSI)
11334 return true;
11336 if (NewTSI->getType()->isUndeducedType()) {
11337 // C++17 [temp.dep.expr]p3:
11338 // An id-expression is type-dependent if it contains
11339 // - an identifier associated by name lookup with a non-type
11340 // template-parameter declared with a type that contains a
11341 // placeholder type (7.1.7.4),
11342 NewTSI = SubstAutoTypeSourceInfoDependent(NewTSI);
11345 if (NewTSI != NTTP->getTypeSourceInfo()) {
11346 NTTP->setTypeSourceInfo(NewTSI);
11347 NTTP->setType(NewTSI->getType());
11351 return false;
11354 /// Produces a formatted string that describes the binding of
11355 /// template parameters to template arguments.
11356 std::string
11357 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
11358 const TemplateArgumentList &Args) {
11359 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
11362 std::string
11363 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
11364 const TemplateArgument *Args,
11365 unsigned NumArgs) {
11366 SmallString<128> Str;
11367 llvm::raw_svector_ostream Out(Str);
11369 if (!Params || Params->size() == 0 || NumArgs == 0)
11370 return std::string();
11372 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11373 if (I >= NumArgs)
11374 break;
11376 if (I == 0)
11377 Out << "[with ";
11378 else
11379 Out << ", ";
11381 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
11382 Out << Id->getName();
11383 } else {
11384 Out << '$' << I;
11387 Out << " = ";
11388 Args[I].print(getPrintingPolicy(), Out,
11389 TemplateParameterList::shouldIncludeTypeForArgument(
11390 getPrintingPolicy(), Params, I));
11393 Out << ']';
11394 return std::string(Out.str());
11397 void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
11398 CachedTokens &Toks) {
11399 if (!FD)
11400 return;
11402 auto LPT = std::make_unique<LateParsedTemplate>();
11404 // Take tokens to avoid allocations
11405 LPT->Toks.swap(Toks);
11406 LPT->D = FnD;
11407 LPT->FPO = getCurFPFeatures();
11408 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
11410 FD->setLateTemplateParsed(true);
11413 void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
11414 if (!FD)
11415 return;
11416 FD->setLateTemplateParsed(false);
11419 bool Sema::IsInsideALocalClassWithinATemplateFunction() {
11420 DeclContext *DC = CurContext;
11422 while (DC) {
11423 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
11424 const FunctionDecl *FD = RD->isLocalClass();
11425 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
11426 } else if (DC->isTranslationUnit() || DC->isNamespace())
11427 return false;
11429 DC = DC->getParent();
11431 return false;
11434 namespace {
11435 /// Walk the path from which a declaration was instantiated, and check
11436 /// that every explicit specialization along that path is visible. This enforces
11437 /// C++ [temp.expl.spec]/6:
11439 /// If a template, a member template or a member of a class template is
11440 /// explicitly specialized then that specialization shall be declared before
11441 /// the first use of that specialization that would cause an implicit
11442 /// instantiation to take place, in every translation unit in which such a
11443 /// use occurs; no diagnostic is required.
11445 /// and also C++ [temp.class.spec]/1:
11447 /// A partial specialization shall be declared before the first use of a
11448 /// class template specialization that would make use of the partial
11449 /// specialization as the result of an implicit or explicit instantiation
11450 /// in every translation unit in which such a use occurs; no diagnostic is
11451 /// required.
11452 class ExplicitSpecializationVisibilityChecker {
11453 Sema &S;
11454 SourceLocation Loc;
11455 llvm::SmallVector<Module *, 8> Modules;
11456 Sema::AcceptableKind Kind;
11458 public:
11459 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
11460 Sema::AcceptableKind Kind)
11461 : S(S), Loc(Loc), Kind(Kind) {}
11463 void check(NamedDecl *ND) {
11464 if (auto *FD = dyn_cast<FunctionDecl>(ND))
11465 return checkImpl(FD);
11466 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
11467 return checkImpl(RD);
11468 if (auto *VD = dyn_cast<VarDecl>(ND))
11469 return checkImpl(VD);
11470 if (auto *ED = dyn_cast<EnumDecl>(ND))
11471 return checkImpl(ED);
11474 private:
11475 void diagnose(NamedDecl *D, bool IsPartialSpec) {
11476 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
11477 : Sema::MissingImportKind::ExplicitSpecialization;
11478 const bool Recover = true;
11480 // If we got a custom set of modules (because only a subset of the
11481 // declarations are interesting), use them, otherwise let
11482 // diagnoseMissingImport intelligently pick some.
11483 if (Modules.empty())
11484 S.diagnoseMissingImport(Loc, D, Kind, Recover);
11485 else
11486 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
11489 bool CheckMemberSpecialization(const NamedDecl *D) {
11490 return Kind == Sema::AcceptableKind::Visible
11491 ? S.hasVisibleMemberSpecialization(D)
11492 : S.hasReachableMemberSpecialization(D);
11495 bool CheckExplicitSpecialization(const NamedDecl *D) {
11496 return Kind == Sema::AcceptableKind::Visible
11497 ? S.hasVisibleExplicitSpecialization(D)
11498 : S.hasReachableExplicitSpecialization(D);
11501 bool CheckDeclaration(const NamedDecl *D) {
11502 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
11503 : S.hasReachableDeclaration(D);
11506 // Check a specific declaration. There are three problematic cases:
11508 // 1) The declaration is an explicit specialization of a template
11509 // specialization.
11510 // 2) The declaration is an explicit specialization of a member of an
11511 // templated class.
11512 // 3) The declaration is an instantiation of a template, and that template
11513 // is an explicit specialization of a member of a templated class.
11515 // We don't need to go any deeper than that, as the instantiation of the
11516 // surrounding class / etc is not triggered by whatever triggered this
11517 // instantiation, and thus should be checked elsewhere.
11518 template<typename SpecDecl>
11519 void checkImpl(SpecDecl *Spec) {
11520 bool IsHiddenExplicitSpecialization = false;
11521 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
11522 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
11523 ? !CheckMemberSpecialization(Spec)
11524 : !CheckExplicitSpecialization(Spec);
11525 } else {
11526 checkInstantiated(Spec);
11529 if (IsHiddenExplicitSpecialization)
11530 diagnose(Spec->getMostRecentDecl(), false);
11533 void checkInstantiated(FunctionDecl *FD) {
11534 if (auto *TD = FD->getPrimaryTemplate())
11535 checkTemplate(TD);
11538 void checkInstantiated(CXXRecordDecl *RD) {
11539 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
11540 if (!SD)
11541 return;
11543 auto From = SD->getSpecializedTemplateOrPartial();
11544 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
11545 checkTemplate(TD);
11546 else if (auto *TD =
11547 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
11548 if (!CheckDeclaration(TD))
11549 diagnose(TD, true);
11550 checkTemplate(TD);
11554 void checkInstantiated(VarDecl *RD) {
11555 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
11556 if (!SD)
11557 return;
11559 auto From = SD->getSpecializedTemplateOrPartial();
11560 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
11561 checkTemplate(TD);
11562 else if (auto *TD =
11563 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
11564 if (!CheckDeclaration(TD))
11565 diagnose(TD, true);
11566 checkTemplate(TD);
11570 void checkInstantiated(EnumDecl *FD) {}
11572 template<typename TemplDecl>
11573 void checkTemplate(TemplDecl *TD) {
11574 if (TD->isMemberSpecialization()) {
11575 if (!CheckMemberSpecialization(TD))
11576 diagnose(TD->getMostRecentDecl(), false);
11580 } // end anonymous namespace
11582 void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
11583 if (!getLangOpts().Modules)
11584 return;
11586 ExplicitSpecializationVisibilityChecker(*this, Loc,
11587 Sema::AcceptableKind::Visible)
11588 .check(Spec);
11591 void Sema::checkSpecializationReachability(SourceLocation Loc,
11592 NamedDecl *Spec) {
11593 if (!getLangOpts().CPlusPlusModules)
11594 return checkSpecializationVisibility(Loc, Spec);
11596 ExplicitSpecializationVisibilityChecker(*this, Loc,
11597 Sema::AcceptableKind::Reachable)
11598 .check(Spec);