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