clang 20.0.0git
SemaTemplate.cpp
Go to the documentation of this file.
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//===----------------------------------------------------------------------===//
10
11#include "TreeTransform.h"
14#include "clang/AST/Decl.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/ExprCXX.h"
28#include "clang/Sema/DeclSpec.h"
31#include "clang/Sema/Lookup.h"
32#include "clang/Sema/Overload.h"
34#include "clang/Sema/Scope.h"
35#include "clang/Sema/SemaCUDA.h"
37#include "clang/Sema/Template.h"
39#include "llvm/ADT/SmallBitVector.h"
40#include "llvm/ADT/StringExtras.h"
41
42#include <optional>
43using namespace clang;
44using namespace sema;
45
46// Exported for use by Parser.
49 unsigned N) {
50 if (!N) return SourceRange();
51 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
52}
53
54unsigned Sema::getTemplateDepth(Scope *S) const {
55 unsigned Depth = 0;
56
57 // Each template parameter scope represents one level of template parameter
58 // depth.
59 for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
60 TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
61 ++Depth;
62 }
63
64 // Note that there are template parameters with the given depth.
65 auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(Depth, D + 1); };
66
67 // Look for parameters of an enclosing generic lambda. We don't create a
68 // template parameter scope for these.
70 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FSI)) {
71 if (!LSI->TemplateParams.empty()) {
72 ParamsAtDepth(LSI->AutoTemplateParameterDepth);
73 break;
74 }
75 if (LSI->GLTemplateParameterList) {
76 ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
77 break;
78 }
79 }
80 }
81
82 // Look for parameters of an enclosing terse function template. We don't
83 // create a template parameter scope for these either.
84 for (const InventedTemplateParameterInfo &Info :
86 if (!Info.TemplateParams.empty()) {
87 ParamsAtDepth(Info.AutoTemplateParameterDepth);
88 break;
89 }
90 }
91
92 return Depth;
93}
94
95/// \brief Determine whether the declaration found is acceptable as the name
96/// of a template and, if so, return that template declaration. Otherwise,
97/// returns null.
98///
99/// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
100/// is true. In all other cases it will return a TemplateDecl (or null).
102 bool AllowFunctionTemplates,
103 bool AllowDependent) {
104 D = D->getUnderlyingDecl();
105
106 if (isa<TemplateDecl>(D)) {
107 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
108 return nullptr;
109
110 return D;
111 }
112
113 if (const auto *Record = dyn_cast<CXXRecordDecl>(D)) {
114 // C++ [temp.local]p1:
115 // Like normal (non-template) classes, class templates have an
116 // injected-class-name (Clause 9). The injected-class-name
117 // can be used with or without a template-argument-list. When
118 // it is used without a template-argument-list, it is
119 // equivalent to the injected-class-name followed by the
120 // template-parameters of the class template enclosed in
121 // <>. When it is used with a template-argument-list, it
122 // refers to the specified class template specialization,
123 // which could be the current specialization or another
124 // specialization.
125 if (Record->isInjectedClassName()) {
126 Record = cast<CXXRecordDecl>(Record->getDeclContext());
127 if (Record->getDescribedClassTemplate())
128 return Record->getDescribedClassTemplate();
129
130 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Record))
131 return Spec->getSpecializedTemplate();
132 }
133
134 return nullptr;
135 }
136
137 // 'using Dependent::foo;' can resolve to a template name.
138 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
139 // injected-class-name).
140 if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
141 return D;
142
143 return nullptr;
144}
145
147 bool AllowFunctionTemplates,
148 bool AllowDependent) {
149 LookupResult::Filter filter = R.makeFilter();
150 while (filter.hasNext()) {
151 NamedDecl *Orig = filter.next();
152 if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
153 filter.erase();
154 }
155 filter.done();
156}
157
159 bool AllowFunctionTemplates,
160 bool AllowDependent,
161 bool AllowNonTemplateFunctions) {
162 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
163 if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
164 return true;
165 if (AllowNonTemplateFunctions &&
166 isa<FunctionDecl>((*I)->getUnderlyingDecl()))
167 return true;
168 }
169
170 return false;
171}
172
174 CXXScopeSpec &SS,
175 bool hasTemplateKeyword,
176 const UnqualifiedId &Name,
177 ParsedType ObjectTypePtr,
178 bool EnteringContext,
179 TemplateTy &TemplateResult,
180 bool &MemberOfUnknownSpecialization,
181 bool Disambiguation) {
182 assert(getLangOpts().CPlusPlus && "No template names in C!");
183
184 DeclarationName TName;
185 MemberOfUnknownSpecialization = false;
186
187 switch (Name.getKind()) {
189 TName = DeclarationName(Name.Identifier);
190 break;
191
194 Name.OperatorFunctionId.Operator);
195 break;
196
198 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
199 break;
200
201 default:
202 return TNK_Non_template;
203 }
204
205 QualType ObjectType = ObjectTypePtr.get();
206
207 AssumedTemplateKind AssumedTemplate;
208 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
209 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
210 /*RequiredTemplate=*/SourceLocation(),
211 &AssumedTemplate,
212 /*AllowTypoCorrection=*/!Disambiguation))
213 return TNK_Non_template;
214 MemberOfUnknownSpecialization = R.wasNotFoundInCurrentInstantiation();
215
216 if (AssumedTemplate != AssumedTemplateKind::None) {
217 TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
218 // Let the parser know whether we found nothing or found functions; if we
219 // found nothing, we want to more carefully check whether this is actually
220 // a function template name versus some other kind of undeclared identifier.
221 return AssumedTemplate == AssumedTemplateKind::FoundNothing
224 }
225
226 if (R.empty())
227 return TNK_Non_template;
228
229 NamedDecl *D = nullptr;
230 UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(*R.begin());
231 if (R.isAmbiguous()) {
232 // If we got an ambiguity involving a non-function template, treat this
233 // as a template name, and pick an arbitrary template for error recovery.
234 bool AnyFunctionTemplates = false;
235 for (NamedDecl *FoundD : R) {
236 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
237 if (isa<FunctionTemplateDecl>(FoundTemplate))
238 AnyFunctionTemplates = true;
239 else {
240 D = FoundTemplate;
241 FoundUsingShadow = dyn_cast<UsingShadowDecl>(FoundD);
242 break;
243 }
244 }
245 }
246
247 // If we didn't find any templates at all, this isn't a template name.
248 // Leave the ambiguity for a later lookup to diagnose.
249 if (!D && !AnyFunctionTemplates) {
250 R.suppressDiagnostics();
251 return TNK_Non_template;
252 }
253
254 // If the only templates were function templates, filter out the rest.
255 // We'll diagnose the ambiguity later.
256 if (!D)
258 }
259
260 // At this point, we have either picked a single template name declaration D
261 // or we have a non-empty set of results R containing either one template name
262 // declaration or a set of function templates.
263
264 TemplateName Template;
265 TemplateNameKind TemplateKind;
266
267 unsigned ResultCount = R.end() - R.begin();
268 if (!D && ResultCount > 1) {
269 // We assume that we'll preserve the qualifier from a function
270 // template name in other ways.
271 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
272 TemplateKind = TNK_Function_template;
273
274 // We'll do this lookup again later.
276 } else {
277 if (!D) {
279 assert(D && "unambiguous result is not a template name");
280 }
281
282 if (isa<UnresolvedUsingValueDecl>(D)) {
283 // We don't yet know whether this is a template-name or not.
284 MemberOfUnknownSpecialization = true;
285 return TNK_Non_template;
286 }
287
288 TemplateDecl *TD = cast<TemplateDecl>(D);
289 Template =
290 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
291 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
292 if (!SS.isInvalid()) {
293 NestedNameSpecifier *Qualifier = SS.getScopeRep();
294 Template = Context.getQualifiedTemplateName(Qualifier, hasTemplateKeyword,
295 Template);
296 }
297
298 if (isa<FunctionTemplateDecl>(TD)) {
299 TemplateKind = TNK_Function_template;
300
301 // We'll do this lookup again later.
303 } else {
304 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
305 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
306 isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD));
307 TemplateKind =
308 isa<VarTemplateDecl>(TD) ? TNK_Var_template :
309 isa<ConceptDecl>(TD) ? TNK_Concept_template :
311 }
312 }
313
314 TemplateResult = TemplateTy::make(Template);
315 return TemplateKind;
316}
317
319 SourceLocation NameLoc, CXXScopeSpec &SS,
320 ParsedTemplateTy *Template /*=nullptr*/) {
321 // We could use redeclaration lookup here, but we don't need to: the
322 // syntactic form of a deduction guide is enough to identify it even
323 // if we can't look up the template name at all.
324 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
325 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
326 /*EnteringContext*/ false))
327 return false;
328
329 if (R.empty()) return false;
330 if (R.isAmbiguous()) {
331 // FIXME: Diagnose an ambiguity if we find at least one template.
333 return false;
334 }
335
336 // We only treat template-names that name type templates as valid deduction
337 // guide names.
339 if (!TD || !getAsTypeTemplateDecl(TD))
340 return false;
341
342 if (Template) {
344 SS.getScopeRep(), /*TemplateKeyword=*/false, TemplateName(TD));
345 *Template = TemplateTy::make(Name);
346 }
347 return true;
348}
349
351 SourceLocation IILoc,
352 Scope *S,
353 const CXXScopeSpec *SS,
354 TemplateTy &SuggestedTemplate,
355 TemplateNameKind &SuggestedKind) {
356 // We can't recover unless there's a dependent scope specifier preceding the
357 // template name.
358 // FIXME: Typo correction?
359 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
361 return false;
362
363 // The code is missing a 'template' keyword prior to the dependent template
364 // name.
366 Diag(IILoc, diag::err_template_kw_missing)
367 << Qualifier << II.getName()
368 << FixItHint::CreateInsertion(IILoc, "template ");
369 SuggestedTemplate
371 SuggestedKind = TNK_Dependent_template_name;
372 return true;
373}
374
376 QualType ObjectType, bool EnteringContext,
377 RequiredTemplateKind RequiredTemplate,
379 bool AllowTypoCorrection) {
380 if (ATK)
382
383 if (SS.isInvalid())
384 return true;
385
386 Found.setTemplateNameLookup(true);
387
388 // Determine where to perform name lookup
389 DeclContext *LookupCtx = nullptr;
390 bool IsDependent = false;
391 if (!ObjectType.isNull()) {
392 // This nested-name-specifier occurs in a member access expression, e.g.,
393 // x->B::f, and we are looking into the type of the object.
394 assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");
395 LookupCtx = computeDeclContext(ObjectType);
396 IsDependent = !LookupCtx && ObjectType->isDependentType();
397 assert((IsDependent || !ObjectType->isIncompleteType() ||
398 !ObjectType->getAs<TagType>() ||
399 ObjectType->castAs<TagType>()->isBeingDefined()) &&
400 "Caller should have completed object type");
401
402 // Template names cannot appear inside an Objective-C class or object type
403 // or a vector type.
404 //
405 // FIXME: This is wrong. For example:
406 //
407 // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
408 // Vec<int> vi;
409 // vi.Vec<int>::~Vec<int>();
410 //
411 // ... should be accepted but we will not treat 'Vec' as a template name
412 // here. The right thing to do would be to check if the name is a valid
413 // vector component name, and look up a template name if not. And similarly
414 // for lookups into Objective-C class and object types, where the same
415 // problem can arise.
416 if (ObjectType->isObjCObjectOrInterfaceType() ||
417 ObjectType->isVectorType()) {
418 Found.clear();
419 return false;
420 }
421 } else if (SS.isNotEmpty()) {
422 // This nested-name-specifier occurs after another nested-name-specifier,
423 // so long into the context associated with the prior nested-name-specifier.
424 LookupCtx = computeDeclContext(SS, EnteringContext);
425 IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
426
427 // The declaration context must be complete.
428 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
429 return true;
430 }
431
432 bool ObjectTypeSearchedInScope = false;
433 bool AllowFunctionTemplatesInLookup = true;
434 if (LookupCtx) {
435 // Perform "qualified" name lookup into the declaration context we
436 // computed, which is either the type of the base of a member access
437 // expression or the declaration context associated with a prior
438 // nested-name-specifier.
439 LookupQualifiedName(Found, LookupCtx);
440
441 // FIXME: The C++ standard does not clearly specify what happens in the
442 // case where the object type is dependent, and implementations vary. In
443 // Clang, we treat a name after a . or -> as a template-name if lookup
444 // finds a non-dependent member or member of the current instantiation that
445 // is a type template, or finds no such members and lookup in the context
446 // of the postfix-expression finds a type template. In the latter case, the
447 // name is nonetheless dependent, and we may resolve it to a member of an
448 // unknown specialization when we come to instantiate the template.
449 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
450 }
451
452 if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
453 // C++ [basic.lookup.classref]p1:
454 // In a class member access expression (5.2.5), if the . or -> token is
455 // immediately followed by an identifier followed by a <, the
456 // identifier must be looked up to determine whether the < is the
457 // beginning of a template argument list (14.2) or a less-than operator.
458 // The identifier is first looked up in the class of the object
459 // expression. If the identifier is not found, it is then looked up in
460 // the context of the entire postfix-expression and shall name a class
461 // template.
462 if (S)
463 LookupName(Found, S);
464
465 if (!ObjectType.isNull()) {
466 // FIXME: We should filter out all non-type templates here, particularly
467 // variable templates and concepts. But the exclusion of alias templates
468 // and template template parameters is a wording defect.
469 AllowFunctionTemplatesInLookup = false;
470 ObjectTypeSearchedInScope = true;
471 }
472
473 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
474 }
475
476 if (Found.isAmbiguous())
477 return false;
478
479 if (ATK && SS.isEmpty() && ObjectType.isNull() &&
480 !RequiredTemplate.hasTemplateKeyword()) {
481 // C++2a [temp.names]p2:
482 // A name is also considered to refer to a template if it is an
483 // unqualified-id followed by a < and name lookup finds either one or more
484 // functions or finds nothing.
485 //
486 // To keep our behavior consistent, we apply the "finds nothing" part in
487 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
488 // successfully form a call to an undeclared template-id.
489 bool AllFunctions =
490 getLangOpts().CPlusPlus20 && llvm::all_of(Found, [](NamedDecl *ND) {
491 return isa<FunctionDecl>(ND->getUnderlyingDecl());
492 });
493 if (AllFunctions || (Found.empty() && !IsDependent)) {
494 // If lookup found any functions, or if this is a name that can only be
495 // used for a function, then strongly assume this is a function
496 // template-id.
497 *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
500 Found.clear();
501 return false;
502 }
503 }
504
505 if (Found.empty() && !IsDependent && AllowTypoCorrection) {
506 // If we did not find any names, and this is not a disambiguation, attempt
507 // to correct any typos.
508 DeclarationName Name = Found.getLookupName();
509 Found.clear();
510 // Simple filter callback that, for keywords, only accepts the C++ *_cast
511 DefaultFilterCCC FilterCCC{};
512 FilterCCC.WantTypeSpecifiers = false;
513 FilterCCC.WantExpressionKeywords = false;
514 FilterCCC.WantRemainingKeywords = false;
515 FilterCCC.WantCXXNamedCasts = true;
516 if (TypoCorrection Corrected =
517 CorrectTypo(Found.getLookupNameInfo(), Found.getLookupKind(), S,
518 &SS, FilterCCC, CTK_ErrorRecovery, LookupCtx)) {
519 if (auto *ND = Corrected.getFoundDecl())
520 Found.addDecl(ND);
522 if (Found.isAmbiguous()) {
523 Found.clear();
524 } else if (!Found.empty()) {
525 Found.setLookupName(Corrected.getCorrection());
526 if (LookupCtx) {
527 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
528 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
529 Name.getAsString() == CorrectedStr;
530 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
531 << Name << LookupCtx << DroppedSpecifier
532 << SS.getRange());
533 } else {
534 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
535 }
536 }
537 }
538 }
539
540 NamedDecl *ExampleLookupResult =
541 Found.empty() ? nullptr : Found.getRepresentativeDecl();
542 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
543 if (Found.empty()) {
544 if (IsDependent) {
545 Found.setNotFoundInCurrentInstantiation();
546 return false;
547 }
548
549 // If a 'template' keyword was used, a lookup that finds only non-template
550 // names is an error.
551 if (ExampleLookupResult && RequiredTemplate) {
552 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
553 << Found.getLookupName() << SS.getRange()
554 << RequiredTemplate.hasTemplateKeyword()
555 << RequiredTemplate.getTemplateKeywordLoc();
556 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
557 diag::note_template_kw_refers_to_non_template)
558 << Found.getLookupName();
559 return true;
560 }
561
562 return false;
563 }
564
565 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
567 // C++03 [basic.lookup.classref]p1:
568 // [...] If the lookup in the class of the object expression finds a
569 // template, the name is also looked up in the context of the entire
570 // postfix-expression and [...]
571 //
572 // Note: C++11 does not perform this second lookup.
573 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
575 FoundOuter.setTemplateNameLookup(true);
576 LookupName(FoundOuter, S);
577 // FIXME: We silently accept an ambiguous lookup here, in violation of
578 // [basic.lookup]/1.
579 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
580
581 NamedDecl *OuterTemplate;
582 if (FoundOuter.empty()) {
583 // - if the name is not found, the name found in the class of the
584 // object expression is used, otherwise
585 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
586 !(OuterTemplate =
587 getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
588 // - if the name is found in the context of the entire
589 // postfix-expression and does not name a class template, the name
590 // found in the class of the object expression is used, otherwise
591 FoundOuter.clear();
592 } else if (!Found.isSuppressingAmbiguousDiagnostics()) {
593 // - if the name found is a class template, it must refer to the same
594 // entity as the one found in the class of the object expression,
595 // otherwise the program is ill-formed.
596 if (!Found.isSingleResult() ||
597 getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
598 OuterTemplate->getCanonicalDecl()) {
599 Diag(Found.getNameLoc(),
600 diag::ext_nested_name_member_ref_lookup_ambiguous)
601 << Found.getLookupName()
602 << ObjectType;
603 Diag(Found.getRepresentativeDecl()->getLocation(),
604 diag::note_ambig_member_ref_object_type)
605 << ObjectType;
606 Diag(FoundOuter.getFoundDecl()->getLocation(),
607 diag::note_ambig_member_ref_scope);
608
609 // Recover by taking the template that we found in the object
610 // expression's type.
611 }
612 }
613 }
614
615 return false;
616}
617
621 if (TemplateName.isInvalid())
622 return;
623
624 DeclarationNameInfo NameInfo;
625 CXXScopeSpec SS;
626 LookupNameKind LookupKind;
627
628 DeclContext *LookupCtx = nullptr;
629 NamedDecl *Found = nullptr;
630 bool MissingTemplateKeyword = false;
631
632 // Figure out what name we looked up.
633 if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
634 NameInfo = DRE->getNameInfo();
635 SS.Adopt(DRE->getQualifierLoc());
636 LookupKind = LookupOrdinaryName;
637 Found = DRE->getFoundDecl();
638 } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
639 NameInfo = ME->getMemberNameInfo();
640 SS.Adopt(ME->getQualifierLoc());
641 LookupKind = LookupMemberName;
642 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
643 Found = ME->getMemberDecl();
644 } else if (auto *DSDRE =
645 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
646 NameInfo = DSDRE->getNameInfo();
647 SS.Adopt(DSDRE->getQualifierLoc());
648 MissingTemplateKeyword = true;
649 } else if (auto *DSME =
650 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
651 NameInfo = DSME->getMemberNameInfo();
652 SS.Adopt(DSME->getQualifierLoc());
653 MissingTemplateKeyword = true;
654 } else {
655 llvm_unreachable("unexpected kind of potential template name");
656 }
657
658 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
659 // was missing.
660 if (MissingTemplateKeyword) {
661 Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
662 << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater);
663 return;
664 }
665
666 // Try to correct the name by looking for templates and C++ named casts.
667 struct TemplateCandidateFilter : CorrectionCandidateCallback {
668 Sema &S;
669 TemplateCandidateFilter(Sema &S) : S(S) {
670 WantTypeSpecifiers = false;
671 WantExpressionKeywords = false;
672 WantRemainingKeywords = false;
673 WantCXXNamedCasts = true;
674 };
675 bool ValidateCandidate(const TypoCorrection &Candidate) override {
676 if (auto *ND = Candidate.getCorrectionDecl())
677 return S.getAsTemplateNameDecl(ND);
678 return Candidate.isKeyword();
679 }
680
681 std::unique_ptr<CorrectionCandidateCallback> clone() override {
682 return std::make_unique<TemplateCandidateFilter>(*this);
683 }
684 };
685
686 DeclarationName Name = NameInfo.getName();
687 TemplateCandidateFilter CCC(*this);
688 if (TypoCorrection Corrected = CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
689 CTK_ErrorRecovery, LookupCtx)) {
690 auto *ND = Corrected.getFoundDecl();
691 if (ND)
692 ND = getAsTemplateNameDecl(ND);
693 if (ND || Corrected.isKeyword()) {
694 if (LookupCtx) {
695 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
696 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
697 Name.getAsString() == CorrectedStr;
698 diagnoseTypo(Corrected,
699 PDiag(diag::err_non_template_in_member_template_id_suggest)
700 << Name << LookupCtx << DroppedSpecifier
701 << SS.getRange(), false);
702 } else {
703 diagnoseTypo(Corrected,
704 PDiag(diag::err_non_template_in_template_id_suggest)
705 << Name, false);
706 }
707 if (Found)
708 Diag(Found->getLocation(),
709 diag::note_non_template_in_template_id_found);
710 return;
711 }
712 }
713
714 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
715 << Name << SourceRange(Less, Greater);
716 if (Found)
717 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
718}
719
722 SourceLocation TemplateKWLoc,
723 const DeclarationNameInfo &NameInfo,
724 bool isAddressOfOperand,
725 const TemplateArgumentListInfo *TemplateArgs) {
726 if (SS.isEmpty()) {
727 // FIXME: This codepath is only used by dependent unqualified names
728 // (e.g. a dependent conversion-function-id, or operator= once we support
729 // it). It doesn't quite do the right thing, and it will silently fail if
730 // getCurrentThisType() returns null.
731 QualType ThisType = getCurrentThisType();
732 if (ThisType.isNull())
733 return ExprError();
734
736 Context, /*Base=*/nullptr, ThisType,
737 /*IsArrow=*/!Context.getLangOpts().HLSL,
738 /*OperatorLoc=*/SourceLocation(),
739 /*QualifierLoc=*/NestedNameSpecifierLoc(), TemplateKWLoc,
740 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
741 }
742 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
743}
744
747 SourceLocation TemplateKWLoc,
748 const DeclarationNameInfo &NameInfo,
749 const TemplateArgumentListInfo *TemplateArgs) {
750 // DependentScopeDeclRefExpr::Create requires a valid NestedNameSpecifierLoc
751 if (!SS.isValid())
752 return CreateRecoveryExpr(
753 SS.getBeginLoc(),
754 TemplateArgs ? TemplateArgs->getRAngleLoc() : NameInfo.getEndLoc(), {});
755
757 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
758 TemplateArgs);
759}
760
762 NamedDecl *Instantiation,
763 bool InstantiatedFromMember,
764 const NamedDecl *Pattern,
765 const NamedDecl *PatternDef,
767 bool Complain /*= true*/) {
768 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
769 isa<VarDecl>(Instantiation));
770
771 bool IsEntityBeingDefined = false;
772 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
773 IsEntityBeingDefined = TD->isBeingDefined();
774
775 if (PatternDef && !IsEntityBeingDefined) {
776 NamedDecl *SuggestedDef = nullptr;
777 if (!hasReachableDefinition(const_cast<NamedDecl *>(PatternDef),
778 &SuggestedDef,
779 /*OnlyNeedComplete*/ false)) {
780 // If we're allowed to diagnose this and recover, do so.
781 bool Recover = Complain && !isSFINAEContext();
782 if (Complain)
783 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
785 return !Recover;
786 }
787 return false;
788 }
789
790 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
791 return true;
792
793 QualType InstantiationTy;
794 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
795 InstantiationTy = Context.getTypeDeclType(TD);
796 if (PatternDef) {
797 Diag(PointOfInstantiation,
798 diag::err_template_instantiate_within_definition)
799 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
800 << InstantiationTy;
801 // Not much point in noting the template declaration here, since
802 // we're lexically inside it.
803 Instantiation->setInvalidDecl();
804 } else if (InstantiatedFromMember) {
805 if (isa<FunctionDecl>(Instantiation)) {
806 Diag(PointOfInstantiation,
807 diag::err_explicit_instantiation_undefined_member)
808 << /*member function*/ 1 << Instantiation->getDeclName()
809 << Instantiation->getDeclContext();
810 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
811 } else {
812 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
813 Diag(PointOfInstantiation,
814 diag::err_implicit_instantiate_member_undefined)
815 << InstantiationTy;
816 Diag(Pattern->getLocation(), diag::note_member_declared_at);
817 }
818 } else {
819 if (isa<FunctionDecl>(Instantiation)) {
820 Diag(PointOfInstantiation,
821 diag::err_explicit_instantiation_undefined_func_template)
822 << Pattern;
823 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
824 } else if (isa<TagDecl>(Instantiation)) {
825 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
826 << (TSK != TSK_ImplicitInstantiation)
827 << InstantiationTy;
828 NoteTemplateLocation(*Pattern);
829 } else {
830 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
831 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
832 Diag(PointOfInstantiation,
833 diag::err_explicit_instantiation_undefined_var_template)
834 << Instantiation;
835 Instantiation->setInvalidDecl();
836 } else
837 Diag(PointOfInstantiation,
838 diag::err_explicit_instantiation_undefined_member)
839 << /*static data member*/ 2 << Instantiation->getDeclName()
840 << Instantiation->getDeclContext();
841 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
842 }
843 }
844
845 // In general, Instantiation isn't marked invalid to get more than one
846 // error for multiple undefined instantiations. But the code that does
847 // explicit declaration -> explicit definition conversion can't handle
848 // invalid declarations, so mark as invalid in that case.
850 Instantiation->setInvalidDecl();
851 return true;
852}
853
855 bool SupportedForCompatibility) {
856 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
857
858 // C++23 [temp.local]p6:
859 // The name of a template-parameter shall not be bound to any following.
860 // declaration whose locus is contained by the scope to which the
861 // template-parameter belongs.
862 //
863 // When MSVC compatibility is enabled, the diagnostic is always a warning
864 // by default. Otherwise, it an error unless SupportedForCompatibility is
865 // true, in which case it is a default-to-error warning.
866 unsigned DiagId =
867 getLangOpts().MSVCCompat
868 ? diag::ext_template_param_shadow
869 : (SupportedForCompatibility ? diag::ext_compat_template_param_shadow
870 : diag::err_template_param_shadow);
871 const auto *ND = cast<NamedDecl>(PrevDecl);
872 Diag(Loc, DiagId) << ND->getDeclName();
874}
875
877 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
878 D = Temp->getTemplatedDecl();
879 return Temp;
880 }
881 return nullptr;
882}
883
885 SourceLocation EllipsisLoc) const {
886 assert(Kind == Template &&
887 "Only template template arguments can be pack expansions here");
888 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
889 "Template template argument pack expansion without packs");
891 Result.EllipsisLoc = EllipsisLoc;
892 return Result;
893}
894
896 const ParsedTemplateArgument &Arg) {
897
898 switch (Arg.getKind()) {
900 TypeSourceInfo *DI;
901 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
902 if (!DI)
903 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
905 }
906
908 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
910 }
911
913 TemplateName Template = Arg.getAsTemplate().get();
914 TemplateArgument TArg;
915 if (Arg.getEllipsisLoc().isValid())
916 TArg = TemplateArgument(Template, std::optional<unsigned int>());
917 else
918 TArg = Template;
919 return TemplateArgumentLoc(
920 SemaRef.Context, TArg,
922 Arg.getLocation(), Arg.getEllipsisLoc());
923 }
924 }
925
926 llvm_unreachable("Unhandled parsed template argument");
927}
928
930 TemplateArgumentListInfo &TemplateArgs) {
931 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
932 TemplateArgs.addArgument(translateTemplateArgument(*this,
933 TemplateArgsIn[I]));
934}
935
938 const IdentifierInfo *Name) {
939 NamedDecl *PrevDecl =
941 RedeclarationKind::ForVisibleRedeclaration);
942 if (PrevDecl && PrevDecl->isTemplateParameter())
943 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
944}
945
947 TypeSourceInfo *TInfo;
949 if (T.isNull())
950 return ParsedTemplateArgument();
951 assert(TInfo && "template argument with no location");
952
953 // If we might have formed a deduced template specialization type, convert
954 // it to a template template argument.
955 if (getLangOpts().CPlusPlus17) {
956 TypeLoc TL = TInfo->getTypeLoc();
957 SourceLocation EllipsisLoc;
958 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
959 EllipsisLoc = PET.getEllipsisLoc();
960 TL = PET.getPatternLoc();
961 }
962
963 CXXScopeSpec SS;
964 if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
965 SS.Adopt(ET.getQualifierLoc());
966 TL = ET.getNamedTypeLoc();
967 }
968
969 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
970 TemplateName Name = DTST.getTypePtr()->getTemplateName();
972 DTST.getTemplateNameLoc());
973 if (EllipsisLoc.isValid())
974 Result = Result.getTemplatePackExpansion(EllipsisLoc);
975 return Result;
976 }
977 }
978
979 // This is a normal type template argument. Note, if the type template
980 // argument is an injected-class-name for a template, it has a dual nature
981 // and can be used as either a type or a template. We handle that in
982 // convertTypeTemplateArgumentToTemplate.
985 TInfo->getTypeLoc().getBeginLoc());
986}
987
989 SourceLocation EllipsisLoc,
990 SourceLocation KeyLoc,
991 IdentifierInfo *ParamName,
992 SourceLocation ParamNameLoc,
993 unsigned Depth, unsigned Position,
994 SourceLocation EqualLoc,
995 ParsedType DefaultArg,
996 bool HasTypeConstraint) {
997 assert(S->isTemplateParamScope() &&
998 "Template type parameter not in template parameter scope!");
999
1000 bool IsParameterPack = EllipsisLoc.isValid();
1003 KeyLoc, ParamNameLoc, Depth, Position,
1004 ParamName, Typename, IsParameterPack,
1005 HasTypeConstraint);
1006 Param->setAccess(AS_public);
1007
1008 if (Param->isParameterPack())
1009 if (auto *CSI = getEnclosingLambdaOrBlock())
1010 CSI->LocalPacks.push_back(Param);
1011
1012 if (ParamName) {
1013 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1014
1015 // Add the template parameter into the current scope.
1016 S->AddDecl(Param);
1017 IdResolver.AddDecl(Param);
1018 }
1019
1020 // C++0x [temp.param]p9:
1021 // A default template-argument may be specified for any kind of
1022 // template-parameter that is not a template parameter pack.
1023 if (DefaultArg && IsParameterPack) {
1024 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1025 DefaultArg = nullptr;
1026 }
1027
1028 // Handle the default argument, if provided.
1029 if (DefaultArg) {
1030 TypeSourceInfo *DefaultTInfo;
1031 GetTypeFromParser(DefaultArg, &DefaultTInfo);
1032
1033 assert(DefaultTInfo && "expected source information for type");
1034
1035 // Check for unexpanded parameter packs.
1036 if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
1038 return Param;
1039
1040 // Check the template argument itself.
1041 if (CheckTemplateArgument(DefaultTInfo)) {
1042 Param->setInvalidDecl();
1043 return Param;
1044 }
1045
1046 Param->setDefaultArgument(
1047 Context, TemplateArgumentLoc(DefaultTInfo->getType(), DefaultTInfo));
1048 }
1049
1050 return Param;
1051}
1052
1053/// Convert the parser's template argument list representation into our form.
1056 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1057 TemplateId.RAngleLoc);
1058 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1059 TemplateId.NumArgs);
1060 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
1061 return TemplateArgs;
1062}
1063
1065
1066 TemplateName TN = TypeConstr->Template.get();
1067 ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl());
1068
1069 // C++2a [temp.param]p4:
1070 // [...] The concept designated by a type-constraint shall be a type
1071 // concept ([temp.concept]).
1072 if (!CD->isTypeConcept()) {
1073 Diag(TypeConstr->TemplateNameLoc,
1074 diag::err_type_constraint_non_type_concept);
1075 return true;
1076 }
1077
1078 if (CheckConceptUseInDefinition(CD, TypeConstr->TemplateNameLoc))
1079 return true;
1080
1081 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1082
1083 if (!WereArgsSpecified &&
1085 Diag(TypeConstr->TemplateNameLoc,
1086 diag::err_type_constraint_missing_arguments)
1087 << CD;
1088 return true;
1089 }
1090 return false;
1091}
1092
1094 TemplateIdAnnotation *TypeConstr,
1095 TemplateTypeParmDecl *ConstrainedParameter,
1096 SourceLocation EllipsisLoc) {
1097 return BuildTypeConstraint(SS, TypeConstr, ConstrainedParameter, EllipsisLoc,
1098 false);
1099}
1100
1102 TemplateIdAnnotation *TypeConstr,
1103 TemplateTypeParmDecl *ConstrainedParameter,
1104 SourceLocation EllipsisLoc,
1105 bool AllowUnexpandedPack) {
1106
1107 if (CheckTypeConstraint(TypeConstr))
1108 return true;
1109
1110 TemplateName TN = TypeConstr->Template.get();
1111 ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl());
1113
1114 DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1115 TypeConstr->TemplateNameLoc);
1116
1117 TemplateArgumentListInfo TemplateArgs;
1118 if (TypeConstr->LAngleLoc.isValid()) {
1119 TemplateArgs =
1120 makeTemplateArgumentListInfo(*this, *TypeConstr);
1121
1122 if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1123 for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1125 return true;
1126 }
1127 }
1128 }
1129 return AttachTypeConstraint(
1131 ConceptName, CD, /*FoundDecl=*/USD ? cast<NamedDecl>(USD) : CD,
1132 TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1133 ConstrainedParameter, Context.getTypeDeclType(ConstrainedParameter),
1134 EllipsisLoc);
1135}
1136
1137template <typename ArgumentLocAppender>
1140 ConceptDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc,
1141 SourceLocation RAngleLoc, QualType ConstrainedType,
1142 SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1143 SourceLocation EllipsisLoc) {
1144
1145 TemplateArgumentListInfo ConstraintArgs;
1146 ConstraintArgs.addArgument(
1148 /*NTTPType=*/QualType(), ParamNameLoc));
1149
1150 ConstraintArgs.setRAngleLoc(RAngleLoc);
1151 ConstraintArgs.setLAngleLoc(LAngleLoc);
1152 Appender(ConstraintArgs);
1153
1154 // C++2a [temp.param]p4:
1155 // [...] This constraint-expression E is called the immediately-declared
1156 // constraint of T. [...]
1157 CXXScopeSpec SS;
1158 SS.Adopt(NS);
1159 ExprResult ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1160 SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
1161 /*FoundDecl=*/FoundDecl ? FoundDecl : NamedConcept, NamedConcept,
1162 &ConstraintArgs);
1163 if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1164 return ImmediatelyDeclaredConstraint;
1165
1166 // C++2a [temp.param]p4:
1167 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1168 //
1169 // We have the following case:
1170 //
1171 // template<typename T> concept C1 = true;
1172 // template<C1... T> struct s1;
1173 //
1174 // The constraint: (C1<T> && ...)
1175 //
1176 // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1177 // any unqualified lookups for 'operator&&' here.
1178 return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
1179 /*LParenLoc=*/SourceLocation(),
1180 ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1181 EllipsisLoc, /*RHS=*/nullptr,
1182 /*RParenLoc=*/SourceLocation(),
1183 /*NumExpansions=*/std::nullopt);
1184}
1185
1187 DeclarationNameInfo NameInfo,
1188 ConceptDecl *NamedConcept, NamedDecl *FoundDecl,
1189 const TemplateArgumentListInfo *TemplateArgs,
1190 TemplateTypeParmDecl *ConstrainedParameter,
1191 QualType ConstrainedType,
1192 SourceLocation EllipsisLoc) {
1193 // C++2a [temp.param]p4:
1194 // [...] If Q is of the form C<A1, ..., An>, then let E' be
1195 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1196 const ASTTemplateArgumentListInfo *ArgsAsWritten =
1198 *TemplateArgs) : nullptr;
1199
1200 QualType ParamAsArgument = ConstrainedType;
1201
1202 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1203 *this, NS, NameInfo, NamedConcept, FoundDecl,
1204 TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1205 TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1206 ParamAsArgument, ConstrainedParameter->getLocation(),
1207 [&](TemplateArgumentListInfo &ConstraintArgs) {
1208 if (TemplateArgs)
1209 for (const auto &ArgLoc : TemplateArgs->arguments())
1210 ConstraintArgs.addArgument(ArgLoc);
1211 },
1212 EllipsisLoc);
1213 if (ImmediatelyDeclaredConstraint.isInvalid())
1214 return true;
1215
1216 auto *CL = ConceptReference::Create(Context, /*NNS=*/NS,
1217 /*TemplateKWLoc=*/SourceLocation{},
1218 /*ConceptNameInfo=*/NameInfo,
1219 /*FoundDecl=*/FoundDecl,
1220 /*NamedConcept=*/NamedConcept,
1221 /*ArgsWritten=*/ArgsAsWritten);
1222 ConstrainedParameter->setTypeConstraint(CL,
1223 ImmediatelyDeclaredConstraint.get());
1224 return false;
1225}
1226
1228 NonTypeTemplateParmDecl *NewConstrainedParm,
1229 NonTypeTemplateParmDecl *OrigConstrainedParm,
1230 SourceLocation EllipsisLoc) {
1231 if (NewConstrainedParm->getType() != TL.getType() ||
1233 Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1234 diag::err_unsupported_placeholder_constraint)
1235 << NewConstrainedParm->getTypeSourceInfo()
1236 ->getTypeLoc()
1237 .getSourceRange();
1238 return true;
1239 }
1240 // FIXME: Concepts: This should be the type of the placeholder, but this is
1241 // unclear in the wording right now.
1242 DeclRefExpr *Ref =
1243 BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(),
1244 VK_PRValue, OrigConstrainedParm->getLocation());
1245 if (!Ref)
1246 return true;
1247 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1249 TL.getNamedConcept(), /*FoundDecl=*/TL.getFoundDecl(), TL.getLAngleLoc(),
1251 OrigConstrainedParm->getLocation(),
1252 [&](TemplateArgumentListInfo &ConstraintArgs) {
1253 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1254 ConstraintArgs.addArgument(TL.getArgLoc(I));
1255 },
1256 EllipsisLoc);
1257 if (ImmediatelyDeclaredConstraint.isInvalid() ||
1258 !ImmediatelyDeclaredConstraint.isUsable())
1259 return true;
1260
1261 NewConstrainedParm->setPlaceholderTypeConstraint(
1262 ImmediatelyDeclaredConstraint.get());
1263 return false;
1264}
1265
1268 if (TSI->getType()->isUndeducedType()) {
1269 // C++17 [temp.dep.expr]p3:
1270 // An id-expression is type-dependent if it contains
1271 // - an identifier associated by name lookup with a non-type
1272 // template-parameter declared with a type that contains a
1273 // placeholder type (7.1.7.4),
1275 }
1276
1278}
1279
1281 if (T->isDependentType())
1282 return false;
1283
1284 if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))
1285 return true;
1286
1287 if (T->isStructuralType())
1288 return false;
1289
1290 // Structural types are required to be object types or lvalue references.
1291 if (T->isRValueReferenceType()) {
1292 Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;
1293 return true;
1294 }
1295
1296 // Don't mention structural types in our diagnostic prior to C++20. Also,
1297 // there's not much more we can say about non-scalar non-class types --
1298 // because we can't see functions or arrays here, those can only be language
1299 // extensions.
1300 if (!getLangOpts().CPlusPlus20 ||
1301 (!T->isScalarType() && !T->isRecordType())) {
1302 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1303 return true;
1304 }
1305
1306 // Structural types are required to be literal types.
1307 if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))
1308 return true;
1309
1310 Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;
1311
1312 // Drill down into the reason why the class is non-structural.
1313 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1314 // All members are required to be public and non-mutable, and can't be of
1315 // rvalue reference type. Check these conditions first to prefer a "local"
1316 // reason over a more distant one.
1317 for (const FieldDecl *FD : RD->fields()) {
1318 if (FD->getAccess() != AS_public) {
1319 Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;
1320 return true;
1321 }
1322 if (FD->isMutable()) {
1323 Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;
1324 return true;
1325 }
1326 if (FD->getType()->isRValueReferenceType()) {
1327 Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)
1328 << T;
1329 return true;
1330 }
1331 }
1332
1333 // All bases are required to be public.
1334 for (const auto &BaseSpec : RD->bases()) {
1335 if (BaseSpec.getAccessSpecifier() != AS_public) {
1336 Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)
1337 << T << 1;
1338 return true;
1339 }
1340 }
1341
1342 // All subobjects are required to be of structural types.
1343 SourceLocation SubLoc;
1344 QualType SubType;
1345 int Kind = -1;
1346
1347 for (const FieldDecl *FD : RD->fields()) {
1348 QualType T = Context.getBaseElementType(FD->getType());
1349 if (!T->isStructuralType()) {
1350 SubLoc = FD->getLocation();
1351 SubType = T;
1352 Kind = 0;
1353 break;
1354 }
1355 }
1356
1357 if (Kind == -1) {
1358 for (const auto &BaseSpec : RD->bases()) {
1359 QualType T = BaseSpec.getType();
1360 if (!T->isStructuralType()) {
1361 SubLoc = BaseSpec.getBaseTypeLoc();
1362 SubType = T;
1363 Kind = 1;
1364 break;
1365 }
1366 }
1367 }
1368
1369 assert(Kind != -1 && "couldn't find reason why type is not structural");
1370 Diag(SubLoc, diag::note_not_structural_subobject)
1371 << T << Kind << SubType;
1372 T = SubType;
1373 RD = T->getAsCXXRecordDecl();
1374 }
1375
1376 return true;
1377}
1378
1381 // We don't allow variably-modified types as the type of non-type template
1382 // parameters.
1383 if (T->isVariablyModifiedType()) {
1384 Diag(Loc, diag::err_variably_modified_nontype_template_param)
1385 << T;
1386 return QualType();
1387 }
1388
1389 // C++ [temp.param]p4:
1390 //
1391 // A non-type template-parameter shall have one of the following
1392 // (optionally cv-qualified) types:
1393 //
1394 // -- integral or enumeration type,
1396 // -- pointer to object or pointer to function,
1397 T->isPointerType() ||
1398 // -- lvalue reference to object or lvalue reference to function,
1400 // -- pointer to member,
1402 // -- std::nullptr_t, or
1403 T->isNullPtrType() ||
1404 // -- a type that contains a placeholder type.
1405 T->isUndeducedType()) {
1406 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1407 // are ignored when determining its type.
1408 return T.getUnqualifiedType();
1409 }
1410
1411 // C++ [temp.param]p8:
1412 //
1413 // A non-type template-parameter of type "array of T" or
1414 // "function returning T" is adjusted to be of type "pointer to
1415 // T" or "pointer to function returning T", respectively.
1416 if (T->isArrayType() || T->isFunctionType())
1417 return Context.getDecayedType(T);
1418
1419 // If T is a dependent type, we can't do the check now, so we
1420 // assume that it is well-formed. Note that stripping off the
1421 // qualifiers here is not really correct if T turns out to be
1422 // an array type, but we'll recompute the type everywhere it's
1423 // used during instantiation, so that should be OK. (Using the
1424 // qualified type is equally wrong.)
1425 if (T->isDependentType())
1426 return T.getUnqualifiedType();
1427
1428 // C++20 [temp.param]p6:
1429 // -- a structural type
1431 return QualType();
1432
1433 if (!getLangOpts().CPlusPlus20) {
1434 // FIXME: Consider allowing structural types as an extension in C++17. (In
1435 // earlier language modes, the template argument evaluation rules are too
1436 // inflexible.)
1437 Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;
1438 return QualType();
1439 }
1440
1441 Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1442 return T.getUnqualifiedType();
1443}
1444
1446 unsigned Depth,
1447 unsigned Position,
1448 SourceLocation EqualLoc,
1449 Expr *Default) {
1451
1452 // Check that we have valid decl-specifiers specified.
1453 auto CheckValidDeclSpecifiers = [this, &D] {
1454 // C++ [temp.param]
1455 // p1
1456 // template-parameter:
1457 // ...
1458 // parameter-declaration
1459 // p2
1460 // ... A storage class shall not be specified in a template-parameter
1461 // declaration.
1462 // [dcl.typedef]p1:
1463 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1464 // of a parameter-declaration
1465 const DeclSpec &DS = D.getDeclSpec();
1466 auto EmitDiag = [this](SourceLocation Loc) {
1467 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1469 };
1471 EmitDiag(DS.getStorageClassSpecLoc());
1472
1474 EmitDiag(DS.getThreadStorageClassSpecLoc());
1475
1476 // [dcl.inline]p1:
1477 // The inline specifier can be applied only to the declaration or
1478 // definition of a variable or function.
1479
1480 if (DS.isInlineSpecified())
1481 EmitDiag(DS.getInlineSpecLoc());
1482
1483 // [dcl.constexpr]p1:
1484 // The constexpr specifier shall be applied only to the definition of a
1485 // variable or variable template or the declaration of a function or
1486 // function template.
1487
1488 if (DS.hasConstexprSpecifier())
1489 EmitDiag(DS.getConstexprSpecLoc());
1490
1491 // [dcl.fct.spec]p1:
1492 // Function-specifiers can be used only in function declarations.
1493
1494 if (DS.isVirtualSpecified())
1495 EmitDiag(DS.getVirtualSpecLoc());
1496
1497 if (DS.hasExplicitSpecifier())
1498 EmitDiag(DS.getExplicitSpecLoc());
1499
1500 if (DS.isNoreturnSpecified())
1501 EmitDiag(DS.getNoreturnSpecLoc());
1502 };
1503
1504 CheckValidDeclSpecifiers();
1505
1506 if (const auto *T = TInfo->getType()->getContainedDeducedType())
1507 if (isa<AutoType>(T))
1508 Diag(D.getIdentifierLoc(),
1509 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1510 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1511
1512 assert(S->isTemplateParamScope() &&
1513 "Non-type template parameter not in template parameter scope!");
1514 bool Invalid = false;
1515
1516 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
1517 if (T.isNull()) {
1518 T = Context.IntTy; // Recover with an 'int' type.
1519 Invalid = true;
1520 }
1521
1523
1524 const IdentifierInfo *ParamName = D.getIdentifier();
1525 bool IsParameterPack = D.hasEllipsis();
1528 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1529 TInfo);
1530 Param->setAccess(AS_public);
1531
1533 if (TL.isConstrained())
1534 if (AttachTypeConstraint(TL, Param, Param, D.getEllipsisLoc()))
1535 Invalid = true;
1536
1537 if (Invalid)
1538 Param->setInvalidDecl();
1539
1540 if (Param->isParameterPack())
1541 if (auto *CSI = getEnclosingLambdaOrBlock())
1542 CSI->LocalPacks.push_back(Param);
1543
1544 if (ParamName) {
1545 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
1546 ParamName);
1547
1548 // Add the template parameter into the current scope.
1549 S->AddDecl(Param);
1550 IdResolver.AddDecl(Param);
1551 }
1552
1553 // C++0x [temp.param]p9:
1554 // A default template-argument may be specified for any kind of
1555 // template-parameter that is not a template parameter pack.
1556 if (Default && IsParameterPack) {
1557 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1558 Default = nullptr;
1559 }
1560
1561 // Check the well-formedness of the default template argument, if provided.
1562 if (Default) {
1563 // Check for unexpanded parameter packs.
1565 return Param;
1566
1567 Param->setDefaultArgument(
1569 QualType(), SourceLocation()));
1570 }
1571
1572 return Param;
1573}
1574
1576 Scope *S, SourceLocation TmpLoc, TemplateParameterList *Params,
1577 bool Typename, SourceLocation EllipsisLoc, IdentifierInfo *Name,
1578 SourceLocation NameLoc, unsigned Depth, unsigned Position,
1580 assert(S->isTemplateParamScope() &&
1581 "Template template parameter not in template parameter scope!");
1582
1583 // Construct the parameter object.
1584 bool IsParameterPack = EllipsisLoc.isValid();
1587 NameLoc.isInvalid() ? TmpLoc : NameLoc, Depth, Position, IsParameterPack,
1588 Name, Typename, Params);
1589 Param->setAccess(AS_public);
1590
1591 if (Param->isParameterPack())
1592 if (auto *LSI = getEnclosingLambdaOrBlock())
1593 LSI->LocalPacks.push_back(Param);
1594
1595 // If the template template parameter has a name, then link the identifier
1596 // into the scope and lookup mechanisms.
1597 if (Name) {
1598 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1599
1600 S->AddDecl(Param);
1601 IdResolver.AddDecl(Param);
1602 }
1603
1604 if (Params->size() == 0) {
1605 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1606 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1607 Param->setInvalidDecl();
1608 }
1609
1610 // C++0x [temp.param]p9:
1611 // A default template-argument may be specified for any kind of
1612 // template-parameter that is not a template parameter pack.
1613 if (IsParameterPack && !Default.isInvalid()) {
1614 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1616 }
1617
1618 if (!Default.isInvalid()) {
1619 // Check only that we have a template template argument. We don't want to
1620 // try to check well-formedness now, because our template template parameter
1621 // might have dependent types in its template parameters, which we wouldn't
1622 // be able to match now.
1623 //
1624 // If none of the template template parameter's template arguments mention
1625 // other template parameters, we could actually perform more checking here.
1626 // However, it isn't worth doing.
1628 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1629 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1630 << DefaultArg.getSourceRange();
1631 return Param;
1632 }
1633
1634 // Check for unexpanded parameter packs.
1636 DefaultArg.getArgument().getAsTemplate(),
1638 return Param;
1639
1640 Param->setDefaultArgument(Context, DefaultArg);
1641 }
1642
1643 return Param;
1644}
1645
1646namespace {
1647class ConstraintRefersToContainingTemplateChecker
1648 : public TreeTransform<ConstraintRefersToContainingTemplateChecker> {
1649 bool Result = false;
1650 const FunctionDecl *Friend = nullptr;
1651 unsigned TemplateDepth = 0;
1652
1653 // Check a record-decl that we've seen to see if it is a lexical parent of the
1654 // Friend, likely because it was referred to without its template arguments.
1655 void CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1656 CheckingRD = CheckingRD->getMostRecentDecl();
1657 if (!CheckingRD->isTemplated())
1658 return;
1659
1660 for (const DeclContext *DC = Friend->getLexicalDeclContext();
1661 DC && !DC->isFileContext(); DC = DC->getParent())
1662 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
1663 if (CheckingRD == RD->getMostRecentDecl())
1664 Result = true;
1665 }
1666
1667 void CheckNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
1668 if (D->getDepth() < TemplateDepth)
1669 Result = true;
1670
1671 // Necessary because the type of the NTTP might be what refers to the parent
1672 // constriant.
1673 TransformType(D->getType());
1674 }
1675
1676public:
1678
1679 ConstraintRefersToContainingTemplateChecker(Sema &SemaRef,
1680 const FunctionDecl *Friend,
1681 unsigned TemplateDepth)
1682 : inherited(SemaRef), Friend(Friend), TemplateDepth(TemplateDepth) {}
1683 bool getResult() const { return Result; }
1684
1685 // This should be the only template parm type that we have to deal with.
1686 // SubstTempalteTypeParmPack, SubstNonTypeTemplateParmPack, and
1687 // FunctionParmPackExpr are all partially substituted, which cannot happen
1688 // with concepts at this point in translation.
1689 using inherited::TransformTemplateTypeParmType;
1690 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1691 TemplateTypeParmTypeLoc TL, bool) {
1692 if (TL.getDecl()->getDepth() < TemplateDepth)
1693 Result = true;
1694 return inherited::TransformTemplateTypeParmType(
1695 TLB, TL,
1696 /*SuppressObjCLifetime=*/false);
1697 }
1698
1699 Decl *TransformDecl(SourceLocation Loc, Decl *D) {
1700 if (!D)
1701 return D;
1702 // FIXME : This is possibly an incomplete list, but it is unclear what other
1703 // Decl kinds could be used to refer to the template parameters. This is a
1704 // best guess so far based on examples currently available, but the
1705 // unreachable should catch future instances/cases.
1706 if (auto *TD = dyn_cast<TypedefNameDecl>(D))
1707 TransformType(TD->getUnderlyingType());
1708 else if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(D))
1709 CheckNonTypeTemplateParmDecl(NTTPD);
1710 else if (auto *VD = dyn_cast<ValueDecl>(D))
1711 TransformType(VD->getType());
1712 else if (auto *TD = dyn_cast<TemplateDecl>(D))
1713 TransformTemplateParameterList(TD->getTemplateParameters());
1714 else if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1715 CheckIfContainingRecord(RD);
1716 else if (isa<NamedDecl>(D)) {
1717 // No direct types to visit here I believe.
1718 } else
1719 llvm_unreachable("Don't know how to handle this declaration type yet");
1720 return D;
1721 }
1722};
1723} // namespace
1724
1726 const FunctionDecl *Friend, unsigned TemplateDepth,
1727 const Expr *Constraint) {
1728 assert(Friend->getFriendObjectKind() && "Only works on a friend");
1729 ConstraintRefersToContainingTemplateChecker Checker(*this, Friend,
1730 TemplateDepth);
1731 Checker.TransformExpr(const_cast<Expr *>(Constraint));
1732 return Checker.getResult();
1733}
1734
1737 SourceLocation ExportLoc,
1738 SourceLocation TemplateLoc,
1739 SourceLocation LAngleLoc,
1740 ArrayRef<NamedDecl *> Params,
1741 SourceLocation RAngleLoc,
1742 Expr *RequiresClause) {
1743 if (ExportLoc.isValid())
1744 Diag(ExportLoc, diag::warn_template_export_unsupported);
1745
1746 for (NamedDecl *P : Params)
1748
1750 Context, TemplateLoc, LAngleLoc,
1751 llvm::ArrayRef(Params.data(), Params.size()), RAngleLoc, RequiresClause);
1752}
1753
1755 const CXXScopeSpec &SS) {
1756 if (SS.isSet())
1757 T->setQualifierInfo(SS.getWithLocInContext(S.Context));
1758}
1759
1760// Returns the template parameter list with all default template argument
1761// information.
1763 // Make sure we get the template parameter list from the most
1764 // recent declaration, since that is the only one that is guaranteed to
1765 // have all the default template argument information.
1766 Decl *D = TD->getMostRecentDecl();
1767 // C++11 N3337 [temp.param]p12:
1768 // A default template argument shall not be specified in a friend class
1769 // template declaration.
1770 //
1771 // Skip past friend *declarations* because they are not supposed to contain
1772 // default template arguments. Moreover, these declarations may introduce
1773 // template parameters living in different template depths than the
1774 // corresponding template parameters in TD, causing unmatched constraint
1775 // substitution.
1776 //
1777 // FIXME: Diagnose such cases within a class template:
1778 // template <class T>
1779 // struct S {
1780 // template <class = void> friend struct C;
1781 // };
1782 // template struct S<int>;
1784 D->getPreviousDecl())
1785 D = D->getPreviousDecl();
1786 return cast<TemplateDecl>(D)->getTemplateParameters();
1787}
1788
1790 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1791 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1792 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1793 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1794 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1795 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1796 assert(TemplateParams && TemplateParams->size() > 0 &&
1797 "No template parameters");
1798 assert(TUK != TagUseKind::Reference &&
1799 "Can only declare or define class templates");
1800 bool Invalid = false;
1801
1802 // Check that we can declare a template here.
1803 if (CheckTemplateDeclScope(S, TemplateParams))
1804 return true;
1805
1807 assert(Kind != TagTypeKind::Enum &&
1808 "can't build template of enumerated type");
1809
1810 // There is no such thing as an unnamed class template.
1811 if (!Name) {
1812 Diag(KWLoc, diag::err_template_unnamed_class);
1813 return true;
1814 }
1815
1816 // Find any previous declaration with this name. For a friend with no
1817 // scope explicitly specified, we only look for tag declarations (per
1818 // C++11 [basic.lookup.elab]p2).
1819 DeclContext *SemanticContext;
1820 LookupResult Previous(*this, Name, NameLoc,
1821 (SS.isEmpty() && TUK == TagUseKind::Friend)
1825 if (SS.isNotEmpty() && !SS.isInvalid()) {
1826 SemanticContext = computeDeclContext(SS, true);
1827 if (!SemanticContext) {
1828 // FIXME: Horrible, horrible hack! We can't currently represent this
1829 // in the AST, and historically we have just ignored such friend
1830 // class templates, so don't complain here.
1831 Diag(NameLoc, TUK == TagUseKind::Friend
1832 ? diag::warn_template_qualified_friend_ignored
1833 : diag::err_template_qualified_declarator_no_match)
1834 << SS.getScopeRep() << SS.getRange();
1835 return TUK != TagUseKind::Friend;
1836 }
1837
1838 if (RequireCompleteDeclContext(SS, SemanticContext))
1839 return true;
1840
1841 // If we're adding a template to a dependent context, we may need to
1842 // rebuilding some of the types used within the template parameter list,
1843 // now that we know what the current instantiation is.
1844 if (SemanticContext->isDependentContext()) {
1845 ContextRAII SavedContext(*this, SemanticContext);
1847 Invalid = true;
1848 }
1849
1850 if (TUK != TagUseKind::Friend && TUK != TagUseKind::Reference)
1851 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc,
1852 /*TemplateId-*/ nullptr,
1853 /*IsMemberSpecialization*/ false);
1854
1855 LookupQualifiedName(Previous, SemanticContext);
1856 } else {
1857 SemanticContext = CurContext;
1858
1859 // C++14 [class.mem]p14:
1860 // If T is the name of a class, then each of the following shall have a
1861 // name different from T:
1862 // -- every member template of class T
1863 if (TUK != TagUseKind::Friend &&
1864 DiagnoseClassNameShadow(SemanticContext,
1865 DeclarationNameInfo(Name, NameLoc)))
1866 return true;
1867
1868 LookupName(Previous, S);
1869 }
1870
1871 if (Previous.isAmbiguous())
1872 return true;
1873
1874 // Let the template parameter scope enter the lookup chain of the current
1875 // class template. For example, given
1876 //
1877 // namespace ns {
1878 // template <class> bool Param = false;
1879 // template <class T> struct N;
1880 // }
1881 //
1882 // template <class Param> struct ns::N { void foo(Param); };
1883 //
1884 // When we reference Param inside the function parameter list, our name lookup
1885 // chain for it should be like:
1886 // FunctionScope foo
1887 // -> RecordScope N
1888 // -> TemplateParamScope (where we will find Param)
1889 // -> NamespaceScope ns
1890 //
1891 // See also CppLookupName().
1892 if (S->isTemplateParamScope())
1893 EnterTemplatedContext(S, SemanticContext);
1894
1895 NamedDecl *PrevDecl = nullptr;
1896 if (Previous.begin() != Previous.end())
1897 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1898
1899 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1900 // Maybe we will complain about the shadowed template parameter.
1901 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1902 // Just pretend that we didn't see the previous declaration.
1903 PrevDecl = nullptr;
1904 }
1905
1906 // If there is a previous declaration with the same name, check
1907 // whether this is a valid redeclaration.
1908 ClassTemplateDecl *PrevClassTemplate =
1909 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1910
1911 // We may have found the injected-class-name of a class template,
1912 // class template partial specialization, or class template specialization.
1913 // In these cases, grab the template that is being defined or specialized.
1914 if (!PrevClassTemplate && isa_and_nonnull<CXXRecordDecl>(PrevDecl) &&
1915 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1916 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1917 PrevClassTemplate
1918 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1919 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1920 PrevClassTemplate
1921 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1922 ->getSpecializedTemplate();
1923 }
1924 }
1925
1926 if (TUK == TagUseKind::Friend) {
1927 // C++ [namespace.memdef]p3:
1928 // [...] When looking for a prior declaration of a class or a function
1929 // declared as a friend, and when the name of the friend class or
1930 // function is neither a qualified name nor a template-id, scopes outside
1931 // the innermost enclosing namespace scope are not considered.
1932 if (!SS.isSet()) {
1933 DeclContext *OutermostContext = CurContext;
1934 while (!OutermostContext->isFileContext())
1935 OutermostContext = OutermostContext->getLookupParent();
1936
1937 if (PrevDecl &&
1938 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1939 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1940 SemanticContext = PrevDecl->getDeclContext();
1941 } else {
1942 // Declarations in outer scopes don't matter. However, the outermost
1943 // context we computed is the semantic context for our new
1944 // declaration.
1945 PrevDecl = PrevClassTemplate = nullptr;
1946 SemanticContext = OutermostContext;
1947
1948 // Check that the chosen semantic context doesn't already contain a
1949 // declaration of this name as a non-tag type.
1951 DeclContext *LookupContext = SemanticContext;
1952 while (LookupContext->isTransparentContext())
1953 LookupContext = LookupContext->getLookupParent();
1954 LookupQualifiedName(Previous, LookupContext);
1955
1956 if (Previous.isAmbiguous())
1957 return true;
1958
1959 if (Previous.begin() != Previous.end())
1960 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1961 }
1962 }
1963 } else if (PrevDecl && !isDeclInScope(Previous.getRepresentativeDecl(),
1964 SemanticContext, S, SS.isValid()))
1965 PrevDecl = PrevClassTemplate = nullptr;
1966
1967 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1968 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1969 if (SS.isEmpty() &&
1970 !(PrevClassTemplate &&
1971 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1972 SemanticContext->getRedeclContext()))) {
1973 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1974 Diag(Shadow->getTargetDecl()->getLocation(),
1975 diag::note_using_decl_target);
1976 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
1977 // Recover by ignoring the old declaration.
1978 PrevDecl = PrevClassTemplate = nullptr;
1979 }
1980 }
1981
1982 if (PrevClassTemplate) {
1983 // Ensure that the template parameter lists are compatible. Skip this check
1984 // for a friend in a dependent context: the template parameter list itself
1985 // could be dependent.
1986 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
1988 TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
1989 : CurContext,
1990 CurContext, KWLoc),
1991 TemplateParams, PrevClassTemplate,
1992 PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
1994 return true;
1995
1996 // C++ [temp.class]p4:
1997 // In a redeclaration, partial specialization, explicit
1998 // specialization or explicit instantiation of a class template,
1999 // the class-key shall agree in kind with the original class
2000 // template declaration (7.1.5.3).
2001 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
2003 PrevRecordDecl, Kind, TUK == TagUseKind::Definition, KWLoc, Name)) {
2004 Diag(KWLoc, diag::err_use_with_wrong_tag)
2005 << Name
2006 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
2007 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
2008 Kind = PrevRecordDecl->getTagKind();
2009 }
2010
2011 // Check for redefinition of this class template.
2012 if (TUK == TagUseKind::Definition) {
2013 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2014 // If we have a prior definition that is not visible, treat this as
2015 // simply making that previous definition visible.
2016 NamedDecl *Hidden = nullptr;
2017 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
2018 SkipBody->ShouldSkip = true;
2019 SkipBody->Previous = Def;
2020 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
2021 assert(Tmpl && "original definition of a class template is not a "
2022 "class template?");
2025 } else {
2026 Diag(NameLoc, diag::err_redefinition) << Name;
2027 Diag(Def->getLocation(), diag::note_previous_definition);
2028 // FIXME: Would it make sense to try to "forget" the previous
2029 // definition, as part of error recovery?
2030 return true;
2031 }
2032 }
2033 }
2034 } else if (PrevDecl) {
2035 // C++ [temp]p5:
2036 // A class template shall not have the same name as any other
2037 // template, class, function, object, enumeration, enumerator,
2038 // namespace, or type in the same scope (3.3), except as specified
2039 // in (14.5.4).
2040 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2041 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2042 return true;
2043 }
2044
2045 // Check the template parameter list of this declaration, possibly
2046 // merging in the template parameter list from the previous class
2047 // template declaration. Skip this check for a friend in a dependent
2048 // context, because the template parameter list might be dependent.
2049 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2051 TemplateParams,
2052 PrevClassTemplate ? GetTemplateParameterList(PrevClassTemplate)
2053 : nullptr,
2054 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2055 SemanticContext->isDependentContext())
2059 SkipBody))
2060 Invalid = true;
2061
2062 if (SS.isSet()) {
2063 // If the name of the template was qualified, we must be defining the
2064 // template out-of-line.
2065 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
2066 Diag(NameLoc, TUK == TagUseKind::Friend
2067 ? diag::err_friend_decl_does_not_match
2068 : diag::err_member_decl_does_not_match)
2069 << Name << SemanticContext << /*IsDefinition*/ true << SS.getRange();
2070 Invalid = true;
2071 }
2072 }
2073
2074 // If this is a templated friend in a dependent context we should not put it
2075 // on the redecl chain. In some cases, the templated friend can be the most
2076 // recent declaration tricking the template instantiator to make substitutions
2077 // there.
2078 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2079 bool ShouldAddRedecl =
2081
2082 CXXRecordDecl *NewClass =
2083 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
2084 PrevClassTemplate && ShouldAddRedecl ?
2085 PrevClassTemplate->getTemplatedDecl() : nullptr,
2086 /*DelayTypeCreation=*/true);
2087 SetNestedNameSpecifier(*this, NewClass, SS);
2088 if (NumOuterTemplateParamLists > 0)
2090 Context,
2091 llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2092
2093 // Add alignment attributes if necessary; these attributes are checked when
2094 // the ASTContext lays out the structure.
2095 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2098 }
2099
2100 ClassTemplateDecl *NewTemplate
2101 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
2102 DeclarationName(Name), TemplateParams,
2103 NewClass);
2104
2105 if (ShouldAddRedecl)
2106 NewTemplate->setPreviousDecl(PrevClassTemplate);
2107
2108 NewClass->setDescribedClassTemplate(NewTemplate);
2109
2110 if (ModulePrivateLoc.isValid())
2111 NewTemplate->setModulePrivate();
2112
2113 // Build the type for the class template declaration now.
2115 T = Context.getInjectedClassNameType(NewClass, T);
2116 assert(T->isDependentType() && "Class template type is not dependent?");
2117 (void)T;
2118
2119 // If we are providing an explicit specialization of a member that is a
2120 // class template, make a note of that.
2121 if (PrevClassTemplate &&
2122 PrevClassTemplate->getInstantiatedFromMemberTemplate())
2123 PrevClassTemplate->setMemberSpecialization();
2124
2125 // Set the access specifier.
2126 if (!Invalid && TUK != TagUseKind::Friend &&
2127 NewTemplate->getDeclContext()->isRecord())
2128 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
2129
2130 // Set the lexical context of these templates
2132 NewTemplate->setLexicalDeclContext(CurContext);
2133
2134 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
2135 NewClass->startDefinition();
2136
2137 ProcessDeclAttributeList(S, NewClass, Attr);
2138 ProcessAPINotes(NewClass);
2139
2140 if (PrevClassTemplate)
2141 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2142
2146
2147 if (TUK != TagUseKind::Friend) {
2148 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2149 Scope *Outer = S;
2150 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2151 Outer = Outer->getParent();
2152 PushOnScopeChains(NewTemplate, Outer);
2153 } else {
2154 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2155 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2156 NewClass->setAccess(PrevClassTemplate->getAccess());
2157 }
2158
2159 NewTemplate->setObjectOfFriendDecl();
2160
2161 // Friend templates are visible in fairly strange ways.
2163 DeclContext *DC = SemanticContext->getRedeclContext();
2164 DC->makeDeclVisibleInContext(NewTemplate);
2165 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2166 PushOnScopeChains(NewTemplate, EnclosingScope,
2167 /* AddToContext = */ false);
2168 }
2169
2171 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
2172 Friend->setAccess(AS_public);
2174 }
2175
2176 if (PrevClassTemplate)
2177 CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);
2178
2179 if (Invalid) {
2180 NewTemplate->setInvalidDecl();
2181 NewClass->setInvalidDecl();
2182 }
2183
2184 ActOnDocumentableDecl(NewTemplate);
2185
2186 if (SkipBody && SkipBody->ShouldSkip)
2187 return SkipBody->Previous;
2188
2189 return NewTemplate;
2190}
2191
2192/// Diagnose the presence of a default template argument on a
2193/// template parameter, which is ill-formed in certain contexts.
2194///
2195/// \returns true if the default template argument should be dropped.
2198 SourceLocation ParamLoc,
2199 SourceRange DefArgRange) {
2200 switch (TPC) {
2204 return false;
2205
2208 // C++ [temp.param]p9:
2209 // A default template-argument shall not be specified in a
2210 // function template declaration or a function template
2211 // definition [...]
2212 // If a friend function template declaration specifies a default
2213 // template-argument, that declaration shall be a definition and shall be
2214 // the only declaration of the function template in the translation unit.
2215 // (C++98/03 doesn't have this wording; see DR226).
2216 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
2217 diag::warn_cxx98_compat_template_parameter_default_in_function_template
2218 : diag::ext_template_parameter_default_in_function_template)
2219 << DefArgRange;
2220 return false;
2221
2223 // C++0x [temp.param]p9:
2224 // A default template-argument shall not be specified in the
2225 // template-parameter-lists of the definition of a member of a
2226 // class template that appears outside of the member's class.
2227 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2228 << DefArgRange;
2229 return true;
2230
2233 // C++ [temp.param]p9:
2234 // A default template-argument shall not be specified in a
2235 // friend template declaration.
2236 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2237 << DefArgRange;
2238 return true;
2239
2240 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2241 // for friend function templates if there is only a single
2242 // declaration (and it is a definition). Strange!
2243 }
2244
2245 llvm_unreachable("Invalid TemplateParamListContext!");
2246}
2247
2248/// Check for unexpanded parameter packs within the template parameters
2249/// of a template template parameter, recursively.
2252 // A template template parameter which is a parameter pack is also a pack
2253 // expansion.
2254 if (TTP->isParameterPack())
2255 return false;
2256
2258 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2259 NamedDecl *P = Params->getParam(I);
2260 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
2261 if (!TTP->isParameterPack())
2262 if (const TypeConstraint *TC = TTP->getTypeConstraint())
2263 if (TC->hasExplicitTemplateArgs())
2264 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2267 return true;
2268 continue;
2269 }
2270
2271 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2272 if (!NTTP->isParameterPack() &&
2273 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2274 NTTP->getTypeSourceInfo(),
2276 return true;
2277
2278 continue;
2279 }
2280
2281 if (TemplateTemplateParmDecl *InnerTTP
2282 = dyn_cast<TemplateTemplateParmDecl>(P))
2283 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2284 return true;
2285 }
2286
2287 return false;
2288}
2289
2291 TemplateParameterList *OldParams,
2293 SkipBodyInfo *SkipBody) {
2294 bool Invalid = false;
2295
2296 // C++ [temp.param]p10:
2297 // The set of default template-arguments available for use with a
2298 // template declaration or definition is obtained by merging the
2299 // default arguments from the definition (if in scope) and all
2300 // declarations in scope in the same way default function
2301 // arguments are (8.3.6).
2302 bool SawDefaultArgument = false;
2303 SourceLocation PreviousDefaultArgLoc;
2304
2305 // Dummy initialization to avoid warnings.
2306 TemplateParameterList::iterator OldParam = NewParams->end();
2307 if (OldParams)
2308 OldParam = OldParams->begin();
2309
2310 bool RemoveDefaultArguments = false;
2311 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2312 NewParamEnd = NewParams->end();
2313 NewParam != NewParamEnd; ++NewParam) {
2314 // Whether we've seen a duplicate default argument in the same translation
2315 // unit.
2316 bool RedundantDefaultArg = false;
2317 // Whether we've found inconsis inconsitent default arguments in different
2318 // translation unit.
2319 bool InconsistentDefaultArg = false;
2320 // The name of the module which contains the inconsistent default argument.
2321 std::string PrevModuleName;
2322
2323 SourceLocation OldDefaultLoc;
2324 SourceLocation NewDefaultLoc;
2325
2326 // Variable used to diagnose missing default arguments
2327 bool MissingDefaultArg = false;
2328
2329 // Variable used to diagnose non-final parameter packs
2330 bool SawParameterPack = false;
2331
2332 if (TemplateTypeParmDecl *NewTypeParm
2333 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2334 // Check the presence of a default argument here.
2335 if (NewTypeParm->hasDefaultArgument() &&
2337 *this, TPC, NewTypeParm->getLocation(),
2338 NewTypeParm->getDefaultArgument().getSourceRange()))
2339 NewTypeParm->removeDefaultArgument();
2340
2341 // Merge default arguments for template type parameters.
2342 TemplateTypeParmDecl *OldTypeParm
2343 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2344 if (NewTypeParm->isParameterPack()) {
2345 assert(!NewTypeParm->hasDefaultArgument() &&
2346 "Parameter packs can't have a default argument!");
2347 SawParameterPack = true;
2348 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2349 NewTypeParm->hasDefaultArgument() &&
2350 (!SkipBody || !SkipBody->ShouldSkip)) {
2351 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2352 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2353 SawDefaultArgument = true;
2354
2355 if (!OldTypeParm->getOwningModule())
2356 RedundantDefaultArg = true;
2357 else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm,
2358 NewTypeParm)) {
2359 InconsistentDefaultArg = true;
2360 PrevModuleName =
2362 }
2363 PreviousDefaultArgLoc = NewDefaultLoc;
2364 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2365 // Merge the default argument from the old declaration to the
2366 // new declaration.
2367 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2368 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2369 } else if (NewTypeParm->hasDefaultArgument()) {
2370 SawDefaultArgument = true;
2371 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2372 } else if (SawDefaultArgument)
2373 MissingDefaultArg = true;
2374 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2375 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2376 // Check for unexpanded parameter packs.
2377 if (!NewNonTypeParm->isParameterPack() &&
2378 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2379 NewNonTypeParm->getTypeSourceInfo(),
2381 Invalid = true;
2382 continue;
2383 }
2384
2385 // Check the presence of a default argument here.
2386 if (NewNonTypeParm->hasDefaultArgument() &&
2388 *this, TPC, NewNonTypeParm->getLocation(),
2389 NewNonTypeParm->getDefaultArgument().getSourceRange())) {
2390 NewNonTypeParm->removeDefaultArgument();
2391 }
2392
2393 // Merge default arguments for non-type template parameters
2394 NonTypeTemplateParmDecl *OldNonTypeParm
2395 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2396 if (NewNonTypeParm->isParameterPack()) {
2397 assert(!NewNonTypeParm->hasDefaultArgument() &&
2398 "Parameter packs can't have a default argument!");
2399 if (!NewNonTypeParm->isPackExpansion())
2400 SawParameterPack = true;
2401 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2402 NewNonTypeParm->hasDefaultArgument() &&
2403 (!SkipBody || !SkipBody->ShouldSkip)) {
2404 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2405 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2406 SawDefaultArgument = true;
2407 if (!OldNonTypeParm->getOwningModule())
2408 RedundantDefaultArg = true;
2409 else if (!getASTContext().isSameDefaultTemplateArgument(
2410 OldNonTypeParm, NewNonTypeParm)) {
2411 InconsistentDefaultArg = true;
2412 PrevModuleName =
2413 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
2414 }
2415 PreviousDefaultArgLoc = NewDefaultLoc;
2416 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2417 // Merge the default argument from the old declaration to the
2418 // new declaration.
2419 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2420 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2421 } else if (NewNonTypeParm->hasDefaultArgument()) {
2422 SawDefaultArgument = true;
2423 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2424 } else if (SawDefaultArgument)
2425 MissingDefaultArg = true;
2426 } else {
2427 TemplateTemplateParmDecl *NewTemplateParm
2428 = cast<TemplateTemplateParmDecl>(*NewParam);
2429
2430 // Check for unexpanded parameter packs, recursively.
2431 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2432 Invalid = true;
2433 continue;
2434 }
2435
2436 // Check the presence of a default argument here.
2437 if (NewTemplateParm->hasDefaultArgument() &&
2439 NewTemplateParm->getLocation(),
2440 NewTemplateParm->getDefaultArgument().getSourceRange()))
2441 NewTemplateParm->removeDefaultArgument();
2442
2443 // Merge default arguments for template template parameters
2444 TemplateTemplateParmDecl *OldTemplateParm
2445 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2446 if (NewTemplateParm->isParameterPack()) {
2447 assert(!NewTemplateParm->hasDefaultArgument() &&
2448 "Parameter packs can't have a default argument!");
2449 if (!NewTemplateParm->isPackExpansion())
2450 SawParameterPack = true;
2451 } else if (OldTemplateParm &&
2452 hasVisibleDefaultArgument(OldTemplateParm) &&
2453 NewTemplateParm->hasDefaultArgument() &&
2454 (!SkipBody || !SkipBody->ShouldSkip)) {
2455 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2456 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2457 SawDefaultArgument = true;
2458 if (!OldTemplateParm->getOwningModule())
2459 RedundantDefaultArg = true;
2460 else if (!getASTContext().isSameDefaultTemplateArgument(
2461 OldTemplateParm, NewTemplateParm)) {
2462 InconsistentDefaultArg = true;
2463 PrevModuleName =
2464 OldTemplateParm->getImportedOwningModule()->getFullModuleName();
2465 }
2466 PreviousDefaultArgLoc = NewDefaultLoc;
2467 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2468 // Merge the default argument from the old declaration to the
2469 // new declaration.
2470 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2471 PreviousDefaultArgLoc
2472 = OldTemplateParm->getDefaultArgument().getLocation();
2473 } else if (NewTemplateParm->hasDefaultArgument()) {
2474 SawDefaultArgument = true;
2475 PreviousDefaultArgLoc
2476 = NewTemplateParm->getDefaultArgument().getLocation();
2477 } else if (SawDefaultArgument)
2478 MissingDefaultArg = true;
2479 }
2480
2481 // C++11 [temp.param]p11:
2482 // If a template parameter of a primary class template or alias template
2483 // is a template parameter pack, it shall be the last template parameter.
2484 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2485 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2486 TPC == TPC_TypeAliasTemplate)) {
2487 Diag((*NewParam)->getLocation(),
2488 diag::err_template_param_pack_must_be_last_template_parameter);
2489 Invalid = true;
2490 }
2491
2492 // [basic.def.odr]/13:
2493 // There can be more than one definition of a
2494 // ...
2495 // default template argument
2496 // ...
2497 // in a program provided that each definition appears in a different
2498 // translation unit and the definitions satisfy the [same-meaning
2499 // criteria of the ODR].
2500 //
2501 // Simply, the design of modules allows the definition of template default
2502 // argument to be repeated across translation unit. Note that the ODR is
2503 // checked elsewhere. But it is still not allowed to repeat template default
2504 // argument in the same translation unit.
2505 if (RedundantDefaultArg) {
2506 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2507 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2508 Invalid = true;
2509 } else if (InconsistentDefaultArg) {
2510 // We could only diagnose about the case that the OldParam is imported.
2511 // The case NewParam is imported should be handled in ASTReader.
2512 Diag(NewDefaultLoc,
2513 diag::err_template_param_default_arg_inconsistent_redefinition);
2514 Diag(OldDefaultLoc,
2515 diag::note_template_param_prev_default_arg_in_other_module)
2516 << PrevModuleName;
2517 Invalid = true;
2518 } else if (MissingDefaultArg &&
2519 (TPC == TPC_ClassTemplate || TPC == TPC_FriendClassTemplate ||
2520 TPC == TPC_VarTemplate || TPC == TPC_TypeAliasTemplate)) {
2521 // C++ 23[temp.param]p14:
2522 // If a template-parameter of a class template, variable template, or
2523 // alias template has a default template argument, each subsequent
2524 // template-parameter shall either have a default template argument
2525 // supplied or be a template parameter pack.
2526 Diag((*NewParam)->getLocation(),
2527 diag::err_template_param_default_arg_missing);
2528 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2529 Invalid = true;
2530 RemoveDefaultArguments = true;
2531 }
2532
2533 // If we have an old template parameter list that we're merging
2534 // in, move on to the next parameter.
2535 if (OldParams)
2536 ++OldParam;
2537 }
2538
2539 // We were missing some default arguments at the end of the list, so remove
2540 // all of the default arguments.
2541 if (RemoveDefaultArguments) {
2542 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2543 NewParamEnd = NewParams->end();
2544 NewParam != NewParamEnd; ++NewParam) {
2545 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2546 TTP->removeDefaultArgument();
2547 else if (NonTypeTemplateParmDecl *NTTP
2548 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2549 NTTP->removeDefaultArgument();
2550 else
2551 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2552 }
2553 }
2554
2555 return Invalid;
2556}
2557
2558namespace {
2559
2560/// A class which looks for a use of a certain level of template
2561/// parameter.
2562struct DependencyChecker : DynamicRecursiveASTVisitor {
2563 unsigned Depth;
2564
2565 // Whether we're looking for a use of a template parameter that makes the
2566 // overall construct type-dependent / a dependent type. This is strictly
2567 // best-effort for now; we may fail to match at all for a dependent type
2568 // in some cases if this is set.
2569 bool IgnoreNonTypeDependent;
2570
2571 bool Match;
2572 SourceLocation MatchLoc;
2573
2574 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2575 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2576 Match(false) {}
2577
2578 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2579 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2580 NamedDecl *ND = Params->getParam(0);
2581 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2582 Depth = PD->getDepth();
2583 } else if (NonTypeTemplateParmDecl *PD =
2584 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2585 Depth = PD->getDepth();
2586 } else {
2587 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2588 }
2589 }
2590
2591 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2592 if (ParmDepth >= Depth) {
2593 Match = true;
2594 MatchLoc = Loc;
2595 return true;
2596 }
2597 return false;
2598 }
2599
2600 bool TraverseStmt(Stmt *S) override {
2601 // Prune out non-type-dependent expressions if requested. This can
2602 // sometimes result in us failing to find a template parameter reference
2603 // (if a value-dependent expression creates a dependent type), but this
2604 // mode is best-effort only.
2605 if (auto *E = dyn_cast_or_null<Expr>(S))
2606 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2607 return true;
2609 }
2610
2611 bool TraverseTypeLoc(TypeLoc TL) override {
2612 if (IgnoreNonTypeDependent && !TL.isNull() &&
2613 !TL.getType()->isDependentType())
2614 return true;
2616 }
2617
2618 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) override {
2619 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2620 }
2621
2622 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
2623 // For a best-effort search, keep looking until we find a location.
2624 return IgnoreNonTypeDependent || !Matches(T->getDepth());
2625 }
2626
2627 bool TraverseTemplateName(TemplateName N) override {
2628 if (TemplateTemplateParmDecl *PD =
2629 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2630 if (Matches(PD->getDepth()))
2631 return false;
2633 }
2634
2635 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2636 if (NonTypeTemplateParmDecl *PD =
2637 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2638 if (Matches(PD->getDepth(), E->getExprLoc()))
2639 return false;
2640 return DynamicRecursiveASTVisitor::VisitDeclRefExpr(E);
2641 }
2642
2643 bool VisitSubstTemplateTypeParmType(SubstTemplateTypeParmType *T) override {
2644 return TraverseType(T->getReplacementType());
2645 }
2646
2647 bool VisitSubstTemplateTypeParmPackType(
2648 SubstTemplateTypeParmPackType *T) override {
2649 return TraverseTemplateArgument(T->getArgumentPack());
2650 }
2651
2652 bool TraverseInjectedClassNameType(InjectedClassNameType *T) override {
2653 return TraverseType(T->getInjectedSpecializationType());
2654 }
2655};
2656} // end anonymous namespace
2657
2658/// Determines whether a given type depends on the given parameter
2659/// list.
2660static bool
2662 if (!Params->size())
2663 return false;
2664
2665 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2666 Checker.TraverseType(T);
2667 return Checker.Match;
2668}
2669
2670// Find the source range corresponding to the named type in the given
2671// nested-name-specifier, if any.
2673 QualType T,
2674 const CXXScopeSpec &SS) {
2676 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2677 if (const Type *CurType = NNS->getAsType()) {
2678 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2679 return NNSLoc.getTypeLoc().getSourceRange();
2680 } else
2681 break;
2682
2683 NNSLoc = NNSLoc.getPrefix();
2684 }
2685
2686 return SourceRange();
2687}
2688
2690 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2691 TemplateIdAnnotation *TemplateId,
2692 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2693 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
2694 IsMemberSpecialization = false;
2695 Invalid = false;
2696
2697 // The sequence of nested types to which we will match up the template
2698 // parameter lists. We first build this list by starting with the type named
2699 // by the nested-name-specifier and walking out until we run out of types.
2700 SmallVector<QualType, 4> NestedTypes;
2701 QualType T;
2702 if (SS.getScopeRep()) {
2704 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2706 else
2707 T = QualType(SS.getScopeRep()->getAsType(), 0);
2708 }
2709
2710 // If we found an explicit specialization that prevents us from needing
2711 // 'template<>' headers, this will be set to the location of that
2712 // explicit specialization.
2713 SourceLocation ExplicitSpecLoc;
2714
2715 while (!T.isNull()) {
2716 NestedTypes.push_back(T);
2717
2718 // Retrieve the parent of a record type.
2720 // If this type is an explicit specialization, we're done.
2722 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2723 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
2724 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2725 ExplicitSpecLoc = Spec->getLocation();
2726 break;
2727 }
2728 } else if (Record->getTemplateSpecializationKind()
2730 ExplicitSpecLoc = Record->getLocation();
2731 break;
2732 }
2733
2734 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2736 else
2737 T = QualType();
2738 continue;
2739 }
2740
2741 if (const TemplateSpecializationType *TST
2743 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2744 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2746 else
2747 T = QualType();
2748 continue;
2749 }
2750 }
2751
2752 // Look one step prior in a dependent template specialization type.
2753 if (const DependentTemplateSpecializationType *DependentTST
2755 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2756 T = QualType(NNS->getAsType(), 0);
2757 else
2758 T = QualType();
2759 continue;
2760 }
2761
2762 // Look one step prior in a dependent name type.
2763 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2764 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2765 T = QualType(NNS->getAsType(), 0);
2766 else
2767 T = QualType();
2768 continue;
2769 }
2770
2771 // Retrieve the parent of an enumeration type.
2772 if (const EnumType *EnumT = T->getAs<EnumType>()) {
2773 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2774 // check here.
2775 EnumDecl *Enum = EnumT->getDecl();
2776
2777 // Get to the parent type.
2778 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2780 else
2781 T = QualType();
2782 continue;
2783 }
2784
2785 T = QualType();
2786 }
2787 // Reverse the nested types list, since we want to traverse from the outermost
2788 // to the innermost while checking template-parameter-lists.
2789 std::reverse(NestedTypes.begin(), NestedTypes.end());
2790
2791 // C++0x [temp.expl.spec]p17:
2792 // A member or a member template may be nested within many
2793 // enclosing class templates. In an explicit specialization for
2794 // such a member, the member declaration shall be preceded by a
2795 // template<> for each enclosing class template that is
2796 // explicitly specialized.
2797 bool SawNonEmptyTemplateParameterList = false;
2798
2799 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2800 if (SawNonEmptyTemplateParameterList) {
2801 if (!SuppressDiagnostic)
2802 Diag(DeclLoc, diag::err_specialize_member_of_template)
2803 << !Recovery << Range;
2804 Invalid = true;
2805 IsMemberSpecialization = false;
2806 return true;
2807 }
2808
2809 return false;
2810 };
2811
2812 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2813 // Check that we can have an explicit specialization here.
2814 if (CheckExplicitSpecialization(Range, true))
2815 return true;
2816
2817 // We don't have a template header, but we should.
2818 SourceLocation ExpectedTemplateLoc;
2819 if (!ParamLists.empty())
2820 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2821 else
2822 ExpectedTemplateLoc = DeclStartLoc;
2823
2824 if (!SuppressDiagnostic)
2825 Diag(DeclLoc, diag::err_template_spec_needs_header)
2826 << Range
2827 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2828 return false;
2829 };
2830
2831 unsigned ParamIdx = 0;
2832 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2833 ++TypeIdx) {
2834 T = NestedTypes[TypeIdx];
2835
2836 // Whether we expect a 'template<>' header.
2837 bool NeedEmptyTemplateHeader = false;
2838
2839 // Whether we expect a template header with parameters.
2840 bool NeedNonemptyTemplateHeader = false;
2841
2842 // For a dependent type, the set of template parameters that we
2843 // expect to see.
2844 TemplateParameterList *ExpectedTemplateParams = nullptr;
2845
2846 // C++0x [temp.expl.spec]p15:
2847 // A member or a member template may be nested within many enclosing
2848 // class templates. In an explicit specialization for such a member, the
2849 // member declaration shall be preceded by a template<> for each
2850 // enclosing class template that is explicitly specialized.
2853 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2854 ExpectedTemplateParams = Partial->getTemplateParameters();
2855 NeedNonemptyTemplateHeader = true;
2856 } else if (Record->isDependentType()) {
2857 if (Record->getDescribedClassTemplate()) {
2858 ExpectedTemplateParams = Record->getDescribedClassTemplate()
2859 ->getTemplateParameters();
2860 NeedNonemptyTemplateHeader = true;
2861 }
2862 } else if (ClassTemplateSpecializationDecl *Spec
2863 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2864 // C++0x [temp.expl.spec]p4:
2865 // Members of an explicitly specialized class template are defined
2866 // in the same manner as members of normal classes, and not using
2867 // the template<> syntax.
2868 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2869 NeedEmptyTemplateHeader = true;
2870 else
2871 continue;
2872 } else if (Record->getTemplateSpecializationKind()) {
2873 if (Record->getTemplateSpecializationKind()
2875 TypeIdx == NumTypes - 1)
2876 IsMemberSpecialization = true;
2877
2878 continue;
2879 }
2880 } else if (const TemplateSpecializationType *TST
2882 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2883 ExpectedTemplateParams = Template->getTemplateParameters();
2884 NeedNonemptyTemplateHeader = true;
2885 }
2887 // FIXME: We actually could/should check the template arguments here
2888 // against the corresponding template parameter list.
2889 NeedNonemptyTemplateHeader = false;
2890 }
2891
2892 // C++ [temp.expl.spec]p16:
2893 // In an explicit specialization declaration for a member of a class
2894 // template or a member template that appears in namespace scope, the
2895 // member template and some of its enclosing class templates may remain
2896 // unspecialized, except that the declaration shall not explicitly
2897 // specialize a class member template if its enclosing class templates
2898 // are not explicitly specialized as well.
2899 if (ParamIdx < ParamLists.size()) {
2900 if (ParamLists[ParamIdx]->size() == 0) {
2901 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2902 false))
2903 return nullptr;
2904 } else
2905 SawNonEmptyTemplateParameterList = true;
2906 }
2907
2908 if (NeedEmptyTemplateHeader) {
2909 // If we're on the last of the types, and we need a 'template<>' header
2910 // here, then it's a member specialization.
2911 if (TypeIdx == NumTypes - 1)
2912 IsMemberSpecialization = true;
2913
2914 if (ParamIdx < ParamLists.size()) {
2915 if (ParamLists[ParamIdx]->size() > 0) {
2916 // The header has template parameters when it shouldn't. Complain.
2917 if (!SuppressDiagnostic)
2918 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2919 diag::err_template_param_list_matches_nontemplate)
2920 << T
2921 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2922 ParamLists[ParamIdx]->getRAngleLoc())
2924 Invalid = true;
2925 return nullptr;
2926 }
2927
2928 // Consume this template header.
2929 ++ParamIdx;
2930 continue;
2931 }
2932
2933 if (!IsFriend)
2934 if (DiagnoseMissingExplicitSpecialization(
2936 return nullptr;
2937
2938 continue;
2939 }
2940
2941 if (NeedNonemptyTemplateHeader) {
2942 // In friend declarations we can have template-ids which don't
2943 // depend on the corresponding template parameter lists. But
2944 // assume that empty parameter lists are supposed to match this
2945 // template-id.
2946 if (IsFriend && T->isDependentType()) {
2947 if (ParamIdx < ParamLists.size() &&
2949 ExpectedTemplateParams = nullptr;
2950 else
2951 continue;
2952 }
2953
2954 if (ParamIdx < ParamLists.size()) {
2955 // Check the template parameter list, if we can.
2956 if (ExpectedTemplateParams &&
2958 ExpectedTemplateParams,
2959 !SuppressDiagnostic, TPL_TemplateMatch))
2960 Invalid = true;
2961
2962 if (!Invalid &&
2963 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
2965 Invalid = true;
2966
2967 ++ParamIdx;
2968 continue;
2969 }
2970
2971 if (!SuppressDiagnostic)
2972 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2973 << T
2975 Invalid = true;
2976 continue;
2977 }
2978 }
2979
2980 // If there were at least as many template-ids as there were template
2981 // parameter lists, then there are no template parameter lists remaining for
2982 // the declaration itself.
2983 if (ParamIdx >= ParamLists.size()) {
2984 if (TemplateId && !IsFriend) {
2985 // We don't have a template header for the declaration itself, but we
2986 // should.
2987 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2988 TemplateId->RAngleLoc));
2989
2990 // Fabricate an empty template parameter list for the invented header.
2992 SourceLocation(), {},
2993 SourceLocation(), nullptr);
2994 }
2995
2996 return nullptr;
2997 }
2998
2999 // If there were too many template parameter lists, complain about that now.
3000 if (ParamIdx < ParamLists.size() - 1) {
3001 bool HasAnyExplicitSpecHeader = false;
3002 bool AllExplicitSpecHeaders = true;
3003 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3004 if (ParamLists[I]->size() == 0)
3005 HasAnyExplicitSpecHeader = true;
3006 else
3007 AllExplicitSpecHeaders = false;
3008 }
3009
3010 if (!SuppressDiagnostic)
3011 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3012 AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
3013 : diag::err_template_spec_extra_headers)
3014 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3015 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3016
3017 // If there was a specialization somewhere, such that 'template<>' is
3018 // not required, and there were any 'template<>' headers, note where the
3019 // specialization occurred.
3020 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3021 !SuppressDiagnostic)
3022 Diag(ExplicitSpecLoc,
3023 diag::note_explicit_template_spec_does_not_need_header)
3024 << NestedTypes.back();
3025
3026 // We have a template parameter list with no corresponding scope, which
3027 // means that the resulting template declaration can't be instantiated
3028 // properly (we'll end up with dependent nodes when we shouldn't).
3029 if (!AllExplicitSpecHeaders)
3030 Invalid = true;
3031 }
3032
3033 // C++ [temp.expl.spec]p16:
3034 // In an explicit specialization declaration for a member of a class
3035 // template or a member template that ap- pears in namespace scope, the
3036 // member template and some of its enclosing class templates may remain
3037 // unspecialized, except that the declaration shall not explicitly
3038 // specialize a class member template if its en- closing class templates
3039 // are not explicitly specialized as well.
3040 if (ParamLists.back()->size() == 0 &&
3041 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3042 false))
3043 return nullptr;
3044
3045 // Return the last template parameter list, which corresponds to the
3046 // entity being declared.
3047 return ParamLists.back();
3048}
3049
3051 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3052 Diag(Template->getLocation(), diag::note_template_declared_here)
3053 << (isa<FunctionTemplateDecl>(Template)
3054 ? 0
3055 : isa<ClassTemplateDecl>(Template)
3056 ? 1
3057 : isa<VarTemplateDecl>(Template)
3058 ? 2
3059 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
3060 << Template->getDeclName();
3061 return;
3062 }
3063
3064 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
3065 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3066 IEnd = OST->end();
3067 I != IEnd; ++I)
3068 Diag((*I)->getLocation(), diag::note_template_declared_here)
3069 << 0 << (*I)->getDeclName();
3070
3071 return;
3072 }
3073}
3074
3076 SourceLocation TemplateLoc,
3078 auto lookUpCommonType = [&](TemplateArgument T1,
3079 TemplateArgument T2) -> QualType {
3080 // Don't bother looking for other specializations if both types are
3081 // builtins - users aren't allowed to specialize for them
3082 if (T1.getAsType()->isBuiltinType() && T2.getAsType()->isBuiltinType())
3083 return builtinCommonTypeImpl(S, BaseTemplate, TemplateLoc, {T1, T2});
3084
3089 T2, S.Context.getTrivialTypeSourceInfo(T2.getAsType())));
3090
3091 EnterExpressionEvaluationContext UnevaluatedContext(
3093 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
3095
3096 QualType BaseTemplateInst =
3097 S.CheckTemplateIdType(BaseTemplate, TemplateLoc, Args);
3098
3099 if (SFINAE.hasErrorOccurred())
3100 return QualType();
3101
3102 return BaseTemplateInst;
3103 };
3104
3105 // Note A: For the common_type trait applied to a template parameter pack T of
3106 // types, the member type shall be either defined or not present as follows:
3107 switch (Ts.size()) {
3108
3109 // If sizeof...(T) is zero, there shall be no member type.
3110 case 0:
3111 return QualType();
3112
3113 // If sizeof...(T) is one, let T0 denote the sole type constituting the
3114 // pack T. The member typedef-name type shall denote the same type, if any, as
3115 // common_type_t<T0, T0>; otherwise there shall be no member type.
3116 case 1:
3117 return lookUpCommonType(Ts[0], Ts[0]);
3118
3119 // If sizeof...(T) is two, let the first and second types constituting T be
3120 // denoted by T1 and T2, respectively, and let D1 and D2 denote the same types
3121 // as decay_t<T1> and decay_t<T2>, respectively.
3122 case 2: {
3123 QualType T1 = Ts[0].getAsType();
3124 QualType T2 = Ts[1].getAsType();
3125 QualType D1 = S.BuiltinDecay(T1, {});
3126 QualType D2 = S.BuiltinDecay(T2, {});
3127
3128 // If is_same_v<T1, D1> is false or is_same_v<T2, D2> is false, let C denote
3129 // the same type, if any, as common_type_t<D1, D2>.
3130 if (!S.Context.hasSameType(T1, D1) || !S.Context.hasSameType(T2, D2))
3131 return lookUpCommonType(D1, D2);
3132
3133 // Otherwise, if decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3134 // denotes a valid type, let C denote that type.
3135 {
3136 auto CheckConditionalOperands = [&](bool ConstRefQual) -> QualType {
3137 EnterExpressionEvaluationContext UnevaluatedContext(
3139 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
3141
3142 // false
3144 VK_PRValue);
3145 ExprResult Cond = &CondExpr;
3146
3147 auto EVK = ConstRefQual ? VK_LValue : VK_PRValue;
3148 if (ConstRefQual) {
3149 D1.addConst();
3150 D2.addConst();
3151 }
3152
3153 // declval<D1>()
3154 OpaqueValueExpr LHSExpr(TemplateLoc, D1, EVK);
3155 ExprResult LHS = &LHSExpr;
3156
3157 // declval<D2>()
3158 OpaqueValueExpr RHSExpr(TemplateLoc, D2, EVK);
3159 ExprResult RHS = &RHSExpr;
3160
3163
3164 // decltype(false ? declval<D1>() : declval<D2>())
3166 S.CheckConditionalOperands(Cond, LHS, RHS, VK, OK, TemplateLoc);
3167
3168 if (Result.isNull() || SFINAE.hasErrorOccurred())
3169 return QualType();
3170
3171 // decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3172 return S.BuiltinDecay(Result, TemplateLoc);
3173 };
3174
3175 if (auto Res = CheckConditionalOperands(false); !Res.isNull())
3176 return Res;
3177
3178 // Let:
3179 // CREF(A) be add_lvalue_reference_t<const remove_reference_t<A>>,
3180 // COND-RES(X, Y) be
3181 // decltype(false ? declval<X(&)()>()() : declval<Y(&)()>()()).
3182
3183 // C++20 only
3184 // Otherwise, if COND-RES(CREF(D1), CREF(D2)) denotes a type, let C denote
3185 // the type decay_t<COND-RES(CREF(D1), CREF(D2))>.
3186 if (!S.Context.getLangOpts().CPlusPlus20)
3187 return QualType();
3188 return CheckConditionalOperands(true);
3189 }
3190 }
3191
3192 // If sizeof...(T) is greater than two, let T1, T2, and R, respectively,
3193 // denote the first, second, and (pack of) remaining types constituting T. Let
3194 // C denote the same type, if any, as common_type_t<T1, T2>. If there is such
3195 // a type C, the member typedef-name type shall denote the same type, if any,
3196 // as common_type_t<C, R...>. Otherwise, there shall be no member type.
3197 default: {
3198 QualType Result = Ts.front().getAsType();
3199 for (auto T : llvm::drop_begin(Ts)) {
3200 Result = lookUpCommonType(Result, T.getAsType());
3201 if (Result.isNull())
3202 return QualType();
3203 }
3204 return Result;
3205 }
3206 }
3207}
3208
3209static QualType
3212 SourceLocation TemplateLoc,
3213 TemplateArgumentListInfo &TemplateArgs) {
3214 ASTContext &Context = SemaRef.getASTContext();
3215
3216 switch (BTD->getBuiltinTemplateKind()) {
3217 case BTK__make_integer_seq: {
3218 // Specializations of __make_integer_seq<S, T, N> are treated like
3219 // S<T, 0, ..., N-1>.
3220
3221 QualType OrigType = Converted[1].getAsType();
3222 // C++14 [inteseq.intseq]p1:
3223 // T shall be an integer type.
3224 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) {
3225 SemaRef.Diag(TemplateArgs[1].getLocation(),
3226 diag::err_integer_sequence_integral_element_type);
3227 return QualType();
3228 }
3229
3230 TemplateArgument NumArgsArg = Converted[2];
3231 if (NumArgsArg.isDependent())
3233 Converted);
3234
3235 TemplateArgumentListInfo SyntheticTemplateArgs;
3236 // The type argument, wrapped in substitution sugar, gets reused as the
3237 // first template argument in the synthetic template argument list.
3238 SyntheticTemplateArgs.addArgument(
3241 OrigType, TemplateArgs[1].getLocation())));
3242
3243 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3244 // Expand N into 0 ... N-1.
3245 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3246 I < NumArgs; ++I) {
3247 TemplateArgument TA(Context, I, OrigType);
3248 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3249 TA, OrigType, TemplateArgs[2].getLocation()));
3250 }
3251 } else {
3252 // C++14 [inteseq.make]p1:
3253 // If N is negative the program is ill-formed.
3254 SemaRef.Diag(TemplateArgs[2].getLocation(),
3255 diag::err_integer_sequence_negative_length);
3256 return QualType();
3257 }
3258
3259 // The first template argument will be reused as the template decl that
3260 // our synthetic template arguments will be applied to.
3261 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
3262 TemplateLoc, SyntheticTemplateArgs);
3263 }
3264
3266 // Specializations of
3267 // __type_pack_element<Index, T_1, ..., T_N>
3268 // are treated like T_Index.
3269 assert(Converted.size() == 2 &&
3270 "__type_pack_element should be given an index and a parameter pack");
3271
3272 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3273 if (IndexArg.isDependent() || Ts.isDependent())
3275 Converted);
3276
3277 llvm::APSInt Index = IndexArg.getAsIntegral();
3278 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3279 "type std::size_t, and hence be non-negative");
3280 // If the Index is out of bounds, the program is ill-formed.
3281 if (Index >= Ts.pack_size()) {
3282 SemaRef.Diag(TemplateArgs[0].getLocation(),
3283 diag::err_type_pack_element_out_of_bounds);
3284 return QualType();
3285 }
3286
3287 // We simply return the type at index `Index`.
3288 int64_t N = Index.getExtValue();
3289 return Ts.getPackAsArray()[N].getAsType();
3290 }
3291
3293 assert(Converted.size() == 4);
3294 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))
3296 Converted);
3297
3298 TemplateName BaseTemplate = Converted[0].getAsTemplate();
3299 TemplateName HasTypeMember = Converted[1].getAsTemplate();
3300 QualType HasNoTypeMember = Converted[2].getAsType();
3301 ArrayRef<TemplateArgument> Ts = Converted[3].getPackAsArray();
3302 if (auto CT = builtinCommonTypeImpl(SemaRef, BaseTemplate, TemplateLoc, Ts);
3303 !CT.isNull()) {
3307 CT, TemplateArgs[1].getLocation())));
3308
3309 return SemaRef.CheckTemplateIdType(HasTypeMember, TemplateLoc, TAs);
3310 }
3311 return HasNoTypeMember;
3312 }
3313 }
3314 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3315}
3316
3317/// Determine whether this alias template is "enable_if_t".
3318/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3320 return AliasTemplate->getName() == "enable_if_t" ||
3321 AliasTemplate->getName() == "__enable_if_t";
3322}
3323
3324/// Collect all of the separable terms in the given condition, which
3325/// might be a conjunction.
3326///
3327/// FIXME: The right answer is to convert the logical expression into
3328/// disjunctive normal form, so we can find the first failed term
3329/// within each possible clause.
3330static void collectConjunctionTerms(Expr *Clause,
3331 SmallVectorImpl<Expr *> &Terms) {
3332 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3333 if (BinOp->getOpcode() == BO_LAnd) {
3334 collectConjunctionTerms(BinOp->getLHS(), Terms);
3335 collectConjunctionTerms(BinOp->getRHS(), Terms);
3336 return;
3337 }
3338 }
3339
3340 Terms.push_back(Clause);
3341}
3342
3343// The ranges-v3 library uses an odd pattern of a top-level "||" with
3344// a left-hand side that is value-dependent but never true. Identify
3345// the idiom and ignore that term.
3347 // Top-level '||'.
3348 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3349 if (!BinOp) return Cond;
3350
3351 if (BinOp->getOpcode() != BO_LOr) return Cond;
3352
3353 // With an inner '==' that has a literal on the right-hand side.
3354 Expr *LHS = BinOp->getLHS();
3355 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3356 if (!InnerBinOp) return Cond;
3357
3358 if (InnerBinOp->getOpcode() != BO_EQ ||
3359 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3360 return Cond;
3361
3362 // If the inner binary operation came from a macro expansion named
3363 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3364 // of the '||', which is the real, user-provided condition.
3365 SourceLocation Loc = InnerBinOp->getExprLoc();
3366 if (!Loc.isMacroID()) return Cond;
3367
3368 StringRef MacroName = PP.getImmediateMacroName(Loc);
3369 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3370 return BinOp->getRHS();
3371
3372 return Cond;
3373}
3374
3375namespace {
3376
3377// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3378// within failing boolean expression, such as substituting template parameters
3379// for actual types.
3380class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3381public:
3382 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3383 : Policy(P) {}
3384
3385 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3386 const auto *DR = dyn_cast<DeclRefExpr>(E);
3387 if (DR && DR->getQualifier()) {
3388 // If this is a qualified name, expand the template arguments in nested
3389 // qualifiers.
3390 DR->getQualifier()->print(OS, Policy, true);
3391 // Then print the decl itself.
3392 const ValueDecl *VD = DR->getDecl();
3393 OS << VD->getName();
3394 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3395 // This is a template variable, print the expanded template arguments.
3397 OS, IV->getTemplateArgs().asArray(), Policy,
3398 IV->getSpecializedTemplate()->getTemplateParameters());
3399 }
3400 return true;
3401 }
3402 return false;
3403 }
3404
3405private:
3406 const PrintingPolicy Policy;
3407};
3408
3409} // end anonymous namespace
3410
3411std::pair<Expr *, std::string>
3413 Cond = lookThroughRangesV3Condition(PP, Cond);
3414
3415 // Separate out all of the terms in a conjunction.
3417 collectConjunctionTerms(Cond, Terms);
3418
3419 // Determine which term failed.
3420 Expr *FailedCond = nullptr;
3421 for (Expr *Term : Terms) {
3422 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3423
3424 // Literals are uninteresting.
3425 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3426 isa<IntegerLiteral>(TermAsWritten))
3427 continue;
3428
3429 // The initialization of the parameter from the argument is
3430 // a constant-evaluated context.
3433
3434 bool Succeeded;
3435 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3436 !Succeeded) {
3437 FailedCond = TermAsWritten;
3438 break;
3439 }
3440 }
3441 if (!FailedCond)
3442 FailedCond = Cond->IgnoreParenImpCasts();
3443
3444 std::string Description;
3445 {
3446 llvm::raw_string_ostream Out(Description);
3448 Policy.PrintCanonicalTypes = true;
3449 FailedBooleanConditionPrinterHelper Helper(Policy);
3450 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3451 }
3452 return { FailedCond, Description };
3453}
3454
3456 SourceLocation TemplateLoc,
3457 TemplateArgumentListInfo &TemplateArgs) {
3459 Name.getUnderlying().getAsDependentTemplateName();
3460 if (DTN && DTN->isIdentifier())
3461 // When building a template-id where the template-name is dependent,
3462 // assume the template is a type template. Either our assumption is
3463 // correct, or the code is ill-formed and will be diagnosed when the
3464 // dependent name is substituted.
3467 TemplateArgs.arguments());
3468
3469 if (Name.getAsAssumedTemplateName() &&
3470 resolveAssumedTemplateNameAsType(/*Scope=*/nullptr, Name, TemplateLoc))
3471 return QualType();
3472
3473 auto [Template, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
3474
3475 if (!Template || isa<FunctionTemplateDecl>(Template) ||
3476 isa<VarTemplateDecl>(Template) || isa<ConceptDecl>(Template)) {
3477 // We might have a substituted template template parameter pack. If so,
3478 // build a template specialization type for it.
3479 if (Name.getAsSubstTemplateTemplateParmPack())
3481 TemplateArgs.arguments());
3482
3483 Diag(TemplateLoc, diag::err_template_id_not_a_type)
3484 << Name;
3486 return QualType();
3487 }
3488
3489 // Check that the template argument list is well-formed for this
3490 // template.
3491 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
3492 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3493 DefaultArgs, false, SugaredConverted,
3494 CanonicalConverted,
3495 /*UpdateArgsWithConversions=*/true))
3496 return QualType();
3497
3498 QualType CanonType;
3499
3501 dyn_cast<TypeAliasTemplateDecl>(Template)) {
3502
3503 // Find the canonical type for this type alias template specialization.
3504 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3505 if (Pattern->isInvalidDecl())
3506 return QualType();
3507
3508 // Only substitute for the innermost template argument list. NOTE: Some
3509 // external resugarers rely on leaving a Subst* node here. Make the
3510 // substitution non-final in that case. Note that these external resugarers
3511 // will still miss some information in this representation, because we don't
3512 // provide enough context in the Subst* nodes in order to tell different
3513 // template type alias specializations apart.
3514 MultiLevelTemplateArgumentList TemplateArgLists;
3515 TemplateArgLists.addOuterTemplateArguments(
3516 Template, SugaredConverted,
3517 /*Final=*/!getLangOpts().RetainSubstTemplateTypeParmTypeAstNodes);
3518 TemplateArgLists.addOuterRetainedLevels(
3519 AliasTemplate->getTemplateParameters()->getDepth());
3520
3523 *this, /*PointOfInstantiation=*/TemplateLoc,
3524 /*Entity=*/AliasTemplate,
3525 /*TemplateArgs=*/TemplateArgLists.getInnermost());
3526
3527 // Diagnose uses of this alias.
3528 (void)DiagnoseUseOfDecl(AliasTemplate, TemplateLoc);
3529
3530 if (Inst.isInvalid())
3531 return QualType();
3532
3533 std::optional<ContextRAII> SavedContext;
3534 if (!AliasTemplate->getDeclContext()->isFileContext())
3535 SavedContext.emplace(*this, AliasTemplate->getDeclContext());
3536
3537 CanonType =
3538 SubstType(Pattern->getUnderlyingType(), TemplateArgLists,
3539 AliasTemplate->getLocation(), AliasTemplate->getDeclName());
3540 if (CanonType.isNull()) {
3541 // If this was enable_if and we failed to find the nested type
3542 // within enable_if in a SFINAE context, dig out the specific
3543 // enable_if condition that failed and present that instead.
3545 if (auto DeductionInfo = isSFINAEContext()) {
3546 if (*DeductionInfo &&
3547 (*DeductionInfo)->hasSFINAEDiagnostic() &&
3548 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3549 diag::err_typename_nested_not_found_enable_if &&
3550 TemplateArgs[0].getArgument().getKind()
3552 Expr *FailedCond;
3553 std::string FailedDescription;
3554 std::tie(FailedCond, FailedDescription) =
3555 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
3556
3557 // Remove the old SFINAE diagnostic.
3558 PartialDiagnosticAt OldDiag =
3560 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3561
3562 // Add a new SFINAE diagnostic specifying which condition
3563 // failed.
3564 (*DeductionInfo)->addSFINAEDiagnostic(
3565 OldDiag.first,
3566 PDiag(diag::err_typename_nested_not_found_requirement)
3567 << FailedDescription
3568 << FailedCond->getSourceRange());
3569 }
3570 }
3571 }
3572
3573 return QualType();
3574 }
3575 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3576 CanonType = checkBuiltinTemplateIdType(*this, BTD, SugaredConverted,
3577 TemplateLoc, TemplateArgs);
3578 } else if (Name.isDependent() ||
3580 TemplateArgs, CanonicalConverted)) {
3581 // This class template specialization is a dependent
3582 // type. Therefore, its canonical type is another class template
3583 // specialization type that contains all of the converted
3584 // arguments in canonical form. This ensures that, e.g., A<T> and
3585 // A<T, T> have identical types when A is declared as:
3586 //
3587 // template<typename T, typename U = T> struct A;
3589 Name, CanonicalConverted);
3590
3591 // This might work out to be a current instantiation, in which
3592 // case the canonical type needs to be the InjectedClassNameType.
3593 //
3594 // TODO: in theory this could be a simple hashtable lookup; most
3595 // changes to CurContext don't change the set of current
3596 // instantiations.
3597 if (isa<ClassTemplateDecl>(Template)) {
3598 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3599 // If we get out to a namespace, we're done.
3600 if (Ctx->isFileContext()) break;
3601
3602 // If this isn't a record, keep looking.
3603 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3604 if (!Record) continue;
3605
3606 // Look for one of the two cases with InjectedClassNameTypes
3607 // and check whether it's the same template.
3608 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3609 !Record->getDescribedClassTemplate())
3610 continue;
3611
3612 // Fetch the injected class name type and check whether its
3613 // injected type is equal to the type we just built.
3615 QualType Injected = cast<InjectedClassNameType>(ICNT)
3616 ->getInjectedSpecializationType();
3617
3618 if (CanonType != Injected->getCanonicalTypeInternal())
3619 continue;
3620
3621 // If so, the canonical type of this TST is the injected
3622 // class name type of the record we just found.
3623 assert(ICNT.isCanonical());
3624 CanonType = ICNT;
3625 break;
3626 }
3627 }
3628 } else if (ClassTemplateDecl *ClassTemplate =
3629 dyn_cast<ClassTemplateDecl>(Template)) {
3630 // Find the class template specialization declaration that
3631 // corresponds to these arguments.
3632 void *InsertPos = nullptr;
3634 ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
3635 if (!Decl) {
3636 // This is the first time we have referenced this class template
3637 // specialization. Create the canonical declaration and add it to
3638 // the set of specializations.
3640 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3641 ClassTemplate->getDeclContext(),
3642 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3643 ClassTemplate->getLocation(), ClassTemplate, CanonicalConverted,
3644 nullptr);
3645 ClassTemplate->AddSpecialization(Decl, InsertPos);
3646 if (ClassTemplate->isOutOfLine())
3647 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3648 }
3649
3650 if (Decl->getSpecializationKind() == TSK_Undeclared &&
3651 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
3652 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
3653 if (!Inst.isInvalid()) {
3654 MultiLevelTemplateArgumentList TemplateArgLists(Template,
3655 CanonicalConverted,
3656 /*Final=*/false);
3657 InstantiateAttrsForDecl(TemplateArgLists,
3658 ClassTemplate->getTemplatedDecl(), Decl);
3659 }
3660 }
3661
3662 // Diagnose uses of this specialization.
3663 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3664
3665 CanonType = Context.getTypeDeclType(Decl);
3666 assert(isa<RecordType>(CanonType) &&
3667 "type of non-dependent specialization is not a RecordType");
3668 } else {
3669 llvm_unreachable("Unhandled template kind");
3670 }
3671
3672 // Build the fully-sugared type for this class template
3673 // specialization, which refers back to the class template
3674 // specialization we created or found.
3675 return Context.getTemplateSpecializationType(Name, TemplateArgs.arguments(),
3676 CanonType);
3677}
3678
3680 TemplateNameKind &TNK,
3681 SourceLocation NameLoc,
3682 IdentifierInfo *&II) {
3683 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
3684
3685 TemplateName Name = ParsedName.get();
3686 auto *ATN = Name.getAsAssumedTemplateName();
3687 assert(ATN && "not an assumed template name");
3688 II = ATN->getDeclName().getAsIdentifierInfo();
3689
3690 if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) {
3691 // Resolved to a type template name.
3692 ParsedName = TemplateTy::make(Name);
3693 TNK = TNK_Type_template;
3694 }
3695}
3696
3698 SourceLocation NameLoc,
3699 bool Diagnose) {
3700 // We assumed this undeclared identifier to be an (ADL-only) function
3701 // template name, but it was used in a context where a type was required.
3702 // Try to typo-correct it now.
3703 AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName();
3704 assert(ATN && "not an assumed template name");
3705
3706 LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName);
3707 struct CandidateCallback : CorrectionCandidateCallback {
3708 bool ValidateCandidate(const TypoCorrection &TC) override {
3709 return TC.getCorrectionDecl() &&
3711 }
3712 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3713 return std::make_unique<CandidateCallback>(*this);
3714 }
3715 } FilterCCC;
3716
3717 TypoCorrection Corrected =
3718 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
3719 FilterCCC, CTK_ErrorRecovery);
3720 if (Corrected && Corrected.getFoundDecl()) {
3721 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest)
3722 << ATN->getDeclName());
3724 /*NNS=*/nullptr, /*TemplateKeyword=*/false,
3726 return false;
3727 }
3728
3729 if (Diagnose)
3730 Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName();
3731 return true;
3732}
3733
3735 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3736 TemplateTy TemplateD, const IdentifierInfo *TemplateII,
3737 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
3738 ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc,
3739 bool IsCtorOrDtorName, bool IsClassName,
3740 ImplicitTypenameContext AllowImplicitTypename) {
3741 if (SS.isInvalid())
3742 return true;
3743
3744 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3745 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3746
3747 // C++ [temp.res]p3:
3748 // A qualified-id that refers to a type and in which the
3749 // nested-name-specifier depends on a template-parameter (14.6.2)
3750 // shall be prefixed by the keyword typename to indicate that the
3751 // qualified-id denotes a type, forming an
3752 // elaborated-type-specifier (7.1.5.3).
3753 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
3754 // C++2a relaxes some of those restrictions in [temp.res]p5.
3755 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
3757 Diag(SS.getBeginLoc(), diag::warn_cxx17_compat_implicit_typename);
3758 else
3759 Diag(SS.getBeginLoc(), diag::ext_implicit_typename)
3760 << SS.getScopeRep() << TemplateII->getName()
3761 << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename ");
3762 } else
3763 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
3764 << SS.getScopeRep() << TemplateII->getName();
3765
3766 // FIXME: This is not quite correct recovery as we don't transform SS
3767 // into the corresponding dependent form (and we don't diagnose missing
3768 // 'template' keywords within SS as a result).
3769 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3770 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3771 TemplateArgsIn, RAngleLoc);
3772 }
3773
3774 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3775 // it's not actually allowed to be used as a type in most cases. Because
3776 // we annotate it before we know whether it's valid, we have to check for
3777 // this case here.
3778 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
3779 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3780 Diag(TemplateIILoc,
3781 TemplateKWLoc.isInvalid()
3782 ? diag::err_out_of_line_qualified_id_type_names_constructor
3783 : diag::ext_out_of_line_qualified_id_type_names_constructor)
3784 << TemplateII << 0 /*injected-class-name used as template name*/
3785 << 1 /*if any keyword was present, it was 'template'*/;
3786 }
3787 }
3788
3789 TemplateName Template = TemplateD.get();
3790 if (Template.getAsAssumedTemplateName() &&
3791 resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc))
3792 return true;
3793
3794 // Translate the parser's template argument list in our AST format.
3795 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3796 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3797
3798 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3799 assert(SS.getScopeRep() == DTN->getQualifier());
3801 ElaboratedTypeKeyword::None, DTN->getQualifier(), DTN->getIdentifier(),
3802 TemplateArgs.arguments());
3803 // Build type-source information.
3804 TypeLocBuilder TLB;
3809 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3810 SpecTL.setTemplateNameLoc(TemplateIILoc);
3811 SpecTL.setLAngleLoc(LAngleLoc);
3812 SpecTL.setRAngleLoc(RAngleLoc);
3813 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3814 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3816 }
3817
3818 QualType SpecTy = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
3819 if (SpecTy.isNull())
3820 return true;
3821
3822 // Build type-source information.
3823 TypeLocBuilder TLB;
3826 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3827 SpecTL.setTemplateNameLoc(TemplateIILoc);
3828 SpecTL.setLAngleLoc(LAngleLoc);
3829 SpecTL.setRAngleLoc(RAngleLoc);
3830 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3831 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3832
3833 // Create an elaborated-type-specifier containing the nested-name-specifier.
3834 QualType ElTy =
3836 !IsCtorOrDtorName ? SS : CXXScopeSpec(), SpecTy);
3837 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(ElTy);
3839 if (!ElabTL.isEmpty())
3841 return CreateParsedType(ElTy, TLB.getTypeSourceInfo(Context, ElTy));
3842}
3843
3845 TypeSpecifierType TagSpec,
3846 SourceLocation TagLoc,
3847 CXXScopeSpec &SS,
3848 SourceLocation TemplateKWLoc,
3849 TemplateTy TemplateD,
3850 SourceLocation TemplateLoc,
3851 SourceLocation LAngleLoc,
3852 ASTTemplateArgsPtr TemplateArgsIn,
3853 SourceLocation RAngleLoc) {
3854 if (SS.isInvalid())
3855 return TypeResult(true);
3856
3857 TemplateName Template = TemplateD.get();
3858
3859 // Translate the parser's template argument list in our AST format.
3860 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3861 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3862
3863 // Determine the tag kind
3865 ElaboratedTypeKeyword Keyword
3867
3868 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3869 assert(SS.getScopeRep() == DTN->getQualifier());
3871 Keyword, DTN->getQualifier(), DTN->getIdentifier(),
3872 TemplateArgs.arguments());
3873
3874 // Build type-source information.
3875 TypeLocBuilder TLB;
3878 SpecTL.setElaboratedKeywordLoc(TagLoc);
3880 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3881 SpecTL.setTemplateNameLoc(TemplateLoc);
3882 SpecTL.setLAngleLoc(LAngleLoc);
3883 SpecTL.setRAngleLoc(RAngleLoc);
3884 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3885 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3887 }
3888
3889 if (TypeAliasTemplateDecl *TAT =
3890 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3891 // C++0x [dcl.type.elab]p2:
3892 // If the identifier resolves to a typedef-name or the simple-template-id
3893 // resolves to an alias template specialization, the
3894 // elaborated-type-specifier is ill-formed.
3895 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3896 << TAT << NTK_TypeAliasTemplate << llvm::to_underlying(TagKind);
3897 Diag(TAT->getLocation(), diag::note_declared_at);
3898 }
3899
3900 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3901 if (Result.isNull())
3902 return TypeResult(true);
3903
3904 // Check the tag kind
3905 if (const RecordType *RT = Result->getAs<RecordType>()) {
3906 RecordDecl *D = RT->getDecl();
3907
3908 IdentifierInfo *Id = D->getIdentifier();
3909 assert(Id && "templated class must have an identifier");
3910
3912 TagLoc, Id)) {
3913 Diag(TagLoc, diag::err_use_with_wrong_tag)
3914 << Result
3915 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
3916 Diag(D->getLocation(), diag::note_previous_use);
3917 }
3918 }
3919
3920 // Provide source-location information for the template specialization.
3921 TypeLocBuilder TLB;
3924 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3925 SpecTL.setTemplateNameLoc(TemplateLoc);
3926 SpecTL.setLAngleLoc(LAngleLoc);
3927 SpecTL.setRAngleLoc(RAngleLoc);
3928 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3929 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3930
3931 // Construct an elaborated type containing the nested-name-specifier (if any)
3932 // and tag keyword.
3935 ElabTL.setElaboratedKeywordLoc(TagLoc);
3938}
3939
3940static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3941 NamedDecl *PrevDecl,
3944
3946
3948 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3949 switch (Arg.getKind()) {
3957 return false;
3958
3960 QualType Type = Arg.getAsType();
3961 const TemplateTypeParmType *TPT =
3963 return TPT && !Type.hasQualifiers() &&
3964 TPT->getDepth() == Depth && TPT->getIndex() == Index;
3965 }
3966
3968 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3969 if (!DRE || !DRE->getDecl())
3970 return false;
3971 const NonTypeTemplateParmDecl *NTTP =
3972 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3973 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3974 }
3975
3977 const TemplateTemplateParmDecl *TTP =
3978 dyn_cast_or_null<TemplateTemplateParmDecl>(
3980 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3981 }
3982 llvm_unreachable("unexpected kind of template argument");
3983}
3984
3987 if (Params->size() != Args.size())
3988 return false;
3989
3990 unsigned Depth = Params->getDepth();
3991
3992 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3993 TemplateArgument Arg = Args[I];
3994
3995 // If the parameter is a pack expansion, the argument must be a pack
3996 // whose only element is a pack expansion.
3997 if (Params->getParam(I)->isParameterPack()) {
3998 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
3999 !Arg.pack_begin()->isPackExpansion())
4000 return false;
4001 Arg = Arg.pack_begin()->getPackExpansionPattern();
4002 }
4003
4004 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
4005 return false;
4006 }
4007
4008 return true;
4009}
4010
4011template<typename PartialSpecDecl>
4012static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4013 if (Partial->getDeclContext()->isDependentContext())
4014 return;
4015
4016 // FIXME: Get the TDK from deduction in order to provide better diagnostics
4017 // for non-substitution-failure issues?
4018 TemplateDeductionInfo Info(Partial->getLocation());
4019 if (S.isMoreSpecializedThanPrimary(Partial, Info))
4020 return;
4021
4022 auto *Template = Partial->getSpecializedTemplate();
4023 S.Diag(Partial->getLocation(),
4024 diag::ext_partial_spec_not_more_specialized_than_primary)
4025 << isa<VarTemplateDecl>(Template);
4026
4027 if (Info.hasSFINAEDiagnostic()) {
4031 SmallString<128> SFINAEArgString;
4032 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
4033 S.Diag(Diag.first,
4034 diag::note_partial_spec_not_more_specialized_than_primary)
4035 << SFINAEArgString;
4036 }
4037
4038 S.NoteTemplateLocation(*Template);
4039 SmallVector<const Expr *, 3> PartialAC, TemplateAC;
4040 Template->getAssociatedConstraints(TemplateAC);
4041 Partial->getAssociatedConstraints(PartialAC);
4042 S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Partial, PartialAC, Template,
4043 TemplateAC);
4044}
4045
4046static void
4048 const llvm::SmallBitVector &DeducibleParams) {
4049 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4050 if (!DeducibleParams[I]) {
4051 NamedDecl *Param = TemplateParams->getParam(I);
4052 if (Param->getDeclName())
4053 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4054 << Param->getDeclName();
4055 else
4056 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4057 << "(anonymous)";
4058 }
4059 }
4060}
4061
4062
4063template<typename PartialSpecDecl>
4065 PartialSpecDecl *Partial) {
4066 // C++1z [temp.class.spec]p8: (DR1495)
4067 // - The specialization shall be more specialized than the primary
4068 // template (14.5.5.2).
4070
4071 // C++ [temp.class.spec]p8: (DR1315)
4072 // - Each template-parameter shall appear at least once in the
4073 // template-id outside a non-deduced context.
4074 // C++1z [temp.class.spec.match]p3 (P0127R2)
4075 // If the template arguments of a partial specialization cannot be
4076 // deduced because of the structure of its template-parameter-list
4077 // and the template-id, the program is ill-formed.
4078 auto *TemplateParams = Partial->getTemplateParameters();
4079 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4080 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4081 TemplateParams->getDepth(), DeducibleParams);
4082
4083 if (!DeducibleParams.all()) {
4084 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4085 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4086 << isa<VarTemplatePartialSpecializationDecl>(Partial)
4087 << (NumNonDeducible > 1)
4088 << SourceRange(Partial->getLocation(),
4089 Partial->getTemplateArgsAsWritten()->RAngleLoc);
4090 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4091 }
4092}
4093
4096 checkTemplatePartialSpecialization(*this, Partial);
4097}
4098
4101 checkTemplatePartialSpecialization(*this, Partial);
4102}
4103
4105 // C++1z [temp.param]p11:
4106 // A template parameter of a deduction guide template that does not have a
4107 // default-argument shall be deducible from the parameter-type-list of the
4108 // deduction guide template.
4109 auto *TemplateParams = TD->getTemplateParameters();
4110 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4111 MarkDeducedTemplateParameters(TD, DeducibleParams);
4112 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4113 // A parameter pack is deducible (to an empty pack).
4114 auto *Param = TemplateParams->getParam(I);
4115 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
4116 DeducibleParams[I] = true;
4117 }
4118
4119 if (!DeducibleParams.all()) {
4120 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4121 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
4122 << (NumNonDeducible > 1);
4123 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
4124 }
4125}
4126
4129 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
4131 // D must be variable template id.
4132 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
4133 "Variable template specialization is declared with a template id.");
4134
4135 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4136 TemplateArgumentListInfo TemplateArgs =
4137 makeTemplateArgumentListInfo(*this, *TemplateId);
4138 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4139 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4140 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4141
4142 TemplateName Name = TemplateId->Template.get();
4143
4144 // The template-id must name a variable template.
4146 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
4147 if (!VarTemplate) {
4148 NamedDecl *FnTemplate;
4149 if (auto *OTS = Name.getAsOverloadedTemplate())
4150 FnTemplate = *OTS->begin();
4151 else
4152 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4153 if (FnTemplate)
4154 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
4155 << FnTemplate->getDeclName();
4156 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
4158 }
4159
4160 if (const auto *DSA = VarTemplate->getAttr<NoSpecializationsAttr>()) {
4161 auto Message = DSA->getMessage();
4162 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
4163 << VarTemplate << !Message.empty() << Message;
4164 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
4165 }
4166
4167 // Check for unexpanded parameter packs in any of the template arguments.
4168 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4169 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4173 return true;
4174
4175 // Check that the template argument list is well-formed for this
4176 // template.
4177 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4178 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
4179 /*DefaultArgs=*/{}, false, SugaredConverted,
4180 CanonicalConverted,
4181 /*UpdateArgsWithConversions=*/true))
4182 return true;
4183
4184 // Find the variable template (partial) specialization declaration that
4185 // corresponds to these arguments.
4188 TemplateArgs.size(),
4189 CanonicalConverted))
4190 return true;
4191
4192 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
4193 // also do them during instantiation.
4194 if (!Name.isDependent() &&
4196 TemplateArgs, CanonicalConverted)) {
4197 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4198 << VarTemplate->getDeclName();
4200 }
4201
4202 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
4203 CanonicalConverted) &&
4204 (!Context.getLangOpts().CPlusPlus20 ||
4205 !TemplateParams->hasAssociatedConstraints())) {
4206 // C++ [temp.class.spec]p9b3:
4207 //
4208 // -- The argument list of the specialization shall not be identical
4209 // to the implicit argument list of the primary template.
4210 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4211 << /*variable template*/ 1
4212 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
4213 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4214 // FIXME: Recover from this by treating the declaration as a redeclaration
4215 // of the primary template.
4216 return true;
4217 }
4218 }
4219
4220 void *InsertPos = nullptr;
4221 VarTemplateSpecializationDecl *PrevDecl = nullptr;
4222
4224 PrevDecl = VarTemplate->findPartialSpecialization(
4225 CanonicalConverted, TemplateParams, InsertPos);
4226 else
4227 PrevDecl = VarTemplate->findSpecialization(CanonicalConverted, InsertPos);
4228
4230
4231 // Check whether we can declare a variable template specialization in
4232 // the current scope.
4233 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
4234 TemplateNameLoc,
4236 return true;
4237
4238 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4239 // Since the only prior variable template specialization with these
4240 // arguments was referenced but not declared, reuse that
4241 // declaration node as our own, updating its source location and
4242 // the list of outer template parameters to reflect our new declaration.
4243 Specialization = PrevDecl;
4244 Specialization->setLocation(TemplateNameLoc);
4245 PrevDecl = nullptr;
4246 } else if (IsPartialSpecialization) {
4247 // Create a new class template partial specialization declaration node.
4249 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
4252 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
4253 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
4254 CanonicalConverted);
4255 Partial->setTemplateArgsAsWritten(TemplateArgs);
4256
4257 if (!PrevPartial)
4258 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
4259 Specialization = Partial;
4260
4261 // If we are providing an explicit specialization of a member variable
4262 // template specialization, make a note of that.
4263 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4264 PrevPartial->setMemberSpecialization();
4265
4267 } else {
4268 // Create a new class template specialization declaration node for
4269 // this explicit specialization or friend declaration.
4271 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4272 VarTemplate, DI->getType(), DI, SC, CanonicalConverted);
4273 Specialization->setTemplateArgsAsWritten(TemplateArgs);
4274
4275 if (!PrevDecl)
4276 VarTemplate->AddSpecialization(Specialization, InsertPos);
4277 }
4278
4279 // C++ [temp.expl.spec]p6:
4280 // If a template, a member template or the member of a class template is
4281 // explicitly specialized then that specialization shall be declared
4282 // before the first use of that specialization that would cause an implicit
4283 // instantiation to take place, in every translation unit in which such a
4284 // use occurs; no diagnostic is required.
4285 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4286 bool Okay = false;
4287 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4288 // Is there any previous explicit specialization declaration?
4290 Okay = true;
4291 break;
4292 }
4293 }
4294
4295 if (!Okay) {
4296 SourceRange Range(TemplateNameLoc, RAngleLoc);
4297 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4298 << Name << Range;
4299
4300 Diag(PrevDecl->getPointOfInstantiation(),
4301 diag::note_instantiation_required_here)
4302 << (PrevDecl->getTemplateSpecializationKind() !=
4304 return true;
4305 }
4306 }
4307
4308 Specialization->setLexicalDeclContext(CurContext);
4309
4310 // Add the specialization into its lexical context, so that it can
4311 // be seen when iterating through the list of declarations in that
4312 // context. However, specializations are not found by name lookup.
4314
4315 // Note that this is an explicit specialization.
4316 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4317
4318 Previous.clear();
4319 if (PrevDecl)
4320 Previous.addDecl(PrevDecl);
4321 else if (Specialization->isStaticDataMember() &&
4322 Specialization->isOutOfLine())
4323 Specialization->setAccess(VarTemplate->getAccess());
4324
4325 return Specialization;
4326}
4327
4328namespace {
4329/// A partial specialization whose template arguments have matched
4330/// a given template-id.
4331struct PartialSpecMatchResult {
4334};
4335} // end anonymous namespace
4336
4339 SourceLocation TemplateNameLoc,
4340 const TemplateArgumentListInfo &TemplateArgs) {
4341 assert(Template && "A variable template id without template?");
4342
4343 // Check that the template argument list is well-formed for this template.
4344 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4346 Template, TemplateNameLoc,
4347 const_cast<TemplateArgumentListInfo &>(TemplateArgs),
4348 /*DefaultArgs=*/{}, false, SugaredConverted, CanonicalConverted,
4349 /*UpdateArgsWithConversions=*/true))
4350 return true;
4351
4352 // Produce a placeholder value if the specialization is dependent.
4353 if (Template->getDeclContext()->isDependentContext() ||
4355 TemplateArgs, CanonicalConverted))
4356 return DeclResult();
4357
4358 // Find the variable template specialization declaration that
4359 // corresponds to these arguments.
4360 void *InsertPos = nullptr;
4362 Template->findSpecialization(CanonicalConverted, InsertPos)) {
4363 checkSpecializationReachability(TemplateNameLoc, Spec);
4364 // If we already have a variable template specialization, return it.
4365 return Spec;
4366 }
4367
4368 // This is the first time we have referenced this variable template
4369 // specialization. Create the canonical declaration and add it to
4370 // the set of specializations, based on the closest partial specialization
4371 // that it represents. That is,
4372 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4373 const TemplateArgumentList *PartialSpecArgs = nullptr;
4374 bool AmbiguousPartialSpec = false;
4375 typedef PartialSpecMatchResult MatchResult;
4377 SourceLocation PointOfInstantiation = TemplateNameLoc;
4378 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4379 /*ForTakingAddress=*/false);
4380
4381 // 1. Attempt to find the closest partial specialization that this
4382 // specializes, if any.
4383 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4384 // Perhaps better after unification of DeduceTemplateArguments() and
4385 // getMoreSpecializedPartialSpecialization().
4387 Template->getPartialSpecializations(PartialSpecs);
4388
4389 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4390 // C++ [temp.spec.partial.member]p2:
4391 // If the primary member template is explicitly specialized for a given
4392 // (implicit) specialization of the enclosing class template, the partial
4393 // specializations of the member template are ignored for this
4394 // specialization of the enclosing class template. If a partial
4395 // specialization of the member template is explicitly specialized for a
4396 // given (implicit) specialization of the enclosing class template, the
4397 // primary member template and its other partial specializations are still
4398 // considered for this specialization of the enclosing class template.
4399 if (Template->getMostRecentDecl()->isMemberSpecialization() &&
4400 !Partial->getMostRecentDecl()->isMemberSpecialization())
4401 continue;
4402
4403 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4404
4406 DeduceTemplateArguments(Partial, SugaredConverted, Info);
4408 // Store the failed-deduction information for use in diagnostics, later.
4409 // TODO: Actually use the failed-deduction info?
4410 FailedCandidates.addCandidate().set(
4411 DeclAccessPair::make(Template, AS_public), Partial,
4413 (void)Result;
4414 } else {
4415 Matched.push_back(PartialSpecMatchResult());
4416 Matched.back().Partial = Partial;
4417 Matched.back().Args = Info.takeSugared();
4418 }
4419 }
4420
4421 if (Matched.size() >= 1) {
4422 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4423 if (Matched.size() == 1) {
4424 // -- If exactly one matching specialization is found, the
4425 // instantiation is generated from that specialization.
4426 // We don't need to do anything for this.
4427 } else {
4428 // -- If more than one matching specialization is found, the
4429 // partial order rules (14.5.4.2) are used to determine
4430 // whether one of the specializations is more specialized
4431 // than the others. If none of the specializations is more
4432 // specialized than all of the other matching
4433 // specializations, then the use of the variable template is
4434 // ambiguous and the program is ill-formed.
4436 PEnd = Matched.end();
4437 P != PEnd; ++P) {
4438 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4439 PointOfInstantiation) ==
4440 P->Partial)
4441 Best = P;
4442 }
4443
4444 // Determine if the best partial specialization is more specialized than
4445 // the others.
4446 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4447 PEnd = Matched.end();
4448 P != PEnd; ++P) {
4450 P->Partial, Best->Partial,
4451 PointOfInstantiation) != Best->Partial) {
4452 AmbiguousPartialSpec = true;
4453 break;
4454 }
4455 }
4456 }
4457
4458 // Instantiate using the best variable template partial specialization.
4459 InstantiationPattern = Best->Partial;
4460 PartialSpecArgs = Best->Args;
4461 } else {
4462 // -- If no match is found, the instantiation is generated
4463 // from the primary template.
4464 // InstantiationPattern = Template->getTemplatedDecl();
4465 }
4466
4467 // 2. Create the canonical declaration.
4468 // Note that we do not instantiate a definition until we see an odr-use
4469 // in DoMarkVarDeclReferenced().
4470 // FIXME: LateAttrs et al.?
4472 Template, InstantiationPattern, PartialSpecArgs, TemplateArgs,
4473 CanonicalConverted, TemplateNameLoc /*, LateAttrs, StartingScope*/);
4474 if (!Decl)
4475 return true;
4476
4477 if (AmbiguousPartialSpec) {
4478 // Partial ordering did not produce a clear winner. Complain.
4480 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4481 << Decl;
4482
4483 // Print the matching partial specializations.
4484 for (MatchResult P : Matched)
4485 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4486 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4487 *P.Args);
4488 return true;
4489 }
4490
4492 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4493 Decl->setInstantiationOf(D, PartialSpecArgs);
4494
4495 checkSpecializationReachability(TemplateNameLoc, Decl);
4496
4497 assert(Decl && "No variable template specialization?");
4498 return Decl;
4499}
4500
4502 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4503 VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
4504 const TemplateArgumentListInfo *TemplateArgs) {
4505
4506 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4507 *TemplateArgs);
4508 if (Decl.isInvalid())
4509 return ExprError();
4510
4511 if (!Decl.get())
4512 return ExprResult();
4513
4514 VarDecl *Var = cast<VarDecl>(Decl.get());
4517 NameInfo.getLoc());
4518
4519 // Build an ordinary singleton decl ref.
4520 return BuildDeclarationNameExpr(SS, NameInfo, Var, FoundD, TemplateArgs);
4521}
4522
4525 Diag(Loc, diag::err_template_missing_args)
4526 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4527 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4528 NoteTemplateLocation(*TD, TD->getTemplateParameters()->getSourceRange());
4529 }
4530}
4531
4533 bool TemplateKeyword,
4534 TemplateDecl *TD,
4537 SS.getScopeRep(), TemplateKeyword, TemplateName(TD));
4539}
4540
4543 SourceLocation TemplateKWLoc,
4544 const DeclarationNameInfo &ConceptNameInfo,
4545 NamedDecl *FoundDecl,
4546 ConceptDecl *NamedConcept,
4547 const TemplateArgumentListInfo *TemplateArgs) {
4548 assert(NamedConcept && "A concept template id without a template?");
4549
4550 llvm::SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4552 NamedConcept, ConceptNameInfo.getLoc(),
4553 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4554 /*DefaultArgs=*/{},
4555 /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted,
4556 /*UpdateArgsWithConversions=*/false))
4557 return ExprError();
4558
4559 DiagnoseUseOfDecl(NamedConcept, ConceptNameInfo.getLoc());
4560
4562 Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(),
4563 CanonicalConverted);
4564 ConstraintSatisfaction Satisfaction;
4565 bool AreArgsDependent =
4567 *TemplateArgs, CanonicalConverted);
4568 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CanonicalConverted,
4569 /*Final=*/false);
4571
4574
4575 if (!AreArgsDependent &&
4577 NamedConcept, {NamedConcept->getConstraintExpr()}, MLTAL,
4578 SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4579 TemplateArgs->getRAngleLoc()),
4580 Satisfaction))
4581 return ExprError();
4582 auto *CL = ConceptReference::Create(
4583 Context,
4585 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
4588 Context, CL, CSD, AreArgsDependent ? nullptr : &Satisfaction);
4589}
4590
4592 SourceLocation TemplateKWLoc,
4593 LookupResult &R,
4594 bool RequiresADL,
4595 const TemplateArgumentListInfo *TemplateArgs) {
4596 // FIXME: Can we do any checking at this point? I guess we could check the
4597 // template arguments that we have against the template name, if the template
4598 // name refers to a single template. That's not a terribly common case,
4599 // though.
4600 // foo<int> could identify a single function unambiguously
4601 // This approach does NOT work, since f<int>(1);
4602 // gets resolved prior to resorting to overload resolution
4603 // i.e., template<class T> void f(double);
4604 // vs template<class T, class U> void f(U);
4605
4606 // These should be filtered out by our callers.
4607 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4608
4609 // Non-function templates require a template argument list.
4610 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4611 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4613 SS, /*TemplateKeyword=*/TemplateKWLoc.isValid(), TD, R.getNameLoc());
4614 return ExprError();
4615 }
4616 }
4617 bool KnownDependent = false;
4618 // In C++1y, check variable template ids.
4619 if (R.getAsSingle<VarTemplateDecl>()) {
4622 R.getRepresentativeDecl(), TemplateKWLoc, TemplateArgs);
4623 if (Res.isInvalid() || Res.isUsable())
4624 return Res;
4625 // Result is dependent. Carry on to build an UnresolvedLookupExpr.
4626 KnownDependent = true;
4627 }
4628
4629 if (R.getAsSingle<ConceptDecl>()) {
4630 return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
4632 R.getAsSingle<ConceptDecl>(), TemplateArgs);
4633 }
4634
4635 // We don't want lookup warnings at this point.
4637
4640 TemplateKWLoc, R.getLookupNameInfo(), RequiresADL, TemplateArgs,
4641 R.begin(), R.end(), KnownDependent,
4642 /*KnownInstantiationDependent=*/false);
4643
4644 // Model the templates with UnresolvedTemplateTy. The expression should then
4645 // either be transformed in an instantiation or be diagnosed in
4646 // CheckPlaceholderExpr.
4647 if (ULE->getType() == Context.OverloadTy && R.isSingleResult() &&
4650
4651 return ULE;
4652}
4653
4655 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4656 const DeclarationNameInfo &NameInfo,
4657 const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand) {
4658 assert(TemplateArgs || TemplateKWLoc.isValid());
4659
4660 LookupResult R(*this, NameInfo, LookupOrdinaryName);
4661 if (LookupTemplateName(R, /*S=*/nullptr, SS, /*ObjectType=*/QualType(),
4662 /*EnteringContext=*/false, TemplateKWLoc))
4663 return ExprError();
4664
4665 if (R.isAmbiguous())
4666 return ExprError();
4667
4669 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
4670
4671 if (R.empty()) {
4673 Diag(NameInfo.getLoc(), diag::err_no_member)
4674 << NameInfo.getName() << DC << SS.getRange();
4675 return ExprError();
4676 }
4677
4678 // If necessary, build an implicit class member access.
4679 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
4680 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
4681 /*S=*/nullptr);
4682
4683 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL=*/false, TemplateArgs);
4684}
4685
4687 CXXScopeSpec &SS,
4688 SourceLocation TemplateKWLoc,
4689 const UnqualifiedId &Name,
4690 ParsedType ObjectType,
4691 bool EnteringContext,
4693 bool AllowInjectedClassName) {
4694 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
4695 Diag(TemplateKWLoc,
4697 diag::warn_cxx98_compat_template_outside_of_template :
4698 diag::ext_template_outside_of_template)
4699 << FixItHint::CreateRemoval(TemplateKWLoc);
4700
4701 if (SS.isInvalid())
4702 return TNK_Non_template;
4703
4704 // Figure out where isTemplateName is going to look.
4705 DeclContext *LookupCtx = nullptr;
4706 if (SS.isNotEmpty())
4707 LookupCtx = computeDeclContext(SS, EnteringContext);
4708 else if (ObjectType)
4709 LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));
4710
4711 // C++0x [temp.names]p5:
4712 // If a name prefixed by the keyword template is not the name of
4713 // a template, the program is ill-formed. [Note: the keyword
4714 // template may not be applied to non-template members of class
4715 // templates. -end note ] [ Note: as is the case with the
4716 // typename prefix, the template prefix is allowed in cases
4717 // where it is not strictly necessary; i.e., when the
4718 // nested-name-specifier or the expression on the left of the ->
4719 // or . is not dependent on a template-parameter, or the use
4720 // does not appear in the scope of a template. -end note]
4721 //
4722 // Note: C++03 was more strict here, because it banned the use of
4723 // the "template" keyword prior to a template-name that was not a
4724 // dependent name. C++ DR468 relaxed this requirement (the
4725 // "template" keyword is now permitted). We follow the C++0x
4726 // rules, even in C++03 mode with a warning, retroactively applying the DR.
4727 bool MemberOfUnknownSpecialization;
4728 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
4729 ObjectType, EnteringContext, Result,
4730 MemberOfUnknownSpecialization);
4731 if (TNK != TNK_Non_template) {
4732 // We resolved this to a (non-dependent) template name. Return it.
4733 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
4734 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
4735 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
4736 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
4737 // C++14 [class.qual]p2:
4738 // In a lookup in which function names are not ignored and the
4739 // nested-name-specifier nominates a class C, if the name specified
4740 // [...] is the injected-class-name of C, [...] the name is instead
4741 // considered to name the constructor
4742 //
4743 // We don't get here if naming the constructor would be valid, so we
4744 // just reject immediately and recover by treating the
4745 // injected-class-name as naming the template.
4746 Diag(Name.getBeginLoc(),
4747 diag::ext_out_of_line_qualified_id_type_names_constructor)
4748 << Name.Identifier
4749 << 0 /*injected-class-name used as template name*/
4750 << TemplateKWLoc.isValid();
4751 }
4752 return TNK;
4753 }
4754
4755 if (!MemberOfUnknownSpecialization) {
4756 // Didn't find a template name, and the lookup wasn't dependent.
4757 // Do the lookup again to determine if this is a "nothing found" case or
4758 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
4759 // need to do this.
4761 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
4763 // Tell LookupTemplateName that we require a template so that it diagnoses
4764 // cases where it finds a non-template.
4765 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
4766 ? RequiredTemplateKind(TemplateKWLoc)
4768 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, RTK,
4769 /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) &&
4770 !R.isAmbiguous()) {
4771 if (LookupCtx)
4772 Diag(Name.getBeginLoc(), diag::err_no_member)
4773 << DNI.getName() << LookupCtx << SS.getRange();
4774 else
4775 Diag(Name.getBeginLoc(), diag::err_undeclared_use)
4776 << DNI.getName() << SS.getRange();
4777 }
4778 return TNK_Non_template;
4779 }
4780
4781 NestedNameSpecifier *Qualifier = SS.getScopeRep();
4782
4783 switch (Name.getKind()) {
4786 Context.getDependentTemplateName(Qualifier, Name.Identifier));
4788
4791 Qualifier, Name.OperatorFunctionId.Operator));
4792 return TNK_Function_template;
4793
4795 // This is a kind of template name, but can never occur in a dependent
4796 // scope (literal operators can only be declared at namespace scope).
4797 break;
4798
4799 default:
4800 break;
4801 }
4802
4803 // This name cannot possibly name a dependent template. Diagnose this now
4804 // rather than building a dependent template name that can never be valid.
4805 Diag(Name.getBeginLoc(),
4806 diag::err_template_kw_refers_to_dependent_non_template)
4807 << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
4808 << TemplateKWLoc.isValid() << TemplateKWLoc;
4809 return TNK_Non_template;
4810}
4811
4814 SmallVectorImpl<TemplateArgument> &SugaredConverted,
4815 SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
4816 const TemplateArgument &Arg = AL.getArgument();
4817 QualType ArgType;
4818 TypeSourceInfo *TSI = nullptr;
4819
4820 // Check template type parameter.
4821 switch(Arg.getKind()) {
4823 // C++ [temp.arg.type]p1:
4824 // A template-argument for a template-parameter which is a
4825 // type shall be a type-id.
4826 ArgType = Arg.getAsType();
4827 TSI = AL.getTypeSourceInfo();
4828 break;
4831 // We have a template type parameter but the template argument
4832 // is a template without any arguments.
4833 SourceRange SR = AL.getSourceRange();
4836 return true;
4837 }
4839 // We have a template type parameter but the template argument is an
4840 // expression; see if maybe it is missing the "typename" keyword.
4841 CXXScopeSpec SS;
4842 DeclarationNameInfo NameInfo;
4843
4844 if (DependentScopeDeclRefExpr *ArgExpr =
4845 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
4846 SS.Adopt(ArgExpr->getQualifierLoc());
4847 NameInfo = ArgExpr->getNameInfo();
4848 } else if (CXXDependentScopeMemberExpr *ArgExpr =
4849 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
4850 if (ArgExpr->isImplicitAccess()) {
4851 SS.Adopt(ArgExpr->getQualifierLoc());
4852 NameInfo = ArgExpr->getMemberNameInfo();
4853 }
4854 }
4855
4856 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
4857 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
4858 LookupParsedName(Result, CurScope, &SS, /*ObjectType=*/QualType());
4859
4860 if (Result.getAsSingle<TypeDecl>() ||
4861 Result.wasNotFoundInCurrentInstantiation()) {
4862 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
4863 // Suggest that the user add 'typename' before the NNS.
4865 Diag(Loc, getLangOpts().MSVCCompat
4866 ? diag::ext_ms_template_type_arg_missing_typename
4867 : diag::err_template_arg_must_be_type_suggest)
4868 << FixItHint::CreateInsertion(Loc, "typename ");
4870
4871 // Recover by synthesizing a type using the location information that we
4872 // already have.
4874 SS.getScopeRep(), II);
4875 TypeLocBuilder TLB;
4877 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
4879 TL.setNameLoc(NameInfo.getLoc());
4880 TSI = TLB.getTypeSourceInfo(Context, ArgType);
4881
4882 // Overwrite our input TemplateArgumentLoc so that we can recover
4883 // properly.
4886
4887 break;
4888 }
4889 }
4890 // fallthrough
4891 [[fallthrough]];
4892 }
4893 default: {
4894 // We allow instantiateing a template with template argument packs when
4895 // building deduction guides.
4896 if (Arg.getKind() == TemplateArgument::Pack &&
4897 CodeSynthesisContexts.back().Kind ==
4899 SugaredConverted.push_back(Arg);
4900 CanonicalConverted.push_back(Arg);
4901 return false;
4902 }
4903 // We have a template type parameter but the template argument
4904 // is not a type.
4905 SourceRange SR = AL.getSourceRange();
4906 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
4908
4909 return true;
4910 }
4911 }
4912
4913 if (CheckTemplateArgument(TSI))
4914 return true;
4915
4916 // Objective-C ARC:
4917 // If an explicitly-specified template argument type is a lifetime type
4918 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
4919 if (getLangOpts().ObjCAutoRefCount &&
4920 ArgType->isObjCLifetimeType() &&
4921 !ArgType.getObjCLifetime()) {
4922 Qualifiers Qs;
4924 ArgType = Context.getQualifiedType(ArgType, Qs);
4925 }
4926
4927 SugaredConverted.push_back(TemplateArgument(ArgType));
4928 CanonicalConverted.push_back(
4930 return false;
4931}
4932
4933/// Substitute template arguments into the default template argument for
4934/// the given template type parameter.
4935///
4936/// \param SemaRef the semantic analysis object for which we are performing
4937/// the substitution.
4938///
4939/// \param Template the template that we are synthesizing template arguments
4940/// for.
4941///
4942/// \param TemplateLoc the location of the template name that started the
4943/// template-id we are checking.
4944///
4945/// \param RAngleLoc the location of the right angle bracket ('>') that
4946/// terminates the template-id.
4947///
4948/// \param Param the template template parameter whose default we are
4949/// substituting into.
4950///
4951/// \param Converted the list of template arguments provided for template
4952/// parameters that precede \p Param in the template parameter list.
4953///
4954/// \param Output the resulting substituted template argument.
4955///
4956/// \returns true if an error occurred.
4958 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
4959 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,